@flopay/react 1.9.21 → 1.9.22
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 +7 -0
- package/dist/index.cjs +9 -9
- package/dist/index.d.cts +9 -3
- package/dist/index.d.ts +9 -3
- package/dist/index.mjs +8 -8
- package/package.json +3 -3
package/dist/index.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import{a as Bt,b as fr,c as Uo,d as si,e as qo,f as zs,g as Us,h as hc,i as vc}from"./chunk-CSBYK62Y.mjs";import{dropThirdPartyOnlyError as Xm}from"@flopay/shared";import{PaymentAPI as is}from"@flopay/js";import{FloPayError as ia,resolveBillingApiUrl as Au,resolveButtonsLayoutTheme as xu,resolveTheme as Mu}from"@flopay/shared";import{useCallback as Rr,useEffect as _o,useMemo as oa,useRef as Ro,useState as aa}from"react";import{Fragment as co,jsx as Qn,jsxs as qs}from"react/jsx-runtime";function Pc(){return qs(co,{children:[qs("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:[Qn("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),Qn("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",Qn("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:Qn("path",{d:"M9 18l6-6-6-6"})})]})}function bc(){return Qn(co,{children:"Go back"})}function Cc(){return Qn(co,{children:"Secure card checkout"})}function io(e){return e!==void 0&&(e===""||e===null||e===!1)}function so({content:e}){return Qn(co,{children:e===void 0?Qn(Pc,{}):e})}function lo({content:e}){return Qn(co,{children:e===void 0?Qn(bc,{}):e})}function jo({content:e}){return Qn(co,{children:e===void 0?Qn(Cc,{}):e})}import{classifyTelemetryFailure as Sc,FloPayError as jn,isCardHolderNamePlaceholder as js,isMoneySettledOutcome as wc,isSetupIntentClientSecret as Ic,isValidEmail as kc}from"@flopay/shared";var _c="Checkout is temporarily unavailable. Please try again later.";function li(e){return{errorCode:"PROVIDER_LOAD_FAILED",failureCategory:e instanceof jn&&e.type==="authentication_error"?"invalid_response":"provider_runtime",stage:"provider_load",provider:"stripe",requestCategory:"provider_sdk"}}function Rc(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 $s(){return new jn(_c,"api_error",{code:"CheckoutInitializationFailed"})}function ci(e){return!!e?.gateways?.worldpayCorporateGateway}function Ar(e){return e?.status==="open"&&ci(e)}function Ks(e,t,n){let r=e?.data.session,o=r?.gateways?.stripe?.enabledPaymentMethods??e?.data.stripe?.enabledPaymentMethods;return!!(n&&(r?.vault?.html||r?.gateways?.pcivault||o?.includes("card")||Ar(r))||t&&e?.data.paypal?.publishableKey)}function Vs(e,t){if(t&&(!(e instanceof jn)||e.type==="authentication_error"))return li(e);if(!(e instanceof jn&&Rc(e))){if(!t&&!(e instanceof jn)&&(e instanceof TypeError||e instanceof SyntaxError))return{...Sc(e,"NETWORK_REQUEST_FAILED"),stage:"session_read",requestCategory:"session_read"};if(!t&&e instanceof jn)return{errorCode:"NETWORK_REQUEST_FAILED",stage:"session_read",requestCategory:"session_read"};if(!(e instanceof jn))return{errorCode:"INTERNAL_SDK_ERROR",stage:"checkout_mount"}}}function uo(e,t,n,r={}){let o;return(i={})=>{if(o)return o;let s={...r,...i,email:i.email?.trim()||r.email?.trim()},l=js(s.firstName,s.lastName);if(!kc(s.email))return Promise.reject(new jn("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}));let p={};for(let[f,C]of Object.entries(s)){if(l&&f.endsWith("Name")||typeof C!="string")continue;let h=C.trim();h&&(p[f]=h)}return o=e.claimCheckoutSession(t,n,{accountData:p}),o.catch(()=>{}),o}}function Hs(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 Ws(e,t){let n=e.products??[...(e.subscriptions??[]).map(i=>({type:"subscription",code:i.code??i.providerPlanId,name:i.subscriptionName??i.providerPlanName??i.code??i.providerPlanId??null,quantity:i.quantity??1,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount,currency:i.currency,metadata:i.metadata})),...(e.items??[]).map(i=>({type:"item",code:i.code??i.providerItemId,name:i.itemName??i.providerItemName??i.code??i.providerItemId??null,quantity:i.quantity??1,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount,currency:i.currency,metadata:i.metadata}))],r=n.reduce((i,s)=>i+(s.overrideAmount??s.totalAmount??0),0),o=e.currency??n.find(i=>i.currency)?.currency??"USD";return{id:"",clientSecret:"",mode:n.some(i=>i.type==="subscription")?"subscription":"payment",amount:Math.round(r*100),currency:o,status:"open",captureMethod:e.captureMethod,customer:{id:e.account.userId,email:e.account.email??"",firstName:e.account.firstName,lastName:e.account.lastName,gender:e.account.gender??void 0,city:e.account.city??void 0,state:e.account.state??void 0,country:e.account.country??void 0,zip:e.account.zip??void 0},successUrl:e.successUrl,cancelUrl:e.cancelUrl,checkoutMode:t??e.checkoutMode??"full",products:n.map((i,s)=>({uuid:`synthetic-${i.type??"item"}-${s}`,checkoutSessionId:"",type:i.type??"item",code:i.code,name:i.name??null,quantity:i.quantity??1,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount??null,currency:i.currency??o,metadata:i.metadata??null}))}}function Vr(e){if(js(e))return{};let[t,...n]=e?.trim().split(/\s+/)??[];return t?{firstName:t,lastName:n.join(" ")||void 0}:{}}function ui(e,t){return t?{...e,...t}:e}function nn(e,t,n){let r=typeof t=="string"?t:t.message,o=typeof t=="string"?n?.code:n?.code??t.code,i=typeof t=="string"?n?.declineCode:n?.declineCode??t.declineCode;return{method:e,message:r,...o?{code:o}:{},...i?{declineCode:i}:{}}}var Ec=[{match:/^paypal authorization required\.?$/i,replacement:"For your additional security, please re-authenticate this payment via PayPal."}];function xr(e){if(typeof e!="string")return e??void 0;let t=e.trim();if(!t)return e;for(let{match:n,replacement:r}of Ec)if(n.test(t))return r;return e}function Sr(e,t){return e.status!=="authorized"?{status:"succeeded"}:{status:"authorized",paymentId:e.paymentId,sessionId:e.id||t||void 0,authorizationExpiresAt:e.authorizationExpiresAt}}function Mr(e){return e?.status==="authorized"||e?.status==="complete"}function Gs(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function ha(e){let t=Gs(e);return new jn(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function va(e){return e instanceof jn||typeof e=="object"&&e!==null&&"code"in e?e.code:void 0}function po(e){let t=Gs(e),n="checkout_processing_timeout";return t?n="authorization_expired":e?.status==="expired"&&(n="checkout_session_expired"),new jn(t?"Authorization has expired.":"Automatic payment failed. Please try again.","api_error",{code:n})}function $o(e,t){return e==="processing"||wc(e,t)}function Ys(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}async function Js(e,t){let n=e;if(Ic(t)){if(!n?.retrieveSetupIntent)return null;let{setupIntent:i,error:s}=await n.retrieveSetupIntent(t);if(s)throw new jn(s.message??"Failed to retrieve setup intent.","api_error",{...s.code?{code:s.code}:{}});return i??null}if(!n?.retrievePaymentIntent)return null;let{paymentIntent:r,error:o}=await n.retrievePaymentIntent(t);if(o)throw new jn(o.message??"Failed to retrieve payment intent.","api_error",{...o.code?{code:o.code}:{}});return r??null}function Xs(e,t="automatic"){return{...typeof e=="number"&&Number.isFinite(e)&&e>0?{mode:"payment",amount:e,captureMethod:t==="manual"?"manual":"automatic_async"}:{mode:"setup"},paymentMethodTypes:["card"],setupFutureUsage:"off_session"}}function pi(e){let t=e&&typeof e=="object"?e:null;return t?.name==="IntegrationError"||t?.code==="elements_intent_mismatch"||t?.type==="invalid_request_error"?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response"}:{errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime"}}function Ko(e){let t=[e?.id,e?.originalPaymentMethodId];for(let n of t)if(typeof n=="string"&&n.startsWith("pm_"))return n}import{FloPay as yu,PaymentAPI as Ua,SESSION_CREATE_TELEMETRY as fu}from"@flopay/js";import{buildCheckoutDisplayData as gu,classifyTelemetryFailure as Gl,FloPayError as bn,isDetachedSessionEligible as hu,resolveBillingApiUrl as vu,resolveButtonsLayoutTheme as Pu,resolveIdempotencyKey as ql,resolveTheme as Yl,SDK_VERSION as Jl,telemetryStatusClass as bu}from"@flopay/shared";import Xi,{useCallback as Pn,useEffect as ur,useMemo as tr,useRef as Rt,useState as jt}from"react";import{createContext as Zs}from"react";var er=Zs({flopay:null,paypalFlopay:null,billingApiUrl:""}),cr=Zs({session:null,loading:!1,error:null});import{PaymentAPI as gi}from"@flopay/js";import{classifyTelemetryFailure as Kc,FloPayError as hi,generateIdempotencyKey as Vc,isValidEmail as Go,normalizeGatewayEnvironment as Hc,PAYPAL_VAULTED_PAYMENT_METHOD_TYPE as vi,SDK_VERSION as Wc}from"@flopay/shared";import{loadScript as Gc}from"@paypal/paypal-js";import{useCallback as kr,useEffect as Lt,useMemo as Yo,useRef as lt,useState as Dr}from"react";import{isValidEmail as Tc}from"@flopay/shared";import{useCallback as Qs,useEffect as Ac,useRef as el,useState as nl}from"react";import{jsx as tl,jsxs as Vo}from"react/jsx-runtime";function Bn(e,t=!1){let{firstName:n,lastName:r,...o}=e,i=n?.trim(),s=r?.trim();return{...o,...i||t?{firstName:i??""}:{},...s||t?{lastName:s??""}:{}}}function mo(){let[e,t]=nl(null),n=el(null),r=el(0),o=Qs((s,l)=>(n.current?.(null),r.current+=1,t({id:r.current,methodLabel:s,identity:l}),new Promise(p=>{n.current=p})),[]),i=Qs(s=>{let l=n.current;n.current=null,t(null),l?.(s)},[]);return Ac(()=>()=>{n.current?.(null),n.current=null},[]),{request:e,collect:o,finish:i}}function yo({identity:e,methodLabel:t,onComplete:n,onCancel:r,submitting:o=!1,testId:i="flopay-buyer-identity-pane"}){let[s,l]=nl(e.email?.trim()??""),p=Tc(s.trim());return Vo("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:[Vo("div",{style:{fontWeight:700},children:["Continue with ",t]}),Vo("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",tl("input",{type:"email",autoComplete:"email","data-testid":"flopay-email",required:!0,value:s,onChange:f=>l(f.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]}),Vo("div",{style:{display:"flex",gap:"0.5rem"},children:[r&&tl("button",{type:"button",onClick:r,style:{flex:1,minHeight:42},children:"Cancel"}),Vo("button",{type:"button",disabled:!p||o,onClick:()=>{n(Bn({...e,email:s.trim()}))},style:{flex:2,minHeight:42},children:["Continue with ",t]})]})]})}function xc(e){if(e instanceof Error)return e.message;if(typeof e=="object"&&e!==null){let t=e.message;return typeof t=="string"?t:void 0}return typeof e=="string"?e:void 0}function Hr(e){if(typeof e!="string")return;let t=e.trim();return/^[a-z0-9_.-]{1,64}$/i.test(t)?t:void 0}function wr(e){if(typeof e!="object"||e===null)return;let t=e;return Hr(t.code)??Hr(t.type)??Hr(t.name)}function fo(e){if(!(typeof e!="object"||e===null))return Hr(e.decline_code)}function Ho(e){return typeof e!="object"||e===null?!1:Hr(e.type)?.toLowerCase()==="card_error"||fo(e)!==void 0}function Ir(e){let t=xc(e)?.toLowerCase()??"",r=`${wr(e)?.toLowerCase()??""} ${t}`;return r.includes("popup")&&r.includes("block")}import{resolveBillingApiUrl as Mc}from"@flopay/shared";import{useContext as Pa}from"react";function Br(){return Pa(er).flopay}function mi(){return Pa(er).paypalFlopay??null}function Bc(){return Pa(cr)}function rl(){return Pa(er).billingApiUrl||Mc()}function ba(e){let t=e??(typeof navigator>"u"?"":navigator.userAgent),n=r=>({inAppBrowser:r!=="none",appFamily:r,popupCapability:"unknown"});return t?/FBAN|FBAV|FB_IAB|FBIOS/i.test(t)?n("facebook"):/Instagram/i.test(t)?n("instagram"):/musical_ly|BytedanceWebview|TikTok/i.test(t)?n("tiktok"):/Twitter|Snapchat|Pinterest|LinkedInApp|Line\/|MicroMessenger|GSA\//i.test(t)?n("other_in_app"):/Android.*;\s?wv\)/.test(t)||/(iPhone|iPad|iPod).*AppleWebKit(?!.*Safari)/.test(t)?n("generic_webview"):n("none"):n("none")}function Ca(e,t,n){return!e.inAppBrowser||n!=="order"?"popup":t==="app_switch"||t==="redirect"?t:"popup"}import{FLO_INSTRUMENT_SCHEMA_VERSION as Fc}from"@flopay/shared";import{useCallback as Dc,useRef as Sa}from"react";var Nc={"checkout.mount":"checkout_mount","sdk.initialize.ready":"sdk_loaded","provider.ready":"sdk_loaded","checkout.rendered":"form_rendered","vault.widget.ready":"form_rendered","vault.submission.started":"tokenize","payment.tokenization.started":"tokenize","payment.processing.started":"process_attempt","payment.intent.started":"process_attempt","vault.action.required":"3ds_challenge","payment.three_ds.handoff":"3ds_challenge"};function Lc(e){return e==="stripe"||e==="paypal"?e:void 0}function Oc(e){let t=Lc(e.provider),n={schemaVersion:Fc,...t?{gateway:t}:{}};if(e.class==="lifecycle"){let r=Nc[e.name];return r?{...n,name:r}:null}return e.class==="card_surface"?{...n,name:"card_expanded"}:e.errorCode==="CHECKOUT_SESSION_CREATE_FAILED"?{...n,name:"checkout_error",phase:"session_create"}:e.errorCode==="SDK_INITIALIZATION_FAILED"||e.errorCode==="PROVIDER_LOAD_FAILED"?{...n,name:"checkout_error",phase:"sdk_load"}:e.errorCode==="PAYMENT_PROCESSING_FAILED"?{...n,name:"checkout_error",phase:e.requestCategory==="intent_create"?"wallets":"process"}:null}var yi=new Set(["checkout_mount","sdk_loaded","form_rendered","card_expanded"]);function go(e,t){let n=Sa(e);n.current=e;let r=Sa(new Set),o=Sa(t),i=Sa(t);return Uo(()=>{i.current=t,o.current!==t&&(o.current=t,r.current.clear())},[t]),Dc(s=>{if(i.current!==t)return;let l=Oc(s);if(l){if(yi.has(l.name)){if(r.current.has(l.name))return;r.current.add(l.name)}Bt(()=>n.current?.(l))}},[t])}var zc=Symbol.for("@flopay/js.telemetry.bridge.v1"),Uc=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function qc(){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 jc(e){let t=qc(),n=(o,i)=>o?o.bind(e):i,r=n(e.now,t.now);return{error:n(e.error,t.error),log:n(e.log,t.log),performance:n(e.performance,t.performance),terminal:n(e.terminal,t.terminal),now:r,elapsed:e.elapsed?e.elapsed.bind(e):o=>Math.max(0,r()-o),setCheckoutContext:n(e.setCheckoutContext,t.setCheckoutContext),beginCheckout:n(e.beginCheckout,t.beginCheckout),disable:n(e.disable,t.disable),subscribe:n(e.subscribe,t.subscribe),flush:n(e.flush,t.flush),destroy:n(e.destroy,t.destroy)}}function wa(e){let t=globalThis[Uc];return jc(t?.(e)??{})}function Qt(e){if(e)return e[zc]}import{useCallback as Fr,useEffect as $c,useRef as fi}from"react";function Wo(e){let t=fi(0),n=fi(null),r=fi(null),o=Fr((m=r.current)=>{m?.timer&&(clearTimeout(m.timer),m.timer=null)},[]),i=Fr(m=>{o();let w=t.current+1;return t.current=w,n.current=null,r.current={generation:w,method:m,timer:null,yieldedControl:!1},w},[o]),s=Fr(m=>{let w=r.current;return m!==void 0&&w?.generation!==m?!1:(o(w),r.current=null,(m===void 0||n.current===m)&&(n.current=null),!0)},[o]),l=Fr(m=>{let w=r.current,_=m??w?.generation??t.current;(m===void 0||w?.generation===m)&&(o(w),r.current=null),n.current=_},[o]),p=Fr(m=>n.current===(m??t.current),[]),f=Fr(m=>r.current?.generation===m&&n.current!==m,[]),C=Fr(()=>{let m=r.current;m&&(m.yieldedControl=!0,o(m))},[o]),h=Fr(()=>{let m=r.current;!m?.yieldedControl||document.visibilityState!=="visible"||(o(m),m.timer=setTimeout(()=>{m.timer=null,r.current?.generation===m.generation&&(r.current=null,n.current=m.generation,e(m.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}))},600))},[o,e]);return $c(()=>{let m=()=>{document.visibilityState==="visible"?h():C()};return document.addEventListener("visibilitychange",m),window.addEventListener("blur",C),window.addEventListener("focus",h),()=>{document.removeEventListener("visibilitychange",m),window.removeEventListener("blur",C),window.removeEventListener("focus",h),o()}},[o,C,h]),{startAttempt:i,finishAttempt:s,invalidateAttempt:l,isAttemptInvalidated:p,isAttemptCurrent:f,generationRef:t}}import{jsx as Wr,jsxs as bi}from"react/jsx-runtime";var Ia=45,Yc=1e3,Jc=11e3,Xc=["https://www.paypal.com","https://www.sandbox.paypal.com"],Pi="We couldn't open PayPal. Try again or choose another payment method.",Zc={width:"100%",minHeight:Ia,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 Qc(e){return e.includes("No ack for postMessage init()")&&Xc.some(t=>e.includes(t))&&e.includes("10000ms")}var ed={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 td(e){return!e.generationActive||e.kind==="teardown"?{action:"ignore"}:e.kind==="ineligible"?{action:"unavailable"}:e.automaticRetryAllowed&&!e.automaticRetryUsed?{action:"retry"}:{action:"exhaust",report:ed[e.kind]??null}}function nd(e,t){return e==="watchdog_expired"?"paypal_render_timeout":Qc(t)?"paypal_init_timeout":"paypal_init_failure"}function rd(e,t=!1){return e?t?`${Pi} Open this page in your system browser, then try again.`:`${Pi} Allow pop-ups for this site, then try again.`:Pi}function od(e){let t=Ho(e),n=Ir(e);return t?{errorCode:"PROVIDER_RUNTIME_FAILED",popupBlocked:n,providerDeclined:t,terminalReason:"provider_declined"}:{errorCode:n?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",popupBlocked:n,providerDeclined:t,terminalReason:n?"popup_blocked":"provider_error"}}function ad(e){let t=e,n=t?.payer??t?.payment_source?.paypal;return{email:n?.email_address?.trim()||void 0,firstName:n?.name?.given_name?.trim()||void 0,lastName:n?.name?.surname?.trim()||void 0}}function id(e){return e>=500?"5xx":e>=400?"4xx":e>=300?"3xx":"unknown"}function ol({sessionId:e,nonce:t,billingApiUrl:n,email:r,billingName:o,onBuyerIdentityReady:i,clientId:s,environment:l,currency:p,isSubscription:f,providerObjectType:C,approvalPresentation:h,onTokenizedBody:m,onComplete:w,onErrorChange:_,onDecline:ae,onTechnicalFailure:Y,isProcessing:Pe=!1,onLoadStateChange:S,onInitializationStateChange:G,allowAutomaticRetry:X=!0,onButtonClick:ce,runBeforeButtonClick:Te,session:Fe,existingOrderId:ve,telemetry:Ue,telemetryContext:bt,onInstrument:ot,debug:$e=!1}){let De=Br(),ye=go(ot,e),we=Yo(()=>{if(De)return null;let M=wa({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:Wc,enabled:Ue!==!1});return M.setCheckoutContext(bt??{}),M.beginCheckout(bt??{}),M},[n,De,Ue,bt?.checkoutMode,bt?.layout]),Qe=Yo(()=>Qt(De),[De]);Lt(()=>()=>{we&&we.flush().catch(()=>{}).finally(()=>we.destroy())},[we]);let Z=Yo(()=>({error:M=>{Qe?Qe.error(M):we?.error(M),ye({class:"technical_error",errorCode:M.requestCategory==="intent_create"?"PAYMENT_PROCESSING_FAILED":M.errorCode,requestCategory:M.requestCategory,provider:M.provider})},log:M=>{Qe?Qe.log(M):we?.log(M),ye({class:"lifecycle",name:M.name,provider:M.provider})},performance:M=>{Qe?Qe.performance(M):we?.performance(M)},terminal:M=>{Qe?Qe.terminal(M):we?.terminal(M)},startTiming:()=>Qe?.now()??we?.now()??0,elapsed:M=>Qe?.elapsed(M)??Math.max(0,(we?.now()??M)-M)}),[ye,Qe,we]),Ie=lt(null),be=lt(0),ct=lt(null),dt=lt(null),U=lt(null),V=lt(!1),[de,fe]=Dr(!1),[ut,Ne]=Dr(!1),[x,at]=Dr(0),Ye=lt(0),[re,Q]=Dr(!1),L=lt(!1),Ae=lt(!1),[xe,Me]=Dr(!1),[qe,ke]=Dr(!1),{request:Ee,collect:ee,finish:dn}=mo(),Yt=lt({sessionId:e,required:!Go(r?.trim()||Fe?.customer?.email?.trim())});Yt.current.sessionId!==e&&(Yt.current={sessionId:e,required:!Go(r?.trim()||Fe?.customer?.email?.trim())});let H=Yt.current.required,Je=Yo(()=>n.replace(/\/+$/,""),[n]),K=Fe?.gateways?.paypal?.providerObjectType??C,ie=K??(f?"subscription":"order"),[u]=Dr(ba),B=Fe?.gateways?.paypal?.approvalPresentation??h,_e=Ca(u,B==="app_switch"?"app_switch":void 0,ie),Ke=K==="order"||K==="setup_token",Re=Yo(()=>JSON.stringify([Je,s,p,l??"",ie,Ke,_e,e,ve??""]),[Je,s,p,l,ve,ie,Ke,_e,e]),$t=lt(Re),N=$t.current!==Re,Ct=lt($e),Et=lt(null),[pt,un]=Dr([]),O=kr(M=>{Ct.current&&un(Oe=>[...Oe,`${new Date().toISOString().slice(11,23)} ${M}`])},[]);Lt(()=>{Ct.current=$e,$e&&O("debug:enabled"),Et.current?.setEnabled($e)},[O,$e]);let Ot=lt(m),Cn=lt(w),pn=lt(_),mn=lt(ae),_n=lt(Y),Fn=lt(ce),Dn=lt(S),Jt=lt(G),je=lt(i),He=lt(Te),St=lt(Fe),rn=lt(r),wt=lt(o),$n=lt(t),mt=lt(null),Tt=lt(new Map),zt=lt(new Map),yn=lt(!1);Lt(()=>(yn.current=!0,()=>{yn.current=!1}),[]),Lt(()=>{Ot.current=m},[m]),Lt(()=>{je.current=i},[i]),Lt(()=>{Cn.current=w},[w]),Lt(()=>{pn.current=_},[_]),Lt(()=>{mn.current=ae},[ae]),Lt(()=>{_n.current=Y},[Y]),Lt(()=>{Fn.current=ce},[ce]),Lt(()=>{Dn.current=S},[S]),Lt(()=>{Jt.current=G},[G]),Lt(()=>{He.current=Te},[Te]),Lt(()=>{St.current=Fe},[Fe]),Lt(()=>{rn.current=r},[r]),Lt(()=>{wt.current=o},[o]),Lt(()=>{$n.current=t},[t]),Lt(()=>{Ye.current=x},[x]),Lt(()=>{re&&U.current?.focus()},[re,x]);let Ut=kr(()=>{window.setTimeout(()=>{U.current?.focus()},0)},[]),At=kr(()=>{fe(!1),at(M=>M+1)},[]),Sn=kr(()=>{Q(!1),(Ie.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??Ie.current)?.focus?.()},[]);Lt(()=>{!de||!V.current||(V.current=!1,Sn())},[Sn,de,x]);let wn=kr((M,Oe)=>{let D=Oe?.popupBlocked??Ir(M),kt=rd(D,u.inAppBrowser),xt=_n.current;if(xt){let Gt=D&&u.inAppBrowser?new hi(kt,"api_error",{code:Oe?.code??"paypal_popup_blocked"}):M;xt("paypal",Gt,Oe);return}pn.current?.(kt)},[u.inAppBrowser]),It=kr(M=>{let Oe=ct.current,D=dt.current;Oe===null||!D||(Z.log({...D,name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:M}),Z.performance({...D,stage:"overlay_return",durationMs:Z.elapsed(Oe),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:M}),ct.current=null)},[Z]),te=kr((M,Oe,D)=>{let kt=dt.current;It("overlay_timeout"),kt&&Z.error({...kt,errorCode:"REQUEST_TIMEOUT",failureCategory:"provider_runtime",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",statusClass:"timeout",terminalReason:"overlay_timeout"}),wn(Oe,D),Q(!0),At(),Ut()},[It,Ut,wn,At,Z]),{finishAttempt:on,generationRef:Kn,invalidateAttempt:Ht,isAttemptCurrent:Kt,isAttemptInvalidated:an,startAttempt:nr}=Wo(te),Nn=kr(()=>(Q(!1),nr("paypal")),[nr]),Wt=kr(M=>{Ht(M?.generation),M?.showRetry&&Q(!0),M?.remount&&At(),M?.focus!==!1&&Ut()},[Ut,Ht,At]),Le=M=>{let Oe=mt.current;return Oe&&zt.current.set(M,Oe),M};Lt(()=>{$t.current!==Re&&($t.current=Re,L.current=!1,Ae.current=!1,fe(!1),Ne(!1),Me(!1),Jt.current?.("loading"))},[Re]),Lt(()=>{Bt(()=>Dn.current?.(de&&!xe))},[de,xe]);let fn=Hc(l);Lt(()=>{let M={attempt:Kn.current+1,...u,presentationMode:_e},Oe=()=>dt.current??M,D={error:R=>Z.error({...R,...Oe()}),log:R=>Z.log({...R,...Oe()}),performance:R=>Z.performance({...R,...Oe()}),terminal:R=>Z.terminal({...R,...Oe()}),startTiming:Z.startTiming,elapsed:Z.elapsed},kt=s?`${s.slice(0,6)}\u2026(len ${s.length})`:"(empty)",xt=typeof navigator>"u"?"(no navigator)":navigator.userAgent;if(O(`mount clientId=${kt} env=${l??"(unset)"}\u2192${fn??"live"} ccy=${p} sub=${f}`),O(`ua=${xt.slice(0,80)}${xt.length>80?"\u2026":""}`),!s){O("FAIL: clientId empty \u2014 gateway misconfigured"),Me(!0),D.error({errorCode:"CONFIGURATION_INVALID",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),console.error("[FloPay] DirectPayPal: clientId empty \u2014 gateway misconfigured");return}if(!Ie.current){O("FAIL: containerRef not attached");return}be.current=D.startTiming(),D.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let Gt=!1,Vn=!1,ge=()=>Gt||Vn,sn,Hn=!1,Pr=()=>{sn=Vc(),sn||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),Hn=!0},rr=null,zr=!1,Ur=null,or=!1,Er=()=>{!Ur||or||(or=!0,Ur.close().catch(()=>{}))},Rn=!1,ar=!1,Dt=Ie.current,Ln=null,Wn=null,Gn=[],yt=null,En=!1,Yn=!1,ir=null,gn=R=>{if(!R||typeof R.getBoundingClientRect!="function")return"(no rect)";let d=R.getBoundingClientRect();return`${Math.round(d.width)}\xD7${Math.round(d.height)}`},We=R=>{if(!R)return"(empty)";try{let d=new URL(R,typeof window>"u"?"https://localhost":window.location.href),A=d.pathname.toLowerCase();return A.includes("checkcaptcha")||A.includes("captcha")?`CAPTCHA(${d.host}${A})`:A.includes("risk")||A.includes("challenge")?`RISK(${d.host}${A})`:A.includes("smart/buttons")?`smart-buttons(${d.host})`:`${d.host}${A}`.slice(0,100)}catch{return R.slice(0,80)}},hn=R=>{let d=R.getAttribute("src"),A=R.getAttribute("srcdoc"),g=R.getAttribute("name"),P=R.getAttribute("sandbox"),I=[];return d&&I.push(`src=${We(d)}`),A&&I.push(`srcdoc[${A.length}ch]`),!d&&!A&&I.push("src=(empty) srcdoc=(empty)"),g&&I.push(`name=${g.slice(0,40)}`),P!==null&&I.push(`sandbox="${P.slice(0,40)}"`),I.join(" ")},ln=R=>{if(!(R instanceof HTMLIFrameElement))return"";try{let d=R.contentDocument;if(!d)return"cd=null";let A=d.body?.children.length??0,g=d.body?.innerHTML.length??0,P=d.head?.innerHTML.length??0;return`cd=same-origin readyState=${d.readyState} body[${A}children,${g}ch] head[${P}ch]`}catch(d){return`cd=cross-origin(${d.message.slice(0,30)})`}},On=[],br=R=>{if(ge())return;let d=R.message??String(R.error??"(no message)");d&&(d.toLowerCase().includes("paypal")||d.toLowerCase().includes("zoid")||d.toLowerCase().includes("postrobot")||d.toLowerCase().includes("storage"))&&(O(`window:error ${d.slice(0,140)}`),On.push(d))},qr=R=>{if(ge())return;let d=R.reason instanceof Error?R.reason.message:String(R.reason??"(no reason)");d&&(d.toLowerCase().includes("paypal")||d.toLowerCase().includes("zoid")||d.toLowerCase().includes("postrobot")||d.toLowerCase().includes("storage"))&&(O(`window:rejection ${d.slice(0,140)}`),On.push(d))},Cr={value:0},zn=()=>{Ln?.disconnect(),Ln=null,Wn?.disconnect(),Wn=null;for(let R of Gn.splice(0))clearTimeout(R);Yn=!1,En&&typeof window<"u"&&(window.removeEventListener("error",br),window.removeEventListener("unhandledrejection",qr)),En=!1},vn=()=>{if(!(En||ge()||Rn)){if(En=!0,On.length=0,Cr.value=0,typeof window<"u"&&(window.addEventListener("error",br),window.addEventListener("unhandledrejection",qr)),typeof PerformanceObserver<"u")try{Wn=new PerformanceObserver(R=>{if(!ge())for(let d of R.getEntries()){if(!d.name.toLowerCase().includes("paypal"))continue;Cr.value+=1;let A=Math.round(d.duration);O(`net ${A}ms ${d.name.slice(0,90)}`)}}),Wn.observe({type:"resource",buffered:!0})}catch{}ir?.()}},Xr=()=>{yt&&(clearTimeout(yt),yt=null)},Tn=()=>{zn(),Xr()},Tr={setEnabled:R=>{R?vn():zn()}};Et.current=Tr,Ct.current&&vn();let In=R=>{if(!R)return!1;let d=R.toLowerCase();return d.includes("zoid destroyed")||d.includes("destroyed all components")||d.includes("window closed")||d.includes("detected container element removed")},Un=R=>{if(ge()||In(R))return;let d=xr(R)??R;Bt(()=>pn.current?.(d))},et=(R,d)=>{if(Gt||zr)return;zr=!0,Vn=!0,Tn(),Er();let A=td({kind:R,generationActive:!0,automaticRetryAllowed:X,automaticRetryUsed:L.current});if(A.action==="retry"){L.current=!0,fe(!1),ke(!1),Ne(!0),Jt.current?.("retrying"),rr=setTimeout(()=>{Gt||at(g=>g+1)},Yc);return}if(fe(!1),ke(!1),Ne(!1),Me(!0),A.action!=="ignore"){if(Jt.current?.("exhausted"),A.action==="unavailable"){console.error("[FloPay] DirectPayPal load/render failure:",d);return}A.report&&D.error({errorCode:A.report.errorCode,stage:A.report.stage,operationOutcome:A.report.operationOutcome,provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime"}),Ae.current||(Ae.current=!0,console.error("[FloPay] Direct PayPal initialization failed:",nd(R,d)))}};Me(!1);let Jn=async(R,d=mt.current)=>{if(ge())return;let A=d?.sessionId??e;if(Ot.current){await Ot.current(R,{sessionId:A,accountPatch:d?.accountPatch,nonce:d?.nonce});return}let g=D.startTiming();D.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let P=()=>{D.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),D.performance({stage:"processing",durationMs:D.elapsed(g),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment"})};try{let I=St.current,v=d?.accountPatch?.email??rn.current,q=d?.accountPatch?.userId??I?.customer?.id??I?.accountData?.userId??"",Ve=d?.accountPatch?.firstName??I?.customer?.firstName??I?.accountData?.firstName,Nt=d?.accountPatch?.lastName??I?.customer?.lastName??I?.accountData?.lastName,ne=await new gi(Je,{telemetry:!1}).processPayment(q,{sessionId:A,nonce:d?.nonce??$n.current,paymentMethodCategory:"paypal",tokenizedData:R,accountData:{userId:q,email:v??I?.customer?.email??"",...Ve?{firstName:Ve}:{},...Nt?{lastName:Nt}:{},country:d?.accountPatch?.country??I?.customer?.country??I?.accountData?.country??void 0,zip:d?.accountPatch?.zip??I?.customer?.zip??I?.accountData?.zip??void 0}});if(ne.ok){if(Vn||Gt&&yn.current)return;P(),D.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),Bt(()=>Cn.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(ge())return;let y=await ne.json().catch(()=>null),k=y?.message??"PayPal payment failed.",J=xr(k)??k;P(),ne.status===400&&(typeof y?.declineCode=="string"||!Array.isArray(y?.fields))?D.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}):ne.status===400||ne.status===422?D.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx",terminalReason:"approved"}):D.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:id(ne.status),failureCategory:ne.status>=500?"server_error":void 0}),Un(J),Bt(()=>mn.current?.(nn("paypal",J,{code:y?.code,declineCode:y?.declineCode})));return}catch(I){if(ge())return;P(),D.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let v=I instanceof Error?I.message:"PayPal payment failed.",q=xr(v)??v;Un(q),Bt(()=>mn.current?.(nn("paypal",q)));return}},Xt=()=>new hi("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),_t=R=>ge()?Promise.reject(Xt()):Promise.resolve(R),T=async R=>{if(ge())throw Xt();Hn||Pr();let d=mt.current,A=d?.sessionId??e,g=d?.nonce??$n.current;D.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let P;try{P=await new gi(Je,{telemetry:!1}).createSessionIntent(A,g??"",Ke?{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:vi,paymentMethodId:null,intentKind:ie==="setup_token"?"setup":"payment"}:{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"},{idempotencyKey:sn})}catch(I){throw D.error({...Kc(I,"PAYMENT_PROCESSING_FAILED","unknown"),stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"}),I}if(ge())throw Xt();if(P.provider!=="paypal"||P.providerObjectType!==ie)throw new Error(R);return D.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),P.providerObjectId},E=(R,d)=>{let A=d?.nonce??$n.current;if(!A)return;let g=d?.sessionId??e,P=fo(R)??wr(R)??"provider_declined";new gi(Je,{telemetry:!1}).reportSessionIntentDecline(g,A,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:P}).catch(()=>{})},F=x;O("loadScript:scheduled (deferred 1 tick)");let z=null,it=setTimeout(()=>{if(Gt){O("loadScript:skipped (cancelled before defer ran)");return}O("loadScript:start");let R=fn==="live"?"production":fn,d={};ie==="subscription"?d={intent:"subscription",vault:!0}:ie==="order"&&(d={intent:"capture"}),z=Gc({clientId:s,currency:p,...d,...R?{environment:R}:{},...R==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}});let A=!1;z.then(g=>{if(A=!0,O(`loadScript:resolved inactive=${ge()} ns=${!!g} buttons=${!!g?.Buttons}`),ge())return;if(!g?.Buttons){O("FAIL: namespace missing Buttons factory"),et("namespace_unusable","PayPal SDK did not expose the Buttons factory.");return}D.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),D.performance({stage:"provider_ready",durationMs:D.elapsed(be.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),D.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let P=async(ne,y)=>{if(ge()||Ye.current!==F)return;let k=ne.vaultSetupToken??ne.subscriptionID??ne.orderID??"",J=k?zt.current.get(k):Tt.current.get(F);if(!(!J||!Kt(J.generation))&&on(J.generation)){zt.current.delete(k),Tt.current.delete(J.surfaceKey),It("approved");try{if(ke(!0),Bt(()=>pn.current?.(null)),!k)throw new hi("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});let ue=St.current,Se=Vr(wt.current??[ue?.customer?.firstName,ue?.customer?.lastName].filter(Boolean).join(" ")),pe=Bn({email:J.accountPatch?.email?.trim()||rn.current?.trim()||ue?.customer?.email?.trim(),firstName:J.accountPatch?.firstName?.trim()||Se.firstName,lastName:J.accountPatch?.lastName?.trim()||Se.lastName});if(!Go(pe.email)||!(pe.firstName||pe.lastName))try{let ht=ad(await y?.order?.get?.());pe=Bn({email:ht.email||pe.email,firstName:ht.firstName||pe.firstName,lastName:ht.lastName||pe.lastName})}catch{}if((je.current||H)&&!Go(pe.email)){let ht=await ee("PayPal",pe);if(!ht)return;pe=ht}Go(pe.email)&&(J.accountPatch=Bn({...J.accountPatch,...pe}),await je.current?.(pe));let Ge;ie==="setup_token"?Ge={id:k,type:"paypal_setup_token",isPaypal:!0,gateway:"paypal",paymentMethodType:vi}:Ke?Ge={id:k,isPaypal:!0,gateway:"paypal",paymentMethodType:vi}:Ge={id:k,isPaypal:!0},await Jn(Ge,J)}catch(ue){Un(ue instanceof Error?ue.message:"PayPal capture failed.")}finally{ge()||ke(!1)}}},I=ne=>{let y=ve?()=>_t(ve):()=>T(ne);return async()=>Le(await y())},v=g.Buttons({style:{layout:"horizontal",height:Ia,tagline:!1},..._e==="app_switch"?{appSwitchWhenAvailable:!0}:{},onClick:async(ne,y)=>{if(ge()){await y.reject();return}Pr();let k=He.current,J={};if(k)try{let pe=await k("paypal");if(ge()){await y.reject();return}if(!pe.proceed){mt.current=null,Tt.current.delete(F),await y.reject();return}J={sessionId:pe.sessionId,accountPatch:pe.accountPatch,nonce:pe.nonce}}catch(pe){O(`onClick:runBeforeButtonClick rejected msg=${(pe instanceof Error?pe.message:String(pe)).slice(0,120)}`),mt.current=null,Tt.current.delete(F),await y.reject();return}Bt(()=>Fn.current?.("paypal"));let ue=Nn(),Se={generation:ue,surfaceKey:F,...J};mt.current=Se,Tt.current.set(F,Se),dt.current={...M,attempt:ue},await y.resolve(),D.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),D.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),ct.current=D.startTiming()},createOrder:ie==="order"?I("Failed to create PayPal order."):void 0,createSubscription:ie==="subscription"?I("Failed to create PayPal subscription."):void 0,createVaultSetupToken:ie==="setup_token"?async()=>Le(await T("Failed to create PayPal setup token.")):void 0,onApprove:P,onCancel:()=>{if(ge())return;let ne=Tt.current.get(F)??mt.current;ne&&Tt.current.delete(ne.surfaceKey),mt.current=null,It("cancelled"),D.terminal({outcome:"payment_cancelled",terminalReason:"cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),V.current=!0,Wt({generation:ne?.generation,remount:!0,focus:!1})},onError:ne=>{if(ge()||Ye.current!==F)return;let y=ne instanceof Error?ne.message:"PayPal failed to render.";if(O(`onError rendered=${Rn} msg=${y.slice(0,120)}`),Rn){let k=Tt.current.get(F)??mt.current;if(k&&!Kt(k.generation)||!k&&an())return;if(In(y)){on(k?.generation);return}let{errorCode:J,popupBlocked:ue,providerDeclined:Se,terminalReason:pe}=od(ne);if(It(pe),Se){D.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:pe}),E(ne,k),Bt(()=>mn.current?.(nn("paypal",y))),k&&Tt.current.delete(k.surfaceKey),mt.current=null,on(k?.generation);return}D.error({errorCode:J,failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",terminalReason:pe}),k&&Tt.current.delete(k.surfaceKey),mt.current=null,Wt({generation:k?.generation,remount:!0,showRetry:!0,focus:!0}),wn(ne,{code:"paypal_runtime_failed",popupBlocked:ue});return}et(In(y)?"teardown":"pre_ready_callback",y)}}),q=v.isEligible();if(O(`isEligible=${q}`),D.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!q){fe(!1),et("ineligible","PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}ar=!0,Ur=v,ir=()=>{if(!En||Yn||ge()||Rn)return;Yn=!0,O(`container:dims ${gn(Dt)} visibility=${typeof document>"u"?"(no document)":document.visibilityState}`),typeof MutationObserver<"u"&&(Ln=new MutationObserver(y=>{if(!ge()){for(let k of y)if(k.type==="childList")k.addedNodes.forEach(J=>{if(!(J instanceof Element))return;let ue=J.tagName.toLowerCase(),Se=(J.getAttribute("title")??"").slice(0,40),pe=ue==="iframe"?` ${hn(J)}`:"";O(`child+ ${ue}${Se?` title="${Se}"`:""}${pe} dims=${gn(J)}`)});else if(k.type==="attributes"&&k.target instanceof Element){let J=k.target;if(J.tagName.toLowerCase()!=="iframe")continue;let ue=k.attributeName;(ue==="src"||ue==="srcdoc")&&O(`attr~ iframe ${ue}=${ue==="srcdoc"?`[${(J.getAttribute("srcdoc")??"").length}ch]`:We(J.getAttribute("src"))} dims=${gn(J)}`)}}}),Ln.observe(Dt,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let ne=y=>{if(ge()||Rn)return;let k=Dt.querySelectorAll("iframe"),J=typeof document<"u"&&"hasStorageAccess"in document;O(`watchdog:${y} container=${gn(Dt)} children=${Dt.childElementCount} iframes=${k.length} visibility=${typeof document>"u"?"(no document)":document.visibilityState} cookies=${typeof navigator>"u"?"?":navigator.cookieEnabled} hasStorageAccessApi=${J} paypalNetRequests=${Cr.value}`),k.forEach((ue,Se)=>{let pe=(ue.getAttribute("title")??"").slice(0,40);O(` iframe[${Se}] ${gn(ue)}${pe?` title="${pe}"`:""} ${hn(ue)}`);let Ge=ln(ue);Ge&&O(` ${Ge}`)}),On.length===0&&O(" (no PayPal/zoid window errors captured)")};Gn.push(setTimeout(()=>ne("3s"),3e3)),Gn.push(setTimeout(()=>ne("8s"),8e3)),Gn.push(setTimeout(()=>ne("15s"),15e3))},ir(),O("render:start");let Nt=D.startTiming();yt=setTimeout(()=>{ge()||Rn||(O("watchdog:11s retryable render timeout"),et("watchdog_expired","PayPal Buttons render did not settle within 11000ms."))},Jc);let Ce=v.render(Dt);(async()=>{try{if(await Ce,O(`render:resolved inactive=${ge()}`),Tn(),ge()){Er();return}Rn=!0,fe(!0),Ne(!1),Jt.current?.("ready"),D.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),D.performance({stage:"checkout_render",durationMs:D.elapsed(Nt),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}catch(ne){let y=ne instanceof Error?ne.message:"PayPal failed to render.";O(`render:rejected msg=${y.slice(0,120)}`),Tn(),et(In(y)?"teardown":"render_rejected",y)}})()}).catch(g=>{let P=g instanceof Error?g.message:"PayPal operation failed.";O(`provider:failed msg=${P.slice(0,120)}`);let I="script_rejected";A&&In(P)?I="teardown":A&&ar&&(I="render_rejected"),et(I,P)})},0);return()=>{Gt=!0,clearTimeout(it),rr&&clearTimeout(rr),Tn(),Et.current===Tr&&(Et.current=null),Er(),ct.current=null,dt.current=null}},[X,Je,s,p,l,ie,_e,Ke,e,ve,x,Z,ee,H,O,It]);let se=$e?bi("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:xe?"#fef2f2":"#f3f4f6",border:`1px solid ${xe?"#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=${de} failed=${xe})`,pt.length===0?`
|
|
1
|
+
import{a as Ft,b as wr,c as Ho,d as bi,e as Wo,f as Js,g as Xs,h as xc,i as Mc}from"./chunk-CSBYK62Y.mjs";import{dropThirdPartyOnlyError as mm}from"@flopay/shared";import{PaymentAPI as hs}from"@flopay/js";import{FloPayError as fa,resolveBillingApiUrl as qu,resolveButtonsLayoutTheme as ju,resolveTheme as $u}from"@flopay/shared";import{useCallback as xr,useEffect as xo,useMemo as ya,useRef as Mo,useState as ma}from"react";import{Fragment as mo,jsx as rr,jsxs as Zs}from"react/jsx-runtime";function Bc(){return Zs(mo,{children:[Zs("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:[rr("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),rr("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",rr("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:rr("path",{d:"M9 18l6-6-6-6"})})]})}function Fc(){return rr(mo,{children:"Go back"})}function Dc(){return rr(mo,{children:"Secure card checkout"})}function uo(e){return e!==void 0&&(e===""||e===null||e===!1)}function po({content:e}){return rr(mo,{children:e===void 0?rr(Bc,{}):e})}function yo({content:e}){return rr(mo,{children:e===void 0?rr(Fc,{}):e})}function Go({content:e}){return rr(mo,{children:e===void 0?rr(Dc,{}):e})}import{classifyTelemetryFailure as Oc,FloPayError as Vn,isCardHolderNamePlaceholder as Qs,isMoneySettledOutcome as Nc,isSetupIntentClientSecret as Lc,isValidEmail as zc}from"@flopay/shared";var Uc="Checkout is temporarily unavailable. Please try again later.";function Pi(e){return{errorCode:"PROVIDER_LOAD_FAILED",failureCategory:e instanceof Vn&&e.type==="authentication_error"?"invalid_response":"provider_runtime",stage:"provider_load",provider:"stripe",requestCategory:"provider_sdk"}}function qc(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 el(){return new Vn(Uc,"api_error",{code:"CheckoutInitializationFailed"})}function Ci(e){return!!e?.gateways?.worldpayCorporateGateway}function Mr(e){return e?.status==="open"&&Ci(e)}function tl(e,t,n){let r=e?.data.session,o=r?.gateways?.stripe?.enabledPaymentMethods??e?.data.stripe?.enabledPaymentMethods;return!!(n&&(r?.vault?.html||r?.gateways?.pcivault||o?.includes("card")||Mr(r))||t&&e?.data.paypal?.publishableKey)}function nl(e,t){if(t&&(!(e instanceof Vn)||e.type==="authentication_error"))return Pi(e);if(!(e instanceof Vn&&qc(e))){if(!t&&!(e instanceof Vn)&&(e instanceof TypeError||e instanceof SyntaxError))return{...Oc(e,"NETWORK_REQUEST_FAILED"),stage:"session_read",requestCategory:"session_read"};if(!t&&e instanceof Vn)return{errorCode:"NETWORK_REQUEST_FAILED",stage:"session_read",requestCategory:"session_read"};if(!(e instanceof Vn))return{errorCode:"INTERNAL_SDK_ERROR",stage:"checkout_mount"}}}function fo(e,t,n,r={}){let o;return(i={})=>{if(o)return o;let s={...r,...i,email:i.email?.trim()||r.email?.trim()},l=Qs(s.firstName,s.lastName);if(!zc(s.email))return Promise.reject(new Vn("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}));let y={};for(let[f,b]of Object.entries(s)){if(l&&f.endsWith("Name")||typeof b!="string")continue;let g=b.trim();g&&(y[f]=g)}return o=e.claimCheckoutSession(t,n,{accountData:y}),o.catch(()=>{}),o}}function rl(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 wi(e,t){return t?{...e,account:{...e.account,...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,..."checkoutMetadata"in t?{checkoutMetadata:t.checkoutMetadata}:{},tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}:e}function ol(e,t){let n=e.products??[...(e.subscriptions??[]).map(i=>({type:"subscription",code:i.code??i.providerPlanId,name:i.subscriptionName??i.providerPlanName??i.code??i.providerPlanId??null,quantity:i.quantity??1,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount,currency:i.currency,metadata:i.metadata})),...(e.items??[]).map(i=>({type:"item",code:i.code??i.providerItemId,name:i.itemName??i.providerItemName??i.code??i.providerItemId??null,quantity:i.quantity??1,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount,currency:i.currency,metadata:i.metadata}))],r=n.reduce((i,s)=>i+(s.overrideAmount??s.totalAmount??0),0),o=e.currency??n.find(i=>i.currency)?.currency??"USD";return{id:"",clientSecret:"",mode:n.some(i=>i.type==="subscription")?"subscription":"payment",amount:Math.round(r*100),currency:o,status:"open",captureMethod:e.captureMethod,customer:{id:e.account.userId,email:e.account.email??"",firstName:e.account.firstName,lastName:e.account.lastName,gender:e.account.gender??void 0,city:e.account.city??void 0,state:e.account.state??void 0,country:e.account.country??void 0,zip:e.account.zip??void 0},successUrl:e.successUrl,cancelUrl:e.cancelUrl,checkoutMode:t??e.checkoutMode??"full",products:n.map((i,s)=>({uuid:`synthetic-${i.type??"item"}-${s}`,checkoutSessionId:"",type:i.type??"item",code:i.code,name:i.name??null,quantity:i.quantity??1,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount??null,currency:i.currency??o,metadata:i.metadata??null}))}}function Yr(e){if(Qs(e))return{};let[t,...n]=e?.trim().split(/\s+/)??[];return t?{firstName:t,lastName:n.join(" ")||void 0}:{}}function Si(e,t){return t?{...e,...t}:e}function dn(e,t,n){let r=typeof t=="string"?t:t.message,o=typeof t=="string"?n?.code:n?.code??t.code,i=typeof t=="string"?n?.declineCode:n?.declineCode??t.declineCode;return{method:e,message:r,...o?{code:o}:{},...i?{declineCode:i}:{}}}var jc=[{match:/^paypal authorization required\.?$/i,replacement:"For your additional security, please re-authenticate this payment via PayPal."}];function Br(e){if(typeof e!="string")return e??void 0;let t=e.trim();if(!t)return e;for(let{match:n,replacement:r}of jc)if(n.test(t))return r;return e}function Tr(e,t){return e.status!=="authorized"?{status:"succeeded"}:{status:"authorized",paymentId:e.paymentId,sessionId:e.id||t||void 0,authorizationExpiresAt:e.authorizationExpiresAt}}function Fr(e){return e?.status==="authorized"||e?.status==="complete"}function al(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function _a(e){let t=al(e);return new Vn(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function Ra(e){return e instanceof Vn||typeof e=="object"&&e!==null&&"code"in e?e.code:void 0}function go(e){let t=al(e),n="checkout_processing_timeout";return t?n="authorization_expired":e?.status==="expired"&&(n="checkout_session_expired"),new Vn(t?"Authorization has expired.":"Automatic payment failed. Please try again.","api_error",{code:n})}function Yo(e,t){return e==="processing"||Nc(e,t)}function il(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}async function sl(e,t){let n=e;if(Lc(t)){if(!n?.retrieveSetupIntent)return null;let{setupIntent:i,error:s}=await n.retrieveSetupIntent(t);if(s)throw new Vn(s.message??"Failed to retrieve setup intent.","api_error",{...s.code?{code:s.code}:{}});return i??null}if(!n?.retrievePaymentIntent)return null;let{paymentIntent:r,error:o}=await n.retrievePaymentIntent(t);if(o)throw new Vn(o.message??"Failed to retrieve payment intent.","api_error",{...o.code?{code:o.code}:{}});return r??null}function ll(e,t="automatic"){return{...typeof e=="number"&&Number.isFinite(e)&&e>0?{mode:"payment",amount:e,captureMethod:t==="manual"?"manual":"automatic_async"}:{mode:"setup"},paymentMethodTypes:["card"],setupFutureUsage:"off_session"}}function ki(e){let t=e&&typeof e=="object"?e:null;return t?.name==="IntegrationError"||t?.code==="elements_intent_mismatch"||t?.type==="invalid_request_error"?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response"}:{errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime"}}function Jo(e){let t=[e?.id,e?.originalPaymentMethodId];for(let n of t)if(typeof n=="string"&&n.startsWith("pm_"))return n}import{FloPay as Iu,PaymentAPI as Za,SESSION_CREATE_TELEMETRY as _u}from"@flopay/js";import{buildCheckoutDisplayData as Ru,classifyTelemetryFailure as lc,FloPayError as Sn,isDetachedSessionEligible as Eu,resolveBillingApiUrl as Tu,resolveButtonsLayoutTheme as Au,resolveIdempotencyKey as tc,resolveTheme as cc,SDK_VERSION as dc,telemetryStatusClass as xu}from"@flopay/shared";import ls,{useCallback as wn,useEffect as yr,useMemo as ar,useRef as At,useState as zt}from"react";import{createContext as cl}from"react";var or=cl({flopay:null,paypalFlopay:null,billingApiUrl:""}),ur=cl({session:null,loading:!1,error:null});import{PaymentAPI as Ei}from"@flopay/js";import{classifyTelemetryFailure as id,FloPayError as Ti,generateIdempotencyKey as sd,isValidEmail as ra,normalizeGatewayEnvironment as ld,PAYPAL_VAULTED_PAYMENT_METHOD_TYPE as Ai,SDK_VERSION as cd}from"@flopay/shared";import{loadScript as dd}from"@paypal/paypal-js";import{useCallback as kr,useContext as ud,useEffect as Ot,useMemo as oa,useRef as ot,useState as Lr}from"react";import{isValidEmail as $c}from"@flopay/shared";import{useCallback as dl,useEffect as Kc,useRef as ul,useState as yl}from"react";import{jsx as pl,jsxs as Xo}from"react/jsx-runtime";function On(e,t=!1){let{firstName:n,lastName:r,...o}=e,i=n?.trim(),s=r?.trim();return{...o,...i||t?{firstName:i??""}:{},...s||t?{lastName:s??""}:{}}}function ho(){let[e,t]=yl(null),n=ul(null),r=ul(0),o=dl((s,l)=>(n.current?.(null),r.current+=1,t({id:r.current,methodLabel:s,identity:l}),new Promise(y=>{n.current=y})),[]),i=dl(s=>{let l=n.current;n.current=null,t(null),l?.(s)},[]);return Kc(()=>()=>{n.current?.(null),n.current=null},[]),{request:e,collect:o,finish:i}}function vo({identity:e,methodLabel:t,onComplete:n,onCancel:r,submitting:o=!1,testId:i="flopay-buyer-identity-pane"}){let[s,l]=yl(e.email?.trim()??""),y=$c(s.trim());return Xo("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:[Xo("div",{style:{fontWeight:700},children:["Continue with ",t]}),Xo("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",pl("input",{type:"email",autoComplete:"email","data-testid":"flopay-email",required:!0,value:s,onChange:f=>l(f.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]}),Xo("div",{style:{display:"flex",gap:"0.5rem"},children:[r&&pl("button",{type:"button",onClick:r,style:{flex:1,minHeight:42},children:"Cancel"}),Xo("button",{type:"button",disabled:!y||o,onClick:()=>{n(On({...e,email:s.trim()}))},style:{flex:2,minHeight:42},children:["Continue with ",t]})]})]})}var Vc=new Set(["err_blocked_by_client","notallowederror","popup_blocked","popupblocked"]),Hc=["https://www.paypal.com","https://www.sandbox.paypal.com"];function Ea(e,t,n){let r=`We couldn't open ${e}. Try again or choose another payment method.`;return t?n?`${r} Open this page in your system browser, then try again.`:`${r} Allow pop-ups for this site, then try again.`:r}function ml(e){if(e instanceof Error)return e.message;if(typeof e=="object"&&e!==null){let t=e.message;return typeof t=="string"?t:void 0}return typeof e=="string"?e:void 0}function Jr(e){if(typeof e!="string")return;let t=e.trim();return/^[a-z0-9_.-]{1,64}$/i.test(t)?t:void 0}function Sr(e){if(typeof e!="object"||e===null)return;let t=e;return Jr(t.code)??Jr(t.type)??Jr(t.name)}function bo(e){if(!(typeof e!="object"||e===null))return Jr(e.decline_code)}function Zo(e){return typeof e!="object"||e===null?!1:Jr(e.type)?.toLowerCase()==="card_error"||bo(e)!==void 0}function Wc(e){let t=ml(e)?.toLowerCase()??"",n=Sr(e)?.toLowerCase()??"";return Vc.has(n)?!0:/(?:popup|pop-up).{0,40}(?:block|denied|prevent)/i.test(t)||/(?:block|denied|prevent).{0,40}(?:popup|pop-up)/i.test(t)}function Ii(e){if(Sr(e)?.toLowerCase()==="paypal_init_timeout")return!0;let n=ml(e)??"";return n.includes("No ack for postMessage init()")&&Hc.some(r=>n.includes(r))&&n.includes("10000ms")}function Ta(e,t){if(Zo(e))return{errorCode:"PROVIDER_RUNTIME_FAILED",popupBlocked:!1,providerDeclined:!0,terminalReason:"provider_declined"};let r=Wc(e)||t.inAppBrowser&&!t.handoffObserved&&Ii(e);return{errorCode:r?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",popupBlocked:r,providerDeclined:!1,terminalReason:r?"popup_blocked":"provider_error"}}function Dr(e){return Ta(e,{inAppBrowser:!1,handoffObserved:!1}).popupBlocked}import{resolveBillingApiUrl as Gc}from"@flopay/shared";import{useContext as Aa}from"react";function Or(){return Aa(or).flopay}function _i(){return Aa(or).paypalFlopay??null}function Yc(){return Aa(ur)}function fl(){return Aa(or).billingApiUrl||Gc()}function Qo(e){let t=e??(typeof navigator>"u"?"":navigator.userAgent),n=r=>({inAppBrowser:r!=="none",appFamily:r,popupCapability:"unknown"});return t?/FBAN|FBAV|FB_IAB|FBIOS/i.test(t)?n("facebook"):/Instagram/i.test(t)?n("instagram"):/musical_ly|BytedanceWebview|TikTok/i.test(t)?n("tiktok"):/Twitter|Snapchat|Pinterest|LinkedInApp|Line\/|MicroMessenger|GSA\//i.test(t)?n("other_in_app"):/Android.*;\s?wv\)/.test(t)||/(iPhone|iPad|iPod).*AppleWebKit(?!.*Safari)/.test(t)?n("generic_webview"):n("none"):n("none")}function xa(e,t,n){return!e.inAppBrowser||n!=="order"?"popup":t==="app_switch"||t==="redirect"?t:"popup"}import{FLO_INSTRUMENT_SCHEMA_VERSION as Jc}from"@flopay/shared";import{useCallback as Xc,useRef as Ma}from"react";var Zc={"checkout.mount":"checkout_mount","sdk.initialize.ready":"sdk_loaded","provider.ready":"sdk_loaded","checkout.rendered":"form_rendered","vault.widget.ready":"form_rendered","vault.submission.started":"tokenize","payment.tokenization.started":"tokenize","payment.processing.started":"process_attempt","payment.intent.started":"process_attempt","vault.action.required":"3ds_challenge","payment.three_ds.handoff":"3ds_challenge"};function Qc(e){return e==="stripe"||e==="paypal"?e:void 0}function ed(e){let t=Qc(e.provider),n={schemaVersion:Jc,...t?{gateway:t}:{}};if(e.class==="lifecycle"){let r=Zc[e.name];return r?{...n,name:r}:null}return e.class==="card_surface"?{...n,name:"card_expanded"}:e.errorCode==="CHECKOUT_SESSION_CREATE_FAILED"?{...n,name:"checkout_error",phase:"session_create"}:e.errorCode==="SDK_INITIALIZATION_FAILED"||e.errorCode==="PROVIDER_LOAD_FAILED"?{...n,name:"checkout_error",phase:"sdk_load"}:e.errorCode==="PAYMENT_PROCESSING_FAILED"?{...n,name:"checkout_error",phase:e.requestCategory==="intent_create"?"wallets":"process"}:null}var Ri=new Set(["checkout_mount","sdk_loaded","form_rendered","card_expanded"]);function Po(e,t){let n=Ma(e);n.current=e;let r=Ma(new Set),o=Ma(t),i=Ma(t);return Ho(()=>{i.current=t,o.current!==t&&(o.current=t,r.current.clear())},[t]),Xc(s=>{if(i.current!==t)return;let l=ed(s);if(l){if(Ri.has(l.name)){if(r.current.has(l.name))return;r.current.add(l.name)}Ft(()=>n.current?.(l))}},[t])}import{createContext as td}from"react";var ea=td(null);function Ba(){let e="unknown";return{current:()=>e,markAvailable:()=>e!=="unknown"?!1:(e="available",!0),markBlocked:()=>e==="blocked"?!1:(e="blocked",!0)}}var nd=Symbol.for("@flopay/js.telemetry.bridge.v1"),rd=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function od(){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 ad(e){let t=od(),n=(o,i)=>o?o.bind(e):i,r=n(e.now,t.now);return{error:n(e.error,t.error),log:n(e.log,t.log),performance:n(e.performance,t.performance),terminal:n(e.terminal,t.terminal),now:r,elapsed:e.elapsed?e.elapsed.bind(e):o=>Math.max(0,r()-o),setCheckoutContext:n(e.setCheckoutContext,t.setCheckoutContext),beginCheckout:n(e.beginCheckout,t.beginCheckout),disable:n(e.disable,t.disable),subscribe:n(e.subscribe,t.subscribe),flush:n(e.flush,t.flush),destroy:n(e.destroy,t.destroy)}}function Fa(e){let t=globalThis[rd];return ad(t?.(e)??{})}function mn(e){if(e)return e[nd]}import{useCallback as Nr,useEffect as gl,useRef as ta}from"react";function na(e,t){let n=ta(0),r=ta(null),o=ta(null),i=ta(e),s=ta(t?.onHandoffObserved);gl(()=>{i.current=e,s.current=t?.onHandoffObserved},[e,t?.onHandoffObserved]);let l=Nr((v=o.current)=>{v?.timer&&(clearTimeout(v.timer),v.timer=null)},[]),y=Nr(v=>{l();let q=n.current+1;return n.current=q,r.current=null,o.current={generation:q,method:v,timer:null,yieldedControl:!1},q},[l]),f=Nr(v=>{let q=o.current;return v!==void 0&&q?.generation!==v?!1:(l(q),o.current=null,(v===void 0||r.current===v)&&(r.current=null),!0)},[l]),b=Nr(v=>{let q=o.current,Re=v??q?.generation??n.current;(v===void 0||q?.generation===v)&&(l(q),o.current=null),r.current=Re},[l]),g=Nr(v=>r.current===(v??n.current),[]),M=Nr(v=>o.current?.generation===v&&r.current!==v,[]),R=Nr(()=>{let v=o.current;v&&(l(v),!v.yieldedControl&&(v.yieldedControl=!0,s.current?.(v.method)))},[l]),C=Nr(()=>{let v=o.current;!v?.yieldedControl||document.visibilityState!=="visible"||(l(v),v.timer=setTimeout(()=>{v.timer=null,o.current?.generation===v.generation&&(o.current=null,r.current=v.generation,i.current(v.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}))},600))},[l]);return gl(()=>{let v=()=>{document.visibilityState==="visible"?C():R()};return document.addEventListener("visibilitychange",v),window.addEventListener("blur",R),window.addEventListener("focus",C),()=>{document.removeEventListener("visibilitychange",v),window.removeEventListener("blur",R),window.removeEventListener("focus",C),l()}},[l,R,C]),{startAttempt:y,finishAttempt:f,invalidateAttempt:b,isAttemptInvalidated:g,isAttemptCurrent:M,generationRef:n}}import{jsx as Xr,jsxs as xi}from"react/jsx-runtime";var Da=45,pd=1e3,yd=11e3,md={width:"100%",minHeight:Da,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"},fd={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 gd(e){return!e.generationActive||e.kind==="teardown"?{action:"ignore"}:e.kind==="ineligible"?{action:"unavailable"}:e.automaticRetryAllowed&&!e.automaticRetryUsed?{action:"retry"}:{action:"exhaust",report:fd[e.kind]??null}}function hl(e,t){return e==="watchdog_expired"?"paypal_render_timeout":Ii(t)?"paypal_init_timeout":"paypal_init_failure"}function hd(e){let t=e,n=t?.payer??t?.payment_source?.paypal;return{email:n?.email_address?.trim()||void 0,firstName:n?.name?.given_name?.trim()||void 0,lastName:n?.name?.surname?.trim()||void 0}}function vd(e){return e>=500?"5xx":e>=400?"4xx":e>=300?"3xx":"unknown"}function vl({sessionId:e,nonce:t,billingApiUrl:n,email:r,billingName:o,onBuyerIdentityReady:i,clientId:s,environment:l,currency:y,isSubscription:f,providerObjectType:b,approvalPresentation:g,onTokenizedBody:M,onComplete:R,onErrorChange:C,onDecline:v,onTechnicalFailure:q,isProcessing:Re=!1,onLoadStateChange:I,onInitializationStateChange:G,allowAutomaticRetry:Y=!0,onButtonClick:re,runBeforeButtonClick:ve,session:Le,existingOrderId:Ce,telemetry:$e,telemetryContext:vt,onInstrument:Ke,debug:Ne=!1}){let Me=Or(),wt=Po(Ke,e),fe=oa(()=>{if(Me)return null;let x=Fa({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:cd,enabled:$e!==!1});return x.setCheckoutContext(vt??{}),x.beginCheckout(vt??{}),x},[n,Me,$e,vt?.checkoutMode,vt?.layout]),ut=oa(()=>mn(Me),[Me]);Ot(()=>()=>{fe&&fe.flush().catch(()=>{}).finally(()=>fe.destroy())},[fe]);let O=oa(()=>({error:x=>{ut?ut.error(x):fe?.error(x),wt({class:"technical_error",errorCode:x.requestCategory==="intent_create"?"PAYMENT_PROCESSING_FAILED":x.errorCode,requestCategory:x.requestCategory,provider:x.provider})},log:x=>{ut?ut.log(x):fe?.log(x),wt({class:"lifecycle",name:x.name,provider:x.provider})},performance:x=>{ut?ut.performance(x):fe?.performance(x)},terminal:x=>{ut?ut.terminal(x):fe?.terminal(x)},startTiming:()=>ut?.now()??fe?.now()??0,elapsed:x=>ut?.elapsed(x)??Math.max(0,(fe?.now()??x)-x)}),[wt,ut,fe]),Ae=ot(null),yt=ot(0),Be=ot(null),it=ot(null),N=ot(null),ue=ud(ea),ge=ot(null);ge.current||(ge.current=Ba());let K=ue??ge.current,Ge=ot(null),Ve=ot(!1),[L,st]=Lr(!1),[Ye,He]=Lr(!1),[Ee,le]=Lr(0),mt=ot(0),[Q,oe]=Lr(!1),Fe=ot(!1),Je=ot(!1),[lt,z]=Lr(!1),[pt,Xe]=Lr(!1),{request:_,collect:ct,finish:Jt}=ho(),xe=ot({sessionId:e,required:!ra(r?.trim()||Le?.customer?.email?.trim())});xe.current.sessionId!==e&&(xe.current={sessionId:e,required:!ra(r?.trim()||Le?.customer?.email?.trim())});let un=xe.current.required,c=oa(()=>n.replace(/\/+$/,""),[n]),ne=Le?.gateways?.paypal?.providerObjectType??b,k=ne??(f?"subscription":"order"),[$]=Lr(Qo),ft=Le?.gateways?.paypal?.approvalPresentation??g,ze=xa($,ft==="app_switch"?"app_switch":void 0,k),Ue=ne==="order"||ne==="setup_token",xt=oa(()=>JSON.stringify([c,s,y,l??"",k,Ue,ze,e,Ce??""]),[c,s,y,l,Ce,k,Ue,ze,e]),ee=ot(xt),pn=ee.current!==xt,We=ot(Ne),Dt=ot(null),[Rn,Kt]=Lr([]),Te=kr(x=>{We.current&&Kt(qe=>[...qe,`${new Date().toISOString().slice(11,23)} ${x}`])},[]);Ot(()=>{We.current=Ne,Ne&&Te("debug:enabled"),Dt.current?.setEnabled(Ne)},[Te,Ne]);let Ut=ot(M),gn=ot(R),hn=ot(C),kn=ot(v),Nn=ot(q),vn=ot(re),Vt=ot(I),De=ot(G),we=ot(i),Ln=ot(ve),St=ot(Le),bn=ot(r),En=ot(o),Hn=ot(t),Ht=ot(null),Xt=ot(new Map),ln=ot(new Map),kt=ot(!1);Ot(()=>(kt.current=!0,()=>{kt.current=!1}),[]),Ot(()=>{Ut.current=M},[M]),Ot(()=>{we.current=i},[i]),Ot(()=>{gn.current=R},[R]),Ot(()=>{hn.current=C},[C]),Ot(()=>{kn.current=v},[v]),Ot(()=>{Nn.current=q},[q]),Ot(()=>{vn.current=re},[re]),Ot(()=>{Vt.current=I},[I]),Ot(()=>{De.current=G},[G]),Ot(()=>{Ln.current=ve},[ve]),Ot(()=>{St.current=Le},[Le]),Ot(()=>{bn.current=r},[r]),Ot(()=>{En.current=o},[o]),Ot(()=>{Hn.current=t},[t]),Ot(()=>{mt.current=Ee},[Ee]),Ot(()=>{Q&&Ge.current?.focus()},[Q,Ee]);let Mt=kr(()=>{window.setTimeout(()=>{Ge.current?.focus()},0)},[]),yn=kr(()=>{st(!1),le(x=>x+1)},[]),Zt=kr(()=>{oe(!1),(Ae.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??Ae.current)?.focus?.()},[]);Ot(()=>{!L||!Ve.current||(Ve.current=!1,Zt())},[Zt,L,Ee]);let qt=kr((x,qe)=>{let te=qe?.popupBlocked??Dr(x);te&&K.markBlocked();let tn=Ea("PayPal",te,$.inAppBrowser),Pn=Nn.current;if(Pn){let nn=te&&$.inAppBrowser?new Ti(tn,"api_error",{code:qe?.code??"paypal_popup_blocked"}):x;Pn("paypal",nn,qe);return}hn.current?.(tn)},[K,$.inAppBrowser]),Wt=kr(x=>{let qe=Be.current,te=it.current;qe===null||!te||(O.log({...te,popupCapability:K.current(),name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:x}),O.performance({...te,popupCapability:K.current(),stage:"overlay_return",durationMs:O.elapsed(qe),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:x}),Be.current=null)},[K,O]),Tt=kr((x,qe,te)=>{let tn=it.current;Wt("overlay_timeout"),tn&&O.error({...tn,popupCapability:K.current(),errorCode:"REQUEST_TIMEOUT",failureCategory:"provider_runtime",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",statusClass:"timeout",terminalReason:"overlay_timeout"}),qt(qe,{...te,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:ze,terminalReason:"overlay_timeout"}),oe(!0),yn(),Mt()},[Wt,Mt,qt,K,ze,yn,O]),X=kr(()=>{K.markAvailable();let x=it.current;x&&(N.current=x.attempt,O.log({...x,popupCapability:K.current(),name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}))},[K,O]),{finishAttempt:Qt,generationRef:en,invalidateAttempt:ir,isAttemptCurrent:mr,isAttemptInvalidated:Wn,startAttempt:Gt}=na(Tt,{onHandoffObserved:X}),sr=kr(()=>(oe(!1),Gt("paypal")),[Gt]),jt=kr(x=>{ir(x?.generation),x?.showRetry&&oe(!0),x?.remount&&yn(),x?.focus!==!1&&Mt()},[Mt,ir,yn]),A=x=>{let qe=Ht.current;return qe&&ln.current.set(x,qe),x};Ot(()=>{ee.current!==xt&&(ee.current=xt,Fe.current=!1,Je.current=!1,st(!1),He(!1),z(!1),De.current?.("loading"))},[xt]),Ot(()=>{Ft(()=>Vt.current?.(L&&!lt))},[L,lt]);let gt=ld(l);Ot(()=>{let x={attempt:en.current+1,inAppBrowser:$.inAppBrowser,appFamily:$.appFamily,popupCapability:K.current(),presentationMode:ze},qe=()=>({...it.current??x,popupCapability:K.current()}),te={error:p=>O.error({...p,...qe()}),log:p=>O.log({...p,...qe()}),performance:p=>O.performance({...p,...qe()}),terminal:p=>O.terminal({...p,...qe()}),startTiming:O.startTiming,elapsed:O.elapsed},tn=s?`${s.slice(0,6)}\u2026(len ${s.length})`:"(empty)",Pn=typeof navigator>"u"?"(no navigator)":navigator.userAgent;if(Te(`mount clientId=${tn} env=${l??"(unset)"}\u2192${gt??"live"} ccy=${y} sub=${f}`),Te(`ua=${Pn.slice(0,80)}${Pn.length>80?"\u2026":""}`),!s){Te("FAIL: clientId empty \u2014 gateway misconfigured"),z(!0),te.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(!Ae.current){Te("FAIL: containerRef not attached");return}yt.current=te.startTiming(),te.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let nn=!1,fr=!1,he=()=>nn||fr,zn,Gn=!1,jr=()=>{zn=sd(),zn||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),Gn=!0},Yn=null,Jn=!1,Yt=null,Er=!1,gr=()=>{!Yt||Er||(Er=!0,Yt.close().catch(()=>{}))},Tn=!1,hr=!1,Xn=Ae.current,Zn=null,vr=null,Qn=[],It=null,Un=!1,lr=!1,qn=null,Cn=p=>{if(!p||typeof p.getBoundingClientRect!="function")return"(no rect)";let u=p.getBoundingClientRect();return`${Math.round(u.width)}\xD7${Math.round(u.height)}`},nt=p=>{if(!p)return"(empty)";try{let u=new URL(p,typeof window>"u"?"https://localhost":window.location.href),P=u.pathname.toLowerCase();return P.includes("checkcaptcha")||P.includes("captcha")?`CAPTCHA(${u.host}${P})`:P.includes("risk")||P.includes("challenge")?`RISK(${u.host}${P})`:P.includes("smart/buttons")?`smart-buttons(${u.host})`:`${u.host}${P}`.slice(0,100)}catch{return p.slice(0,80)}},In=p=>{let u=p.getAttribute("src"),P=p.getAttribute("srcdoc"),B=p.getAttribute("name"),ie=p.getAttribute("sandbox"),Z=[];return u&&Z.push(`src=${nt(u)}`),P&&Z.push(`srcdoc[${P.length}ch]`),!u&&!P&&Z.push("src=(empty) srcdoc=(empty)"),B&&Z.push(`name=${B.slice(0,40)}`),ie!==null&&Z.push(`sandbox="${ie.slice(0,40)}"`),Z.join(" ")},cn=p=>{if(!(p instanceof HTMLIFrameElement))return"";try{let u=p.contentDocument;if(!u)return"cd=null";let P=u.body?.children.length??0,B=u.body?.innerHTML.length??0,ie=u.head?.innerHTML.length??0;return`cd=same-origin readyState=${u.readyState} body[${P}children,${B}ch] head[${ie}ch]`}catch(u){return`cd=cross-origin(${u.message.slice(0,30)})`}},jn=[],$r=p=>{if(he())return;let u=p.message??String(p.error??"(no message)");u&&(u.toLowerCase().includes("paypal")||u.toLowerCase().includes("zoid")||u.toLowerCase().includes("postrobot")||u.toLowerCase().includes("storage"))&&(Te(`window:error ${u.slice(0,140)}`),jn.push(u))},$n=p=>{if(he())return;let u=p.reason instanceof Error?p.reason.message:String(p.reason??"(no reason)");u&&(u.toLowerCase().includes("paypal")||u.toLowerCase().includes("zoid")||u.toLowerCase().includes("postrobot")||u.toLowerCase().includes("storage"))&&(Te(`window:rejection ${u.slice(0,140)}`),jn.push(u))},br={value:0},An=()=>{Zn?.disconnect(),Zn=null,vr?.disconnect(),vr=null;for(let p of Qn.splice(0))clearTimeout(p);lr=!1,Un&&typeof window<"u"&&(window.removeEventListener("error",$r),window.removeEventListener("unhandledrejection",$n)),Un=!1},xn=()=>{if(!(Un||he()||Tn)){if(Un=!0,jn.length=0,br.value=0,typeof window<"u"&&(window.addEventListener("error",$r),window.addEventListener("unhandledrejection",$n)),typeof PerformanceObserver<"u")try{vr=new PerformanceObserver(p=>{if(!he())for(let u of p.getEntries()){if(!u.name.toLowerCase().includes("paypal"))continue;br.value+=1;let P=Math.round(u.duration);Te(`net ${P}ms ${u.name.slice(0,90)}`)}}),vr.observe({type:"resource",buffered:!0})}catch{}qn?.()}},Kr=()=>{It&&(clearTimeout(It),It=null)},Kn=()=>{An(),Kr()},Vr={setEnabled:p=>{p?xn():An()}};Dt.current=Vr,We.current&&xn();let rn=p=>{if(!p)return!1;let u=p.toLowerCase();return u.includes("zoid destroyed")||u.includes("destroyed all components")||u.includes("window closed")||u.includes("detected container element removed")},S=p=>{if(he()||rn(p))return;let u=Br(p)??p;Ft(()=>hn.current?.(u))},m=(p,u)=>{if(nn||Jn)return;Jn=!0,fr=!0,Kn(),gr();let P=gd({kind:p,generationActive:!0,automaticRetryAllowed:Y,automaticRetryUsed:Fe.current});if(P.action==="retry"){Fe.current=!0,st(!1),Xe(!1),He(!0),De.current?.("retrying"),Yn=setTimeout(()=>{nn||le(B=>B+1)},pd);return}if(st(!1),Xe(!1),He(!1),z(!0),P.action!=="ignore"){if(De.current?.("exhausted"),P.action==="unavailable"){console.error("[FloPay] DirectPayPal load/render failure:",u);return}if(P.report){let B=Ta({code:hl(p,u),message:u},{inAppBrowser:$.inAppBrowser,handoffObserved:!1});B.popupBlocked&&K.markBlocked(),te.error({errorCode:B.popupBlocked?B.errorCode:P.report.errorCode,stage:P.report.stage,operationOutcome:P.report.operationOutcome,provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime",terminalReason:B.terminalReason})}Je.current||(Je.current=!0,console.error("[FloPay] Direct PayPal initialization failed:",hl(p,u)))}};z(!1);let W=async(p,u=Ht.current)=>{if(he())return;let P=u?.sessionId??e;if(Ut.current){await Ut.current(p,{sessionId:P,accountPatch:u?.accountPatch,nonce:u?.nonce});return}let B=te.startTiming();te.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let ie=()=>{te.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),te.performance({stage:"processing",durationMs:te.elapsed(B),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment"})};try{let Z=St.current,j=u?.accountPatch?.email??bn.current,ae=u?.accountPatch?.userId??Z?.customer?.id??Z?.accountData?.userId??"",Se=u?.accountPatch?.firstName??Z?.customer?.firstName??Z?.accountData?.firstName,bt=u?.accountPatch?.lastName??Z?.customer?.lastName??Z?.accountData?.lastName,H=await new Ei(c,{telemetry:!1}).processPayment(ae,{sessionId:P,nonce:u?.nonce??Hn.current,paymentMethodCategory:"paypal",tokenizedData:p,accountData:{userId:ae,email:j??Z?.customer?.email??"",...Se?{firstName:Se}:{},...bt?{lastName:bt}:{},country:u?.accountPatch?.country??Z?.customer?.country??Z?.accountData?.country??void 0,zip:u?.accountPatch?.zip??Z?.customer?.zip??Z?.accountData?.zip??void 0}});if(H.ok){if(fr||nn&&kt.current)return;ie(),te.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),Ft(()=>gn.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(he())return;let T=await H.json().catch(()=>null),U=T?.message??"PayPal payment failed.",ke=Br(U)??U;ie(),H.status===400&&(typeof T?.declineCode=="string"||!Array.isArray(T?.fields))?te.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}):H.status===400||H.status===422?te.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx",terminalReason:"approved"}):te.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:vd(H.status),failureCategory:H.status>=500?"server_error":void 0}),S(ke),Ft(()=>kn.current?.(dn("paypal",ke,{code:T?.code,declineCode:T?.declineCode})));return}catch(Z){if(he())return;ie(),te.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let j=Z instanceof Error?Z.message:"PayPal payment failed.",ae=Br(j)??j;S(ae),Ft(()=>kn.current?.(dn("paypal",ae)));return}},F=()=>new Ti("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),be=p=>he()?Promise.reject(F()):Promise.resolve(p),Nt=async p=>{if(he())throw F();Gn||jr();let u=Ht.current,P=u?.sessionId??e,B=u?.nonce??Hn.current;te.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let ie;try{ie=await new Ei(c,{telemetry:!1}).createSessionIntent(P,B??"",Ue?{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:Ai,paymentMethodId:null,intentKind:k==="setup_token"?"setup":"payment"}:{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"},{idempotencyKey:zn})}catch(Z){throw te.error({...id(Z,"PAYMENT_PROCESSING_FAILED","unknown"),stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"}),Z}if(he())throw F();if(ie.provider!=="paypal"||ie.providerObjectType!==k)throw new Error(p);return te.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),ie.providerObjectId},ye=(p,u)=>{let P=u?.nonce??Hn.current;if(!P)return;let B=u?.sessionId??e,ie=bo(p)??Sr(p)??"provider_declined";new Ei(c,{telemetry:!1}).reportSessionIntentDecline(B,P,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:ie}).catch(()=>{})},pe=Ee;Te("loadScript:scheduled (deferred 1 tick)");let E=null,V=setTimeout(()=>{if(nn){Te("loadScript:skipped (cancelled before defer ran)");return}Te("loadScript:start");let p=gt==="live"?"production":gt,u={};k==="subscription"?u={intent:"subscription",vault:!0}:k==="order"&&(u={intent:"capture"}),E=dd({clientId:s,currency:y,...u,...p?{environment:p}:{},...p==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}});let P=!1;E.then(B=>{if(P=!0,Te(`loadScript:resolved inactive=${he()} ns=${!!B} buttons=${!!B?.Buttons}`),he())return;if(!B?.Buttons){Te("FAIL: namespace missing Buttons factory"),m("namespace_unusable","PayPal SDK did not expose the Buttons factory.");return}te.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),te.performance({stage:"provider_ready",durationMs:te.elapsed(yt.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),te.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let ie=async(H,T)=>{if(he()||mt.current!==pe)return;let U=H.vaultSetupToken??H.subscriptionID??H.orderID??"",ke=U?ln.current.get(U):Xt.current.get(pe);if(!(!ke||!mr(ke.generation))&&Qt(ke.generation)){ln.current.delete(U),Xt.current.delete(ke.surfaceKey),Wt("approved");try{if(Xe(!0),Ft(()=>hn.current?.(null)),!U)throw new Ti("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});let Ie=St.current,ht=Yr(En.current??[Ie?.customer?.firstName,Ie?.customer?.lastName].filter(Boolean).join(" ")),je=On({email:ke.accountPatch?.email?.trim()||bn.current?.trim()||Ie?.customer?.email?.trim(),firstName:ke.accountPatch?.firstName?.trim()||ht.firstName,lastName:ke.accountPatch?.lastName?.trim()||ht.lastName});if(!ra(je.email)||!(je.firstName||je.lastName))try{let on=hd(await T?.order?.get?.());je=On({email:on.email||je.email,firstName:on.firstName||je.firstName,lastName:on.lastName||je.lastName})}catch{}if((we.current||un)&&!ra(je.email)){let on=await ct("PayPal",je);if(!on)return;je=on}ra(je.email)&&(ke.accountPatch=On({...ke.accountPatch,...je}),await we.current?.(je));let Mn;k==="setup_token"?Mn={id:U,type:"paypal_setup_token",isPaypal:!0,gateway:"paypal",paymentMethodType:Ai}:Ue?Mn={id:U,isPaypal:!0,gateway:"paypal",paymentMethodType:Ai}:Mn={id:U,isPaypal:!0},await W(Mn,ke)}catch(Ie){S(Ie instanceof Error?Ie.message:"PayPal capture failed.")}finally{he()||Xe(!1)}}},Z=H=>{let T=Ce?()=>be(Ce):()=>Nt(H);return async()=>A(await T())},j=B.Buttons({style:{layout:"horizontal",height:Da,tagline:!1},...ze==="app_switch"?{appSwitchWhenAvailable:!0}:{},onClick:async(H,T)=>{if(he()){await T.reject();return}jr();let U=Ln.current,ke={};if(U)try{let je=await U("paypal");if(he()){await T.reject();return}if(!je.proceed){Ht.current=null,Xt.current.delete(pe),await T.reject();return}ke={sessionId:je.sessionId,accountPatch:je.accountPatch,nonce:je.nonce}}catch(je){Te(`onClick:runBeforeButtonClick rejected msg=${(je instanceof Error?je.message:String(je)).slice(0,120)}`),Ht.current=null,Xt.current.delete(pe),await T.reject();return}Ft(()=>vn.current?.("paypal"));let Ie=sr(),ht={generation:Ie,surfaceKey:pe,...ke};Ht.current=ht,Xt.current.set(pe,ht),it.current={...x,attempt:Ie},await T.resolve(),te.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),te.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),Be.current=te.startTiming()},createOrder:k==="order"?Z("Failed to create PayPal order."):void 0,createSubscription:k==="subscription"?Z("Failed to create PayPal subscription."):void 0,createVaultSetupToken:k==="setup_token"?async()=>A(await Nt("Failed to create PayPal setup token.")):void 0,onApprove:ie,onCancel:()=>{if(he())return;let H=Xt.current.get(pe)??Ht.current;H&&Xt.current.delete(H.surfaceKey),Ht.current=null,Wt("cancelled"),te.terminal({outcome:"payment_cancelled",terminalReason:"cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),Ve.current=!0,jt({generation:H?.generation,remount:!0,focus:!1})},onError:H=>{if(he()||mt.current!==pe)return;let T=H instanceof Error?H.message:"PayPal failed to render.";if(Te(`onError rendered=${Tn} msg=${T.slice(0,120)}`),Tn){let U=Xt.current.get(pe)??Ht.current;if(U&&!mr(U.generation)||!U&&Wn())return;if(rn(T)){Qt(U?.generation);return}let{errorCode:ke,popupBlocked:Ie,providerDeclined:ht,terminalReason:je}=Ta(H,{inAppBrowser:$.inAppBrowser,handoffObserved:U!=null&&N.current===U.generation});if(Ie&&K.markBlocked(),Wt(je),ht){te.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:je}),ye(H,U),Ft(()=>kn.current?.(dn("paypal",T))),U&&Xt.current.delete(U.surfaceKey),Ht.current=null,Qt(U?.generation);return}te.error({errorCode:ke,failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",terminalReason:je}),U&&Xt.current.delete(U.surfaceKey),Ht.current=null,jt({generation:U?.generation,remount:!0,showRetry:!0,focus:!0}),qt(H,{code:"paypal_runtime_failed",popupBlocked:Ie,telemetryReported:!0,provider:"paypal",paymentMethodCategory:"paypal",presentationMode:ze,terminalReason:je});return}m(rn(T)?"teardown":"pre_ready_callback",T)}}),ae=j.isEligible();if(Te(`isEligible=${ae}`),te.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!ae){st(!1),m("ineligible","PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}hr=!0,Yt=j,qn=()=>{if(!Un||lr||he()||Tn)return;lr=!0,Te(`container:dims ${Cn(Xn)} visibility=${typeof document>"u"?"(no document)":document.visibilityState}`),typeof MutationObserver<"u"&&(Zn=new MutationObserver(T=>{if(!he()){for(let U of T)if(U.type==="childList")U.addedNodes.forEach(ke=>{if(!(ke instanceof Element))return;let Ie=ke.tagName.toLowerCase(),ht=(ke.getAttribute("title")??"").slice(0,40),je=Ie==="iframe"?` ${In(ke)}`:"";Te(`child+ ${Ie}${ht?` title="${ht}"`:""}${je} dims=${Cn(ke)}`)});else if(U.type==="attributes"&&U.target instanceof Element){let ke=U.target;if(ke.tagName.toLowerCase()!=="iframe")continue;let Ie=U.attributeName;(Ie==="src"||Ie==="srcdoc")&&Te(`attr~ iframe ${Ie}=${Ie==="srcdoc"?`[${(ke.getAttribute("srcdoc")??"").length}ch]`:nt(ke.getAttribute("src"))} dims=${Cn(ke)}`)}}}),Zn.observe(Xn,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let H=T=>{if(he()||Tn)return;let U=Xn.querySelectorAll("iframe"),ke=typeof document<"u"&&"hasStorageAccess"in document;Te(`watchdog:${T} container=${Cn(Xn)} children=${Xn.childElementCount} iframes=${U.length} visibility=${typeof document>"u"?"(no document)":document.visibilityState} cookies=${typeof navigator>"u"?"?":navigator.cookieEnabled} hasStorageAccessApi=${ke} paypalNetRequests=${br.value}`),U.forEach((Ie,ht)=>{let je=(Ie.getAttribute("title")??"").slice(0,40);Te(` iframe[${ht}] ${Cn(Ie)}${je?` title="${je}"`:""} ${In(Ie)}`);let Mn=cn(Ie);Mn&&Te(` ${Mn}`)}),jn.length===0&&Te(" (no PayPal/zoid window errors captured)")};Qn.push(setTimeout(()=>H("3s"),3e3)),Qn.push(setTimeout(()=>H("8s"),8e3)),Qn.push(setTimeout(()=>H("15s"),15e3))},qn(),Te("render:start");let bt=te.startTiming();It=setTimeout(()=>{he()||Tn||(Te("watchdog:11s retryable render timeout"),m("watchdog_expired","PayPal Buttons render did not settle within 11000ms."))},yd);let _e=j.render(Xn);(async()=>{try{if(await _e,Te(`render:resolved inactive=${he()}`),Kn(),he()){gr();return}Tn=!0,st(!0),He(!1),De.current?.("ready"),te.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),te.performance({stage:"checkout_render",durationMs:te.elapsed(bt),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}catch(H){let T=H instanceof Error?H.message:"PayPal failed to render.";Te(`render:rejected msg=${T.slice(0,120)}`),Kn(),m(rn(T)?"teardown":"render_rejected",T)}})()}).catch(B=>{let ie=B instanceof Error?B.message:"PayPal operation failed.";Te(`provider:failed msg=${ie.slice(0,120)}`);let Z="script_rejected";P&&rn(ie)?Z="teardown":P&&hr&&(Z="render_rejected"),m(Z,ie)})},0);return()=>{nn=!0,clearTimeout(V),Yn&&clearTimeout(Yn),Kn(),Dt.current===Vr&&(Dt.current=null),gr(),Be.current=null,it.current=null}},[Y,c,s,y,l,k,ze,Ue,e,Ce,Ee,O,ct,un,Te,Wt]);let Ze=Ne?xi("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:lt?"#fef2f2":"#f3f4f6",border:`1px solid ${lt?"#fca5a5":"#d1d5db"}`,borderRadius:6,color:"#111827",font:"11px/1.35 ui-monospace, SFMono-Regular, Menlo, monospace",whiteSpace:"pre-wrap",wordBreak:"break-word",maxHeight:220,overflowY:"auto"},children:[`FloPay/DirectPayPal-debug (ready=${L} failed=${lt})`,Rn.length===0?`
|
|
2
2
|
(waiting for first lifecycle event\u2026)`:`
|
|
3
|
-
${
|
|
4
|
-
`)}`]}):null;return xe&&!N?$e?Wr("div",{children:se}):null:bi("div",{children:[se,Ee&&Wr(yo,{identity:Ee.identity,methodLabel:Ee.methodLabel,testId:"flopay-direct-paypal-identity-pane",onComplete:dn,onCancel:()=>dn(null)}),bi("div",{"aria-hidden":ut||Ee?!0:void 0,style:ut||Ee?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:Ia},children:[!de&&!ut&&Wr("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"}}),Wr("div",{ref:Ie,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,role:"group","aria-label":"PayPal payment method",style:{minHeight:Ia,display:"flex",opacity:de?1:0},"aria-busy":qe||Pe},x)]},x),re&&Wr("button",{ref:U,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:Sn,style:Zc,children:"Try PayPal again"})]})}function ka(e){return Wr(ol,{...e})}function al(e){return Wr(ol,{...e})}import{jsx as il,jsxs as sd}from"react/jsx-runtime";function ho({children:e,margin:t,icon:n=!0,styleOverride:r}){return sd("div",{role:"alert","data-testid":"flopay-error",style:{margin:t,padding:"0.625rem 0.875rem",background:"#FEF2F2",border:"1px solid #FECACA",borderRadius:"8px",color:"#991B1B",fontSize:"0.85rem",fontWeight:600,...n?{display:"flex",alignItems:"center",gap:"0.5rem"}:{},...r??{}},children:[n&&il("svg",{"aria-hidden":"true",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:il("path",{d:"M12 9v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z",stroke:"#DC2626",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}),e]})}import{foldIntoProducts as ld,resolveSessionCurrency as cd}from"@flopay/shared";function vo(){return typeof window<"u"&&typeof window.sessionStorage<"u"}var Si=":idempotency-key";function wi(e,t){if(!vo())return null;let n=window.sessionStorage.getItem(e);if(!n)return null;try{let r=JSON.parse(n);return!r||typeof r.sid!="string"||!r.sid||"canonicalIdentity"in r&&r.canonicalIdentity!==t?null:{..."canonicalIdentity"in r?{canonicalIdentity:t}:{},sid:r.sid,nonce:typeof r.nonce=="string"?r.nonce:void 0}}catch{return{sid:n}}}function Ii(e,t){if(!vo())return null;try{let n=window.sessionStorage.getItem(e+Si);if(!n)return null;try{let r=JSON.parse(n);return typeof r=="string"?r?{idempotencyKey:r}:null:!r||typeof r.idempotencyKey!="string"||!r.idempotencyKey||"canonicalIdentity"in r&&r.canonicalIdentity!==t?null:{..."canonicalIdentity"in r?{canonicalIdentity:t}:{},idempotencyKey:r.idempotencyKey}}catch{return{idempotencyKey:n}}}catch{return null}}function _a(e,t){if(vo())try{wi(e,t)&&window.sessionStorage.removeItem(e)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout session cache.",n)}}function Ra(e,t){if(_a(e,t),!!vo())try{Ii(e,t)&&window.sessionStorage.removeItem(e+Si)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout idempotency key.",n)}}function Ea(e,t,n,r){if(vo())try{window.sessionStorage.setItem(e,JSON.stringify(r?{canonicalIdentity:t,sid:n,nonce:r}:{canonicalIdentity:t,sid:n}))}catch(o){console.warn("[FloPayCheckout] Failed to persist checkout session cache.",o)}}function Ta(e,t,n){if(vo())try{window.sessionStorage.setItem(e+Si,JSON.stringify({canonicalIdentity:t,idempotencyKey:n}))}catch(r){console.warn("[FloPayCheckout] Failed to persist checkout idempotency key.",r)}}function Ci(e,t){return`${e}:${t.totalAmount??""}:${t.overrideAmount??""}:${t.quantity??1}:${t.currency??""}`}function dd(e){if(e==null)return e;let t=JSON.stringify(Object.entries(e).sort(([s],[l])=>s<l?-1:s>l?1:0)),n=1779033703,r=3144134277,o=1013904242,i=2773480762;for(let s=0;s<t.length;s++){let l=t.charCodeAt(s);n=r^Math.imul(n^l,597399067),r=o^Math.imul(r^l,2869860233),o=i^Math.imul(o^l,951274213),i=n^Math.imul(i^l,2716044179)}return n=Math.imul(o^n>>>18,597399067),r=Math.imul(i^r>>>22,2869860233),o=Math.imul(n^o>>>17,951274213),i=Math.imul(r^i>>>19,2716044179),n^=r^o^i,r^=n,o^=n,i^=n,[n,r,o,i].map(s=>(s>>>0).toString(16).padStart(8,"0")).join("")}function Po(e,t=!1){let n=e?.account?.email?.trim().toLowerCase()??"",r={c:e?.clientId,cur:e?.currency??"",captureMethod:e?.captureMethod??"",a:{e:n,u:n?"":e?.account?.userId??"",country:e?.account?.country??""},successUrl:e?.successUrl,cancelUrl:e?.cancelUrl,p:e?.products?.map(o=>Ci(`${o.type??""}:${o.code??o.providerItemId??o.providerPlanId??""}`,o)).sort(),i:e?.items?.map(o=>Ci(o.code??o.providerItemId??"",o)).sort(),s:e?.subscriptions?.map(o=>Ci(o.code??o.providerPlanId??"",o)).sort(),couponCodes:e?.couponCodes?[...e.couponCodes].sort():void 0,checkoutMetadata:dd(e?.checkoutMetadata),...t?{tagsData:e?.tagsData,utmMetadata:e?.utmMetadata,tokenizedData:e?.tokenizedData,checkoutMode:e?.checkoutMode??"full"}:{}};return JSON.stringify(r)}function sl(e,t=!1){let n=Po(e,t),r=0;for(let o=0;o<n.length;o++)r=(r<<5)-r+n.charCodeAt(o)|0;return`flopay_session_${Math.abs(r).toString(36)}`}function ll(e,t){if(!e?.customer||!e.products||t.checkoutMetadata!==void 0)return!1;let n=t.account.email?.trim().toLowerCase()??"",r=e.customer.email?.trim().toLowerCase()??"";if((n?r!==n:e.customer.id!==t.account.userId)||(t.account.country??"").trim().toUpperCase()!==(e.customer.country??"").trim().toUpperCase()||e.successUrl!==t.successUrl||e.cancelUrl!==t.cancelUrl||(e.captureMethod??"automatic")!==(t.captureMethod??"automatic"))return!1;let o=cd(t.currency,t.items,t.subscriptions,t.products);if(!o||e.currency.toUpperCase()!==o.toUpperCase())return!1;let i=(t.products??ld(t.items,t.subscriptions)).map(f=>({type:f.type,code:f.code??f.providerItemId??f.providerPlanId??"",quantity:f.quantity??1,totalAmount:f.totalAmount,overrideAmount:f.overrideAmount??null,currency:(f.currency??o).toUpperCase()})).sort((f,C)=>`${f.code}:${f.type??""}`.localeCompare(`${C.code}:${C.type??""}`)),s=e.products.map(f=>({type:f.type,code:f.code??"",quantity:f.quantity??1,totalAmount:f.totalAmount,overrideAmount:f.overrideAmount??null,currency:(f.currency??e.currency).toUpperCase()})).sort((f,C)=>`${f.code}:${f.type??""}`.localeCompare(`${C.code}:${C.type??""}`));if(i.length!==s.length)return!1;for(let[f,C]of i.entries()){let h=s[f];if(h===void 0||C.code!==h.code||C.type!==void 0&&C.type!==h.type||C.quantity!==h.quantity||C.totalAmount!==h.totalAmount||C.overrideAmount!==h.overrideAmount||C.currency!==h.currency)return!1}let l=[...t.couponCodes??[]].sort(),p=[...e.coupons??[]].sort();return l.length===p.length&&l.every((f,C)=>f===p[C])}import{resolveBillingApiUrl as ud}from"@flopay/shared";import{useEffect as Nr,useMemo as pd,useRef as cl,useState as dl}from"react";import{jsx as md}from"react/jsx-runtime";function Aa({flopay:e,paypalFlopay:t,options:n,onInstrument:r,children:o}){let[i,s]=dl(e instanceof Promise?null:e),[l,p]=dl(t instanceof Promise||!t?null:t),f=cl(null),C=cl(null),h=go(r);Nr(()=>{h({class:"lifecycle",name:"checkout.mount"})},[h]),Nr(()=>{i&&h({class:"lifecycle",name:"sdk.initialize.ready"})},[h,i]),Nr(()=>{if(i)return Qt(i)?.subscribe?.(h)},[h,i]),Nr(()=>{if(!(!l||l===i))return Qt(l)?.subscribe?.(h)},[h,i,l]),Nr(()=>{if(!i)return;let _=Qt(i);return f.current=_?.beginCheckout()??_?.now()??0,_?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{_?.log({name:"checkout.unmount",stage:"unmount"})}},[i]),Nr(()=>{let _=!1;return e instanceof Promise?e.then(ae=>{_||s(ae)},()=>{_||h({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"})}):s(e),()=>{_=!0}},[h,e]),Nr(()=>{let _=!1;if(!t){p(null);return}return t instanceof Promise?t.then(ae=>{_||p(ae)},()=>{_||h({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED",provider:"paypal"})}):p(t),()=>{_=!0}},[h,t]),Nr(()=>{if(!i||C.current===i)return;C.current=i;let _=Qt(i);_?.log({name:"checkout.rendered",stage:"checkout_render"}),h({class:"lifecycle",name:"checkout.rendered"}),_?.performance({stage:"checkout_render",durationMs:_.elapsed(f.current??0),durationMode:"machine"})},[h,i]);let m=ud(n?.billingApiUrl),w=pd(()=>({flopay:i,paypalFlopay:l,billingApiUrl:m,emitInstrument:h}),[i,l,m,h]);return md(er.Provider,{value:w,children:o})}var xa="flopay_recent_completion_";function bo(e){if(!(!e||typeof window>"u"))try{let t={expiresAt:Date.now()+6e4};window.sessionStorage.setItem(xa+e,JSON.stringify(t))}catch{}}function ki(e){if(!e||typeof window>"u")return!1;try{let t=window.sessionStorage.getItem(xa+e);if(!t)return!1;let n=JSON.parse(t);return typeof n?.expiresAt!="number"||n.expiresAt<=Date.now()?(window.sessionStorage.removeItem(xa+e),!1):!0}catch{return!1}}async function Ma(e,t){e.current?.abort();let n=new AbortController;e.current=n;try{return await t(n.signal)}finally{e.current===n&&(e.current=null)}}import{loadFloPay as ul,PaymentAPI as Ri}from"@flopay/js";import{classifyPaymentRejection as yd,FloPayError as Pt,isAuthorizationOnlySession as fd,isSetupIntentClientSecret as gd,normalizeCheckoutFailureOutcome as pl}from"@flopay/shared";var Xo="card",hd=1e3,yl=3e5;async function vd(e,t,n){if(n){if(typeof e.retrieveSetupIntent!="function")return null;let{setupIntent:i,error:s}=await e.retrieveSetupIntent(t);return{error:s,intent:i??null}}if(typeof e.retrievePaymentIntent!="function")return null;let{paymentIntent:r,error:o}=await e.retrievePaymentIntent(t);return{error:o,intent:r??null}}async function Pd(e,t,n,r){if(r){if(typeof e.confirmCardSetup!="function")return null;let{setupIntent:s,error:l}=await e.confirmCardSetup(t,n);return{error:l,intent:s??null}}if(typeof e.confirmCardPayment!="function")return null;let{paymentIntent:o,error:i}=await e.confirmCardPayment(t,n);return{error:i,intent:o??null}}function Zo(e){return new Pt("Card authentication was cancelled.","api_error",{code:"three_ds_aborted",cause:e})}function Ei(e,t){return Object.assign(e,{checkoutMethod:t})}function _r(e,t){let n=e instanceof Pt?e:new Pt(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 Jo(e,t){try{return await e()}catch(n){throw _r(n,t)}}function fl(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 bd(e){return e.status==="succeeded"||e.status==="authorized"||e.status==="declined"}async function Ti(e){if(typeof document>"u"||typeof window>"u")throw new Pt("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});if(e.signal?.aborted)throw new Pt("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"});let t=1e3,n=15e3,r=`${e.billingApiUrl.replace(/\/$/,"")}/v1/checkouts/sessions/${encodeURIComponent(e.sessionId)}/3ds/complete`,o=async()=>{let h=new AbortController,m=()=>h.abort();e.signal?.aborted?h.abort():e.signal?.addEventListener("abort",m);let w=window.setTimeout(()=>h.abort(),n);try{let _=await fetch(r,{method:"POST",headers:{"x-checkout-session-token":e.nonce,"content-type":"application/json"},body:"{}",signal:h.signal});if(!_.ok)return{status:"unknown"};let ae=await _.json().catch(()=>null);return Cd(ae)}catch{return{status:"unknown"}}finally{window.clearTimeout(w),e.signal?.removeEventListener("abort",m)}},i,s=()=>e.pollCompletionEndpoint!==!1?o():(i??(i=o()),i),l=document.activeElement instanceof HTMLElement?document.activeElement:null,p=document.createElement("div");p.setAttribute("data-flopay-auto-3ds-overlay","1"),p.setAttribute("role","dialog"),p.setAttribute("aria-modal","true"),p.setAttribute("aria-label","Card authentication"),p.style.cssText=["position:fixed","inset:0","z-index:2147483647","background:rgba(15,23,42,0.6)","display:flex","align-items:center","justify-content:center","padding:16px"].join(";");let f=document.createElement("iframe");f.setAttribute("title","Card authentication"),f.setAttribute("allow","payment"),f.tabIndex=0,f.style.cssText=["width:min(100%,460px)","height:min(100%,640px)","border:0","border-radius:12px","background:#fff","box-shadow:0 12px 30px rgba(0,0,0,0.35)"].join(";");let C=null;try{C=new URL(e.billingApiUrl,window.location.href).origin}catch{C=null}try{let h=await new Promise((m,w)=>{let _=!1,ae=0,Y=0,Pe=0,S=!1,G=()=>{window.clearTimeout(ae),window.clearInterval(Y),window.clearTimeout(Pe),window.removeEventListener("message",Fe),f.removeEventListener("load",ce),e.signal?.removeEventListener("abort",Te)},X=async()=>{if(!(_||S)){S=!0;try{let ve=await s();if(_||!bd(ve))return;_=!0,G(),m(ve)}finally{S=!1}}},ce=()=>{e.pollCompletionEndpoint!==!1&&(window.clearTimeout(Pe),Pe=window.setTimeout(()=>{X()},250))},Te=()=>{_||(_=!0,G(),w(new Pt("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"})))},Fe=ve=>{if(ve.source!==f.contentWindow||C&&ve.origin!==C)return;let Ue=ve.data;!Ue||typeof Ue!="object"||Ue.source!=="flopay-vault-3ds-return"||_||(_=!0,G(),m(null))};ae=window.setTimeout(()=>{_||(_=!0,G(),w(new Pt("Card authentication timed out.","api_error",{code:"three_ds_timeout"})))},yl),e.pollCompletionEndpoint!==!1&&(Y=window.setInterval(()=>{X()},t)),f.addEventListener("load",ce),window.addEventListener("message",Fe),e.signal?.addEventListener("abort",Te),f.src=e.nextActionRedirectUrl,p.appendChild(f),document.body.appendChild(p),f.focus(),e.signal?.aborted&&Te()});return h||await s()}finally{p.parentNode?.removeChild(p),l?.isConnected&&l.focus()}}async function Co(e,t){let n=t.nonce??t.session.clientSecret,r=new Ri(t.billingApiUrl,{telemetry:!1}),o=new AbortController,i=new AbortController,s=()=>{o.abort(t.signal.reason),i.abort(t.signal.reason)};t.signal.aborted?s():t.signal.addEventListener("abort",s,{once:!0});let l=Ti({billingApiUrl:t.billingApiUrl,sessionId:t.sessionId,nonce:n,nextActionRedirectUrl:e.nextActionRedirectUrl,signal:o.signal,pollCompletionEndpoint:!1}),p=null,f=()=>(p??(p=r.waitForCheckoutSessionCompletion(t.sessionId,{initialDelayMs:hd,nonce:n,statusUrl:`${t.billingApiUrl.replace(/\/+$/,"")}/v1/checkouts/sessions/${encodeURIComponent(t.sessionId)}/status`,continueAfterActionRequired:!0,timeoutMs:yl,signal:i.signal})),p),C=f(),h;try{let w=await Promise.race([l.then(_=>({kind:"challenge",outcome:_})),C.then(_=>({kind:"status",session:_}))]);if(w.kind==="status")o.abort(),h=w.session;else{if(w.outcome.status==="declined")throw gr({type:w.outcome.declineReason??"authorization_declined",message:"Card was declined.",gatewayErrorCode:w.outcome.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:"card"});h=await f()}}catch(w){throw t.signal.aborted||w instanceof Error&&w.name==="AbortError"?Zo(w):w}finally{t.signal.removeEventListener("abort",s),o.abort(),i.abort()}let m=h.data.session;if(!Mr(m))throw po(m);return{...Sr(m,t.sessionId),checkoutMethod:"card"}}function Cd(e){if(!e||typeof e!="object")return{status:"unknown"};let t=typeof e.status=="string"?e.status:"unknown",n=typeof e.providerIntentId=="string"?e.providerIntentId:null;switch(t){case"succeeded":return{status:"succeeded",providerIntentId:n};case"authorized":return{status:"authorized",providerIntentId:n};case"declined":return{status:"declined",providerIntentId:n,declineReason:typeof e.declineReason=="string"?e.declineReason:null,gatewayDeclineReason:typeof e.gatewayDeclineReason=="string"?e.gatewayDeclineReason:null};case"requires_action":return{status:"requires_action",providerIntentId:n,nextActionRedirectUrl:typeof e.nextActionRedirectUrl=="string"?e.nextActionRedirectUrl:null};case"pending":return{status:"pending",providerIntentId:n};case"timeout":return{status:"timeout",providerIntentId:n};case"no_attempt":return{status:"no_attempt"};default:return{status:"unknown"}}}function gr(e,t="Payment failed. Please try again.",n){let r=n?.checkoutMethod??e?.checkoutMethod??(e?.type==="paypal_redirect_required"?"paypal":"card"),o=e?.message??t,i=xr(o)??o,s=Ei(new Pt(i,"api_error",{code:e?.code??pl(e?.outcome)??pl(e?.type)??e?.gatewayErrorCode}),r);return e?.orderId&&(s.orderId=e.orderId),s}function _i(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function Ba(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}function gl(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let o of n)if(typeof o=="string"&&o.length>0&&(!t?.requirePaymentIntentClientSecret||Ba(o)))return o;let r=e?.data;if(r&&typeof r=="object"){let o=r,i=[o.threeDSecureToken,o.clientSecret,o.stripeClientSecret,o.id];for(let l of i)if(typeof l=="string"&&l.length>0&&(!t?.requirePaymentIntentClientSecret||Ba(l)))return l;let s=o.gateways;if(s&&typeof s=="object"){let l=s.stripe;if(l&&typeof l=="object"){let p=l,f=[p.stripeClientSecret,p.clientSecret];for(let C of f)if(typeof C=="string"&&C.length>0&&(!t?.requirePaymentIntentClientSecret||Ba(C)))return C}}}}async function Sd({billingApiUrl:e,sessionId:t,nonce:n,responseJson:r}){let o=gl(r,{requirePaymentIntentClientSecret:!0});if(typeof o=="string"&&o.length>0)return{type:"3ds_required",threeDSecureToken:o};if(!t)return null;try{let l=(await new Ri(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(Ba(l))return{type:"3ds_required",threeDSecureToken:l}}catch{}return null}async function So({billingApiUrl:e,sessionId:t,session:n,nonce:r,tokenizedData:o,returnUrl:i,telemetry:s}){let l=e.replace(/\/+$/,""),p=t??n.id,f=r??n.clientSecret,C=n.customer?.id??n.accountData?.userId??"",h=n.customer?.email??n.accountData?.email??"",m=n.customer?.firstName??n.accountData?.firstName??"",w=n.customer?.lastName??n.accountData?.lastName??"",_=n.customer?.country??n.accountData?.country??void 0,ae=n.customer?.zip??n.accountData?.zip??void 0,Pe=await new Ri(l,s===!1?{telemetry:!1}:void 0).processPayment(C,{sessionId:p,nonce:f,paymentMethodCategory:"saved",tokenizedData:o,accountData:{userId:C,email:h,firstName:m,lastName:w,country:_,zip:ae},returnUrl:i??_i(n)});if(Pe.ok){let X=typeof Pe.json=="function"?await Pe.json().catch(()=>null):null;if(fd(n)||X?.status==="authorized")return{type:"success",result:{status:"authorized",paymentId:typeof X?.paymentId=="string"?X.paymentId:n.paymentId,sessionId:typeof X?.sessionId=="string"?X.sessionId:p,authorizationExpiresAt:typeof X?.authorizationExpiresAt=="string"?X.authorizationExpiresAt:n.authorizationExpiresAt,paymentMethodId:Ko(o),checkoutMethod:ml(o,n)}};let ce=o?.threeDSecureActionResultTokenId;return{type:"success",result:{status:"succeeded",...ce?{paymentIntentId:ce}:{},paymentMethodId:Ko(o),checkoutMethod:ml(o,n)}}}let S;try{S=await Pe.json()}catch(X){throw new Pt("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:Pe.status,cause:X})}if(S?.type==="3ds_required"&&typeof S.nextActionRedirectUrl=="string")return{type:"next_action_required",nextActionRedirectUrl:S.nextActionRedirectUrl};if(S?.type==="paypal_redirect_required"||S?.type==="3ds_required"){let X=gl(S);if(!X)throw new Pt("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:Pe.status});return{type:S.type,threeDSecureToken:X,paymentMethodId:S.paymentMethodId}}if(S?.gatewayErrorCode==="authentication_required"){let X=await Sd({billingApiUrl:l,sessionId:p,nonce:f,responseJson:S});if(X)return X;throw Ei(new Pt("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}let G=new Pt(S?.message??"Payment failed. Please try again.","api_error",{code:S?.code??S?.gatewayErrorCode,declineCode:S?.declineCode??S?.gatewayDeclineReason,statusCode:Pe.status});throw Object.assign(G,{telemetryOutcome:yd(Pe.status,S)})}async function Fa(e,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:i,session:s,returnUrl:l,telemetry:p,signal:f}){let C=t?.getRawProvider();if(!C)throw _r(new Pt("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!r||!e.threeDSecureToken)throw Ei(new Pt("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let h=gd(e.threeDSecureToken),m=null,w=e.paymentMethodId,_=await Jo(()=>vd(C,e.threeDSecureToken,h),"card");if(_){if(_.error)throw _r(new Pt(_.error.message??`Failed to retrieve 3DS ${h?"setup":"payment"} status.`,"api_error",{code:_.error.code}),"card");let Y=_.intent;!w&&Y?.payment_method&&(typeof Y.payment_method=="string"?w=Y.payment_method:"id"in Y.payment_method&&(w=Y.payment_method.id??void 0))}let ae=w?await Jo(()=>Pd(C,e.threeDSecureToken,{payment_method:w,return_url:l??_i(s)??window.location.href},h),"card"):null;if(ae){if(ae.error)throw _r(new Pt(ae.error.message??"3DS authentication failed.","api_error",{code:ae.error.code}),"card");m=ae.intent}else{let Y=await Jo(()=>C.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(Y.error)throw _r(new Pt(Y.error.message??"3DS authentication failed.","api_error",{code:Y.error.code}),"card");m=(h?Y.setupIntent:Y.paymentIntent)??null}if(m&&(m.status==="requires_capture"||m.status==="succeeded"||m.status==="processing")){let Y=await So({billingApiUrl:o,sessionId:i,session:s,telemetry:p,tokenizedData:{id:m.id,type:"card",threeDSecureActionResultTokenId:m.id},returnUrl:l});return Y.type==="success"?{...Y.result,paymentIntentId:Y.result.paymentIntentId??m.id,paymentMethodId:Y.result.paymentMethodId??w}:Y.type==="next_action_required"?Co(Y,{billingApiUrl:o,sessionId:i??s.id,session:s,signal:f}):Fa(Y,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:i,session:s,returnUrl:l,telemetry:p,signal:f})}throw _r(new Pt("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let h=(n??t)?.getRawProvider();if(!h)throw _r(new Pt("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:w}=await Jo(()=>h.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(w)throw _r(new Pt(w.message??"PayPal authorization failed.","api_error",{code:w.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:m}=await Jo(()=>h.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:l??_i(s)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(m)throw _r(new Pt(m.message??"PayPal authorization failed.","api_error",{code:m.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new Pt("Unsupported payment redirect state.","api_error")}function Qo(e){if(e instanceof Pt){let r=xr(e.message);return r&&r!==e.message?Object.assign(new Pt(r,e.type,{code:e.code,declineCode:e.declineCode,param:e.param,statusCode:e.statusCode}),{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=xr(t)??t;return new Pt(n,"api_error")}function Ai(e){let t=e.data.stripe?.publishableKey,n=!!e.data.paypal?.publishableKey,r=!!e.data.session?.vault?.html||Ar(e.data.session);if(!t&&!n&&!r)throw new Pt("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 ml(e,t){return e?e.isPaypal?"paypal":"card":t&&Ar(t)?"card":void 0}async function xi({publishableKey:e,paypalPublishableKey:t,billingApiUrl:n,locale:r,telemetry:o}){if(!e)return{flopay:null,paypalFlopay:null};let i=t&&t!==e?t:void 0,[s,l]=await Promise.all([ul(e,{billingApiUrl:n,locale:r,telemetry:o}),i?ul(i,{billingApiUrl:n,locale:r,telemetry:o}).catch(f=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",f),null)):Promise.resolve(null)]);if(!s)throw new Pt("The payment provider did not initialize.","authentication_error");let p=null;return i?p=l:t&&(p=s),{flopay:s,paypalFlopay:p}}import{PaymentAPI as wo,PciVaultCardCapture as wd,toStripeAppearance as Id}from"@flopay/js";import{COUNTRY_OPTIONS as kd,classifyPaymentRejection as _d,FloPayError as dr,filterStripeMethodsByCountry as Rd,getPostalCodeExample as Ed,getPostalCodeLabel as qi,getStateFromPostalCode as vl,getStateLabel as Mi,getStateOptions as Td,getStripeMethodDisplayName as Jr,hasVendoredStripeMethodLogo as Ad,isAuthorizationOnlySession as Bi,isAVSFieldVisible as rt,isPostalCodeSupported as xd,isSetupIntentClientSecret as Fi,isValidEmail as cn,isValidPostalCode as Md,needsStripeMethodExplicitConfirm as Pl,normalizeCheckoutFailureOutcome as Bd,partitionStripeMethods as Fd,randomUuidV4 as Dd,resolveAVSConfig as Nd,resolveButtonsLayoutTheme as Ld,resolveStripeMethodBrandVariant as Od,resolveTheme as zd,stripeExpressMethodToOptionKey as bl}from"@flopay/shared";import{ExpressCheckoutElement as Bl,PaymentElement as Ud,Elements as Gr,useElements as Vi,useStripe as Hi}from"@stripe/react-stripe-js";import qd,{useCallback as Ze,useContext as Io,useEffect as gt,useMemo as Ft,useRef as me,useState as le}from"react";var hl={alipay:"https://cdn.flopay.com/sdk-logos/v1/alipay.svg",bancontact:"https://cdn.flopay.com/sdk-logos/v1/bancontact.svg",blik:"https://cdn.flopay.com/sdk-logos/v1/blik.svg",eps:"https://cdn.flopay.com/sdk-logos/v1/eps.svg",giropay:"https://cdn.flopay.com/sdk-logos/v1/giropay.svg",ideal:"https://cdn.flopay.com/sdk-logos/v1/ideal.svg",klarna:"https://cdn.flopay.com/sdk-logos/v1/klarna.svg",p24:"https://cdn.flopay.com/sdk-logos/v1/p24.svg",sepa_debit:"https://cdn.flopay.com/sdk-logos/v1/sepa_debit.svg",wechat_pay:"https://cdn.flopay.com/sdk-logos/v1/wechat_pay.svg"};import{Fragment as Yr,jsx as c,jsxs as ze}from"react/jsx-runtime";var hr="flopay_stripe_resume",Cl="flopay_wallet_resume",Fl="fw1",jd="fw2",Dl=300*1e3,$d=900,Kd=25e3,Vd=25e3,Hd=1e4,Di={},Ni={};function Wi(e){return`${jd}:${e}`}function Da(e){if(typeof window>"u")return!1;try{return localStorage.removeItem(Wi(e)),!0}catch{return!1}}function Na(e,t){if(typeof window>"u")return null;let n=Wi(e);try{let r=localStorage.getItem(n);if(!r)return null;let o=JSON.parse(r);return typeof o.createdAt!="number"||Date.now()-o.createdAt<0||Date.now()-o.createdAt>Dl||o.sessionId!==e||o.nonce!==t||typeof o.clientSecret!="string"||typeof o.providerObjectId!="string"||typeof o.paymentMethodType!="string"?(Da(e),null):o}catch{return Da(e),null}}function Wd(e){if(typeof window>"u")return!1;try{return localStorage.setItem(Wi(e.sessionId),JSON.stringify(e)),!0}catch{return!1}}function Sl(e,t,n){let r=Na(e,t);return!r||r.clientSecret!==n?!1:Da(e)}function Li(e,t,n){if(typeof window>"u")return;Na(e,t)?.clientSecret===n&&Da(e)}function Gd(e){return typeof e.payment_method=="string"?e.payment_method:typeof e.payment_method?.id=="string"?e.payment_method.id:null}function Oi(e,t,n){if(!e||typeof e.id!="string"||t&&e.id!==t)return{kind:"ambiguous"};if(e.status==="canceled"||e.status==="requires_payment_method")return{kind:"terminal"};let r=n?e.status==="succeeded":$o(e.status),o=Gd(e);return!r||!o?{kind:"ambiguous"}:{kind:"confirmed",intentId:e.id,paymentMethodId:o}}async function wl(e,t,n){let r=null;try{return await Promise.race([Js(e,t),new Promise(o=>{r=window.setTimeout(()=>{r!==null&&n?.delete(r),o(null)},Hd),n?.add(r)})])}finally{r!==null&&(window.clearTimeout(r),n?.delete(r))}}function Yd(e){return e==="provider_sdk"?"PROVIDER_RUNTIME_FAILED":"REQUEST_TIMEOUT"}function Nl(e){return e instanceof dr&&(e.type==="validation_error"||e.statusCode===400||e.statusCode===422)}async function Oa(e,t,...n){let r=n[2].provider;t?.({class:"lifecycle",name:"payment.intent.started",provider:r});try{return await new wo(e,{telemetry:!1}).createSessionIntent(...n)}catch(o){throw Nl(o)||t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"intent_create",provider:r}),o}}var ea="flopay_paypal_resume",Jd=250,Il="Just a moment \u2014 we are finalizing your order. Please press pay again.",Xd="We are still confirming your last payment with your bank. Please wait a moment before trying again.";function Gi(e,t,n){e?.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:"provider_runtime",stage:"provider_load",provider:t,paymentMethodCategory:n,requestCategory:"provider_sdk"})}async function za({billingApiUrl:e,sessionId:t,nonce:n,request:r}){if(!(!t||!n))try{await new wo(e,{telemetry:!1}).reportSessionIntentDecline(t,n,r)}catch{}}function Zd(e){return e instanceof dr&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function zi(e){return e?.html?{html:e.html,...e.messageToken?{messageToken:e.messageToken}:{},...e.expectedOrigin?{expectedOrigin:e.expectedOrigin}:{}}:null}function Ll({event:e,fallbackEmail:t,fallbackName:n}){let r=e.billingDetails,o=t?.trim(),i=Vr(n),s=i.firstName?i:Vr(r?.name);return Bn({email:cn(o)?o:r?.email?.trim(),firstName:s.firstName,lastName:s.lastName})}async function Qd({event:e,prepared:t,email:n,billingName:r,methodLabel:o,collect:i}){let s=Ll({event:e,fallbackEmail:t?.accountPatch?.email??n,fallbackName:[t?.accountPatch?.firstName,t?.accountPatch?.lastName].join(" ").trim()||r});return cn(s.email)?s:i(o,s)}var eu=`
|
|
3
|
+
${Rn.join(`
|
|
4
|
+
`)}`]}):null;return lt&&!pn?Ne?Xr("div",{children:Ze}):null:xi("div",{children:[Ze,_&&Xr(vo,{identity:_.identity,methodLabel:_.methodLabel,testId:"flopay-direct-paypal-identity-pane",onComplete:Jt,onCancel:()=>Jt(null)}),xi("div",{"aria-hidden":Ye||_?!0:void 0,style:Ye||_?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:Da},children:[!L&&!Ye&&Xr("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"}}),Xr("div",{ref:Ae,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,role:"group","aria-label":"PayPal payment method",style:{minHeight:Da,display:"flex",opacity:L?1:0},"aria-busy":pt||Re},Ee)]},Ee),Q&&Xr("button",{ref:Ge,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:Zt,style:md,children:"Try PayPal again"})]})}function Oa(e){return Xr(vl,{...e})}function bl(e){return Xr(vl,{...e})}import{jsx as Pl,jsxs as bd}from"react/jsx-runtime";function Co({children:e,margin:t,icon:n=!0,styleOverride:r}){return bd("div",{role:"alert","data-testid":"flopay-error",style:{margin:t,padding:"0.625rem 0.875rem",background:"#FEF2F2",border:"1px solid #FECACA",borderRadius:"8px",color:"#991B1B",fontSize:"0.85rem",fontWeight:600,...n?{display:"flex",alignItems:"center",gap:"0.5rem"}:{},...r??{}},children:[n&&Pl("svg",{"aria-hidden":"true",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:Pl("path",{d:"M12 9v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z",stroke:"#DC2626",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}),e]})}import{foldIntoProducts as Pd,resolveSessionCurrency as Cd}from"@flopay/shared";function wo(){return typeof window<"u"&&typeof window.sessionStorage<"u"}var Bi=":idempotency-key";function Fi(e,t){if(!wo())return null;let n=window.sessionStorage.getItem(e);if(!n)return null;try{let r=JSON.parse(n);return!r||typeof r.sid!="string"||!r.sid||"canonicalIdentity"in r&&r.canonicalIdentity!==t?null:{..."canonicalIdentity"in r?{canonicalIdentity:t}:{},sid:r.sid,nonce:typeof r.nonce=="string"?r.nonce:void 0}}catch{return{sid:n}}}function Di(e,t){if(!wo())return null;try{let n=window.sessionStorage.getItem(e+Bi);if(!n)return null;try{let r=JSON.parse(n);return typeof r=="string"?r?{idempotencyKey:r}:null:!r||typeof r.idempotencyKey!="string"||!r.idempotencyKey||"canonicalIdentity"in r&&r.canonicalIdentity!==t?null:{..."canonicalIdentity"in r?{canonicalIdentity:t}:{},idempotencyKey:r.idempotencyKey}}catch{return{idempotencyKey:n}}}catch{return null}}function Na(e,t){if(wo())try{Fi(e,t)&&window.sessionStorage.removeItem(e)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout session cache.",n)}}function La(e,t){if(Na(e,t),!!wo())try{Di(e,t)&&window.sessionStorage.removeItem(e+Bi)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout idempotency key.",n)}}function za(e,t,n,r){if(wo())try{window.sessionStorage.setItem(e,JSON.stringify(r?{canonicalIdentity:t,sid:n,nonce:r}:{canonicalIdentity:t,sid:n}))}catch(o){console.warn("[FloPayCheckout] Failed to persist checkout session cache.",o)}}function Ua(e,t,n){if(wo())try{window.sessionStorage.setItem(e+Bi,JSON.stringify({canonicalIdentity:t,idempotencyKey:n}))}catch(r){console.warn("[FloPayCheckout] Failed to persist checkout idempotency key.",r)}}function Mi(e,t){return`${e}:${t.totalAmount??""}:${t.overrideAmount??""}:${t.quantity??1}:${t.currency??""}`}function wd(e){if(e==null)return e;let t=JSON.stringify(Object.entries(e).sort(([s],[l])=>s<l?-1:s>l?1:0)),n=1779033703,r=3144134277,o=1013904242,i=2773480762;for(let s=0;s<t.length;s++){let l=t.charCodeAt(s);n=r^Math.imul(n^l,597399067),r=o^Math.imul(r^l,2869860233),o=i^Math.imul(o^l,951274213),i=n^Math.imul(i^l,2716044179)}return n=Math.imul(o^n>>>18,597399067),r=Math.imul(i^r>>>22,2869860233),o=Math.imul(n^o>>>17,951274213),i=Math.imul(r^i>>>19,2716044179),n^=r^o^i,r^=n,o^=n,i^=n,[n,r,o,i].map(s=>(s>>>0).toString(16).padStart(8,"0")).join("")}function So(e,t=!1){let n=e?.account?.email?.trim().toLowerCase()??"",r={c:e?.clientId,cur:e?.currency??"",captureMethod:e?.captureMethod??"",a:{e:n,u:n?"":e?.account?.userId??"",country:e?.account?.country??""},successUrl:e?.successUrl,cancelUrl:e?.cancelUrl,p:e?.products?.map(o=>Mi(`${o.type??""}:${o.code??o.providerItemId??o.providerPlanId??""}`,o)).sort(),i:e?.items?.map(o=>Mi(o.code??o.providerItemId??"",o)).sort(),s:e?.subscriptions?.map(o=>Mi(o.code??o.providerPlanId??"",o)).sort(),couponCodes:e?.couponCodes?[...e.couponCodes].sort():void 0,checkoutMetadata:wd(e?.checkoutMetadata),...t?{tagsData:e?.tagsData,utmMetadata:e?.utmMetadata,tokenizedData:e?.tokenizedData,checkoutMode:e?.checkoutMode??"full"}:{}};return JSON.stringify(r)}function Cl(e,t=!1){let n=So(e,t),r=0;for(let o=0;o<n.length;o++)r=(r<<5)-r+n.charCodeAt(o)|0;return`flopay_session_${Math.abs(r).toString(36)}`}function wl(e,t){if(!e?.customer||!e.products||t.checkoutMetadata!==void 0)return!1;let n=t.account.email?.trim().toLowerCase()??"",r=e.customer.email?.trim().toLowerCase()??"";if((n?r!==n:e.customer.id!==t.account.userId)||(t.account.country??"").trim().toUpperCase()!==(e.customer.country??"").trim().toUpperCase()||e.successUrl!==t.successUrl||e.cancelUrl!==t.cancelUrl||(e.captureMethod??"automatic")!==(t.captureMethod??"automatic"))return!1;let o=Cd(t.currency,t.items,t.subscriptions,t.products);if(!o||e.currency.toUpperCase()!==o.toUpperCase())return!1;let i=(t.products??Pd(t.items,t.subscriptions)).map(f=>({type:f.type,code:f.code??f.providerItemId??f.providerPlanId??"",quantity:f.quantity??1,totalAmount:f.totalAmount,overrideAmount:f.overrideAmount??null,currency:(f.currency??o).toUpperCase()})).sort((f,b)=>`${f.code}:${f.type??""}`.localeCompare(`${b.code}:${b.type??""}`)),s=e.products.map(f=>({type:f.type,code:f.code??"",quantity:f.quantity??1,totalAmount:f.totalAmount,overrideAmount:f.overrideAmount??null,currency:(f.currency??e.currency).toUpperCase()})).sort((f,b)=>`${f.code}:${f.type??""}`.localeCompare(`${b.code}:${b.type??""}`));if(i.length!==s.length)return!1;for(let[f,b]of i.entries()){let g=s[f];if(g===void 0||b.code!==g.code||b.type!==void 0&&b.type!==g.type||b.quantity!==g.quantity||b.totalAmount!==g.totalAmount||b.overrideAmount!==g.overrideAmount||b.currency!==g.currency)return!1}let l=[...t.couponCodes??[]].sort(),y=[...e.coupons??[]].sort();return l.length===y.length&&l.every((f,b)=>f===y[b])}import{resolveBillingApiUrl as Sd}from"@flopay/shared";import{useEffect as zr,useMemo as kd,useRef as Sl,useState as kl}from"react";import{jsx as Id}from"react/jsx-runtime";function qa({flopay:e,paypalFlopay:t,options:n,onInstrument:r,children:o}){let[i,s]=kl(e instanceof Promise?null:e),[l,y]=kl(t instanceof Promise||!t?null:t),f=Sl(null),b=Sl(null),g=Po(r);zr(()=>{g({class:"lifecycle",name:"checkout.mount"})},[g]),zr(()=>{i&&g({class:"lifecycle",name:"sdk.initialize.ready"})},[g,i]),zr(()=>{if(i)return mn(i)?.subscribe?.(g)},[g,i]),zr(()=>{if(!(!l||l===i))return mn(l)?.subscribe?.(g)},[g,i,l]),zr(()=>{if(!i)return;let C=mn(i);return f.current=C?.beginCheckout()??C?.now()??0,C?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{C?.log({name:"checkout.unmount",stage:"unmount"})}},[i]),zr(()=>{let C=!1;return e instanceof Promise?e.then(v=>{C||s(v)},()=>{C||g({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"})}):s(e),()=>{C=!0}},[g,e]),zr(()=>{let C=!1;if(!t){y(null);return}return t instanceof Promise?t.then(v=>{C||y(v)},()=>{C||g({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED",provider:"paypal"})}):y(t),()=>{C=!0}},[g,t]),zr(()=>{if(!i||b.current===i)return;b.current=i;let C=mn(i);C?.log({name:"checkout.rendered",stage:"checkout_render"}),g({class:"lifecycle",name:"checkout.rendered"}),C?.performance({stage:"checkout_render",durationMs:C.elapsed(f.current??0),durationMode:"machine"})},[g,i]);let M=Sd(n?.billingApiUrl),R=kd(()=>({flopay:i,paypalFlopay:l,billingApiUrl:M,emitInstrument:g}),[i,l,M,g]);return Id(or.Provider,{value:R,children:o})}var ja="flopay_recent_completion_";function ko(e){if(!(!e||typeof window>"u"))try{let t={expiresAt:Date.now()+6e4};window.sessionStorage.setItem(ja+e,JSON.stringify(t))}catch{}}function Oi(e){if(!e||typeof window>"u")return!1;try{let t=window.sessionStorage.getItem(ja+e);if(!t)return!1;let n=JSON.parse(t);return typeof n?.expiresAt!="number"||n.expiresAt<=Date.now()?(window.sessionStorage.removeItem(ja+e),!1):!0}catch{return!1}}async function $a(e,t){e.current?.abort();let n=new AbortController;e.current=n;try{return await t(n.signal)}finally{e.current===n&&(e.current=null)}}import{loadFloPay as Il,PaymentAPI as Li}from"@flopay/js";import{classifyPaymentRejection as _d,FloPayError as Rt,isAuthorizationOnlySession as Rd,isSetupIntentClientSecret as Ed,normalizeCheckoutFailureOutcome as _l}from"@flopay/shared";var ia="card",Td=1e3,El=3e5;async function Ad(e,t,n){if(n){if(typeof e.retrieveSetupIntent!="function")return null;let{setupIntent:i,error:s}=await e.retrieveSetupIntent(t);return{error:s,intent:i??null}}if(typeof e.retrievePaymentIntent!="function")return null;let{paymentIntent:r,error:o}=await e.retrievePaymentIntent(t);return{error:o,intent:r??null}}async function xd(e,t,n,r){if(r){if(typeof e.confirmCardSetup!="function")return null;let{setupIntent:s,error:l}=await e.confirmCardSetup(t,n);return{error:l,intent:s??null}}if(typeof e.confirmCardPayment!="function")return null;let{paymentIntent:o,error:i}=await e.confirmCardPayment(t,n);return{error:i,intent:o??null}}function sa(e){return new Rt("Card authentication was cancelled.","api_error",{code:"three_ds_aborted",cause:e})}function zi(e,t){return Object.assign(e,{checkoutMethod:t})}function Ar(e,t){let n=e instanceof Rt?e:new Rt(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 aa(e,t){try{return await e()}catch(n){throw Ar(n,t)}}function Tl(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 Md(e){return e.status==="succeeded"||e.status==="authorized"||e.status==="declined"}async function Ui(e){if(typeof document>"u"||typeof window>"u")throw new Rt("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});if(e.signal?.aborted)throw new Rt("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"});let t=1e3,n=15e3,r=`${e.billingApiUrl.replace(/\/$/,"")}/v1/checkouts/sessions/${encodeURIComponent(e.sessionId)}/3ds/complete`,o=async()=>{let g=new AbortController,M=()=>g.abort();e.signal?.aborted?g.abort():e.signal?.addEventListener("abort",M);let R=window.setTimeout(()=>g.abort(),n);try{let C=await fetch(r,{method:"POST",headers:{"x-checkout-session-token":e.nonce,"content-type":"application/json"},body:"{}",signal:g.signal});if(!C.ok)return{status:"unknown"};let v=await C.json().catch(()=>null);return Bd(v)}catch{return{status:"unknown"}}finally{window.clearTimeout(R),e.signal?.removeEventListener("abort",M)}},i,s=()=>e.pollCompletionEndpoint!==!1?o():(i??(i=o()),i),l=document.activeElement instanceof HTMLElement?document.activeElement:null,y=document.createElement("div");y.setAttribute("data-flopay-auto-3ds-overlay","1"),y.setAttribute("role","dialog"),y.setAttribute("aria-modal","true"),y.setAttribute("aria-label","Card authentication"),y.style.cssText=["position:fixed","inset:0","z-index:2147483647","background:rgba(15,23,42,0.6)","display:flex","align-items:center","justify-content:center","padding:16px"].join(";");let f=document.createElement("iframe");f.setAttribute("title","Card authentication"),f.setAttribute("allow","payment"),f.tabIndex=0,f.style.cssText=["width:min(100%,460px)","height:min(100%,640px)","border:0","border-radius:12px","background:#fff","box-shadow:0 12px 30px rgba(0,0,0,0.35)"].join(";");let b=null;try{b=new URL(e.billingApiUrl,window.location.href).origin}catch{b=null}try{let g=await new Promise((M,R)=>{let C=!1,v=0,q=0,Re=0,I=!1,G=()=>{window.clearTimeout(v),window.clearInterval(q),window.clearTimeout(Re),window.removeEventListener("message",Le),f.removeEventListener("load",re),e.signal?.removeEventListener("abort",ve)},Y=async()=>{if(!(C||I)){I=!0;try{let Ce=await s();if(C||!Md(Ce))return;C=!0,G(),M(Ce)}finally{I=!1}}},re=()=>{e.pollCompletionEndpoint!==!1&&(window.clearTimeout(Re),Re=window.setTimeout(()=>{Y()},250))},ve=()=>{C||(C=!0,G(),R(new Rt("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"})))},Le=Ce=>{if(Ce.source!==f.contentWindow||b&&Ce.origin!==b)return;let $e=Ce.data;!$e||typeof $e!="object"||$e.source!=="flopay-vault-3ds-return"||C||(C=!0,G(),M(null))};v=window.setTimeout(()=>{C||(C=!0,G(),R(new Rt("Card authentication timed out.","api_error",{code:"three_ds_timeout"})))},El),e.pollCompletionEndpoint!==!1&&(q=window.setInterval(()=>{Y()},t)),f.addEventListener("load",re),window.addEventListener("message",Le),e.signal?.addEventListener("abort",ve),f.src=e.nextActionRedirectUrl,y.appendChild(f),document.body.appendChild(y),f.focus(),e.signal?.aborted&&ve()});return g||await s()}finally{y.parentNode?.removeChild(y),l?.isConnected&&l.focus()}}async function Io(e,t){let n=t.nonce??t.session.clientSecret,r=new Li(t.billingApiUrl,{telemetry:!1}),o=new AbortController,i=new AbortController,s=()=>{o.abort(t.signal.reason),i.abort(t.signal.reason)};t.signal.aborted?s():t.signal.addEventListener("abort",s,{once:!0});let l=Ui({billingApiUrl:t.billingApiUrl,sessionId:t.sessionId,nonce:n,nextActionRedirectUrl:e.nextActionRedirectUrl,signal:o.signal,pollCompletionEndpoint:!1}),y=null,f=()=>(y??(y=r.waitForCheckoutSessionCompletion(t.sessionId,{initialDelayMs:Td,nonce:n,statusUrl:`${t.billingApiUrl.replace(/\/+$/,"")}/v1/checkouts/sessions/${encodeURIComponent(t.sessionId)}/status`,continueAfterActionRequired:!0,timeoutMs:El,signal:i.signal})),y),b=f(),g;try{let R=await Promise.race([l.then(C=>({kind:"challenge",outcome:C})),b.then(C=>({kind:"status",session:C}))]);if(R.kind==="status")o.abort(),g=R.session;else{if(R.outcome.status==="declined")throw Ir({type:R.outcome.declineReason??"authorization_declined",message:"Card was declined.",gatewayErrorCode:R.outcome.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:"card"});g=await f()}}catch(R){throw t.signal.aborted||R instanceof Error&&R.name==="AbortError"?sa(R):R}finally{t.signal.removeEventListener("abort",s),o.abort(),i.abort()}let M=g.data.session;if(!Fr(M))throw go(M);return{...Tr(M,t.sessionId),checkoutMethod:"card"}}function Bd(e){if(!e||typeof e!="object")return{status:"unknown"};let t=typeof e.status=="string"?e.status:"unknown",n=typeof e.providerIntentId=="string"?e.providerIntentId:null;switch(t){case"succeeded":return{status:"succeeded",providerIntentId:n};case"authorized":return{status:"authorized",providerIntentId:n};case"declined":return{status:"declined",providerIntentId:n,declineReason:typeof e.declineReason=="string"?e.declineReason:null,gatewayDeclineReason:typeof e.gatewayDeclineReason=="string"?e.gatewayDeclineReason:null};case"requires_action":return{status:"requires_action",providerIntentId:n,nextActionRedirectUrl:typeof e.nextActionRedirectUrl=="string"?e.nextActionRedirectUrl:null};case"pending":return{status:"pending",providerIntentId:n};case"timeout":return{status:"timeout",providerIntentId:n};case"no_attempt":return{status:"no_attempt"};default:return{status:"unknown"}}}function Ir(e,t="Payment failed. Please try again.",n){let r=n?.checkoutMethod??e?.checkoutMethod??(e?.type==="paypal_redirect_required"?"paypal":"card"),o=e?.message??t,i=Br(o)??o,s=zi(new Rt(i,"api_error",{code:e?.code??_l(e?.outcome)??_l(e?.type)??e?.gatewayErrorCode}),r);return e?.orderId&&(s.orderId=e.orderId),s}function Ni(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function Ka(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}function Al(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let o of n)if(typeof o=="string"&&o.length>0&&(!t?.requirePaymentIntentClientSecret||Ka(o)))return o;let r=e?.data;if(r&&typeof r=="object"){let o=r,i=[o.threeDSecureToken,o.clientSecret,o.stripeClientSecret,o.id];for(let l of i)if(typeof l=="string"&&l.length>0&&(!t?.requirePaymentIntentClientSecret||Ka(l)))return l;let s=o.gateways;if(s&&typeof s=="object"){let l=s.stripe;if(l&&typeof l=="object"){let y=l,f=[y.stripeClientSecret,y.clientSecret];for(let b of f)if(typeof b=="string"&&b.length>0&&(!t?.requirePaymentIntentClientSecret||Ka(b)))return b}}}}async function Fd({billingApiUrl:e,sessionId:t,nonce:n,responseJson:r}){let o=Al(r,{requirePaymentIntentClientSecret:!0});if(typeof o=="string"&&o.length>0)return{type:"3ds_required",threeDSecureToken:o};if(!t)return null;try{let l=(await new Li(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(Ka(l))return{type:"3ds_required",threeDSecureToken:l}}catch{}return null}async function _o({billingApiUrl:e,sessionId:t,session:n,nonce:r,tokenizedData:o,returnUrl:i,telemetry:s}){let l=e.replace(/\/+$/,""),y=t??n.id,f=r??n.clientSecret,b=n.customer?.id??n.accountData?.userId??"",g=n.customer?.email??n.accountData?.email??"",M=n.customer?.firstName??n.accountData?.firstName??"",R=n.customer?.lastName??n.accountData?.lastName??"",C=n.customer?.country??n.accountData?.country??void 0,v=n.customer?.zip??n.accountData?.zip??void 0,Re=await new Li(l,s===!1?{telemetry:!1}:void 0).processPayment(b,{sessionId:y,nonce:f,paymentMethodCategory:"saved",tokenizedData:o,accountData:{userId:b,email:g,firstName:M,lastName:R,country:C,zip:v},returnUrl:i??Ni(n)});if(Re.ok){let Y=typeof Re.json=="function"?await Re.json().catch(()=>null):null;if(Rd(n)||Y?.status==="authorized")return{type:"success",result:{status:"authorized",paymentId:typeof Y?.paymentId=="string"?Y.paymentId:n.paymentId,sessionId:typeof Y?.sessionId=="string"?Y.sessionId:y,authorizationExpiresAt:typeof Y?.authorizationExpiresAt=="string"?Y.authorizationExpiresAt:n.authorizationExpiresAt,paymentMethodId:Jo(o),checkoutMethod:Rl(o,n)}};let re=o?.threeDSecureActionResultTokenId;return{type:"success",result:{status:"succeeded",...re?{paymentIntentId:re}:{},paymentMethodId:Jo(o),checkoutMethod:Rl(o,n)}}}let I;try{I=await Re.json()}catch(Y){throw new Rt("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:Re.status,cause:Y})}if(I?.type==="3ds_required"&&typeof I.nextActionRedirectUrl=="string")return{type:"next_action_required",nextActionRedirectUrl:I.nextActionRedirectUrl};if(I?.type==="paypal_redirect_required"||I?.type==="3ds_required"){let Y=Al(I);if(!Y)throw new Rt("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:Re.status});return{type:I.type,threeDSecureToken:Y,paymentMethodId:I.paymentMethodId}}if(I?.gatewayErrorCode==="authentication_required"){let Y=await Fd({billingApiUrl:l,sessionId:y,nonce:f,responseJson:I});if(Y)return Y;throw zi(new Rt("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}let G=new Rt(I?.message??"Payment failed. Please try again.","api_error",{code:I?.code??I?.gatewayErrorCode,declineCode:I?.declineCode??I?.gatewayDeclineReason,statusCode:Re.status});throw Object.assign(G,{telemetryOutcome:_d(Re.status,I)})}async function Va(e,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:i,session:s,returnUrl:l,telemetry:y,signal:f}){let b=t?.getRawProvider();if(!b)throw Ar(new Rt("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!r||!e.threeDSecureToken)throw zi(new Rt("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let g=Ed(e.threeDSecureToken),M=null,R=e.paymentMethodId,C=await aa(()=>Ad(b,e.threeDSecureToken,g),"card");if(C){if(C.error)throw Ar(new Rt(C.error.message??`Failed to retrieve 3DS ${g?"setup":"payment"} status.`,"api_error",{code:C.error.code}),"card");let q=C.intent;!R&&q?.payment_method&&(typeof q.payment_method=="string"?R=q.payment_method:"id"in q.payment_method&&(R=q.payment_method.id??void 0))}let v=R?await aa(()=>xd(b,e.threeDSecureToken,{payment_method:R,return_url:l??Ni(s)??window.location.href},g),"card"):null;if(v){if(v.error)throw Ar(new Rt(v.error.message??"3DS authentication failed.","api_error",{code:v.error.code}),"card");M=v.intent}else{let q=await aa(()=>b.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(q.error)throw Ar(new Rt(q.error.message??"3DS authentication failed.","api_error",{code:q.error.code}),"card");M=(g?q.setupIntent:q.paymentIntent)??null}if(M&&(M.status==="requires_capture"||M.status==="succeeded"||M.status==="processing")){let q=await _o({billingApiUrl:o,sessionId:i,session:s,telemetry:y,tokenizedData:{id:M.id,type:"card",threeDSecureActionResultTokenId:M.id},returnUrl:l});return q.type==="success"?{...q.result,paymentIntentId:q.result.paymentIntentId??M.id,paymentMethodId:q.result.paymentMethodId??R}:q.type==="next_action_required"?Io(q,{billingApiUrl:o,sessionId:i??s.id,session:s,signal:f}):Va(q,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:i,session:s,returnUrl:l,telemetry:y,signal:f})}throw Ar(new Rt("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let g=(n??t)?.getRawProvider();if(!g)throw Ar(new Rt("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:R}=await aa(()=>g.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(R)throw Ar(new Rt(R.message??"PayPal authorization failed.","api_error",{code:R.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:M}=await aa(()=>g.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:l??Ni(s)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(M)throw Ar(new Rt(M.message??"PayPal authorization failed.","api_error",{code:M.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new Rt("Unsupported payment redirect state.","api_error")}function la(e){if(e instanceof Rt){let r=Br(e.message);return r&&r!==e.message?Object.assign(new Rt(r,e.type,{code:e.code,declineCode:e.declineCode,param:e.param,statusCode:e.statusCode}),{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=Br(t)??t;return new Rt(n,"api_error")}function qi(e){let t=e.data.stripe?.publishableKey,n=!!e.data.paypal?.publishableKey,r=!!e.data.session?.vault?.html||Mr(e.data.session);if(!t&&!n&&!r)throw new Rt("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 Rl(e,t){return e?e.isPaypal?"paypal":"card":t&&Mr(t)?"card":void 0}async function ji({publishableKey:e,paypalPublishableKey:t,billingApiUrl:n,locale:r,telemetry:o}){if(!e)return{flopay:null,paypalFlopay:null};let i=t&&t!==e?t:void 0,[s,l]=await Promise.all([Il(e,{billingApiUrl:n,locale:r,telemetry:o}),i?Il(i,{billingApiUrl:n,locale:r,telemetry:o}).catch(f=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",f),null)):Promise.resolve(null)]);if(!s)throw new Rt("The payment provider did not initialize.","authentication_error");let y=null;return i?y=l:t&&(y=s),{flopay:s,paypalFlopay:y}}import{PaymentAPI as Eo,PciVaultCardCapture as Dd,toStripeAppearance as Od}from"@flopay/js";import{COUNTRY_OPTIONS as Nd,classifyPaymentRejection as Ld,FloPayError as pr,filterStripeMethodsByCountry as zd,getPostalCodeExample as Ud,getPostalCodeLabel as Zi,getStateFromPostalCode as Ml,getStateLabel as Ki,getStateOptions as qd,getStripeMethodDisplayName as eo,hasVendoredStripeMethodLogo as jd,isAuthorizationOnlySession as Vi,isAVSFieldVisible as at,isPostalCodeSupported as $d,isSetupIntentClientSecret as Hi,isValidEmail as fn,isValidPostalCode as Kd,needsStripeMethodExplicitConfirm as Bl,normalizeCheckoutFailureOutcome as Vd,partitionStripeMethods as Hd,randomUuidV4 as Wd,resolveAVSConfig as Gd,resolveButtonsLayoutTheme as Yd,resolveStripeMethodBrandVariant as Jd,resolveTheme as Xd,stripeExpressMethodToOptionKey as Fl}from"@flopay/shared";import{ExpressCheckoutElement as Wl,PaymentElement as Zd,Elements as Zr,useElements as ns,useStripe as rs}from"@stripe/react-stripe-js";import Qd,{useCallback as tt,useContext as To,useEffect as Ct,useMemo as Et,useRef as de,useState as ce}from"react";function Ro(e,t){return{...t,inAppBrowser:e.browser.inAppBrowser,appFamily:e.browser.appFamily,popupCapability:e.capability.current(),presentationMode:e.presentationMode}}function $i(e,t){if(e)return{error:n=>e.error(Ro(t,n)),log:n=>e.log(Ro(t,n)),performance:n=>e.performance(Ro(t,n)),terminal:n=>e.terminal(Ro(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()}}var xl={alipay:"https://cdn.flopay.com/sdk-logos/v1/alipay.svg",bancontact:"https://cdn.flopay.com/sdk-logos/v1/bancontact.svg",blik:"https://cdn.flopay.com/sdk-logos/v1/blik.svg",eps:"https://cdn.flopay.com/sdk-logos/v1/eps.svg",giropay:"https://cdn.flopay.com/sdk-logos/v1/giropay.svg",ideal:"https://cdn.flopay.com/sdk-logos/v1/ideal.svg",klarna:"https://cdn.flopay.com/sdk-logos/v1/klarna.svg",p24:"https://cdn.flopay.com/sdk-logos/v1/p24.svg",sepa_debit:"https://cdn.flopay.com/sdk-logos/v1/sepa_debit.svg",wechat_pay:"https://cdn.flopay.com/sdk-logos/v1/wechat_pay.svg"};import{Fragment as Qr,jsx as d,jsxs as Oe}from"react/jsx-runtime";var _r="flopay_stripe_resume",Dl="flopay_wallet_resume",Gl="fw1",eu="fw2",Yl=300*1e3,tu=900,nu=25e3,ru=25e3,ou=1e4,Ha={},Wi={};function os(e){return`${eu}:${e}`}function Wa(e){if(typeof window>"u")return!1;try{return localStorage.removeItem(os(e)),!0}catch{return!1}}function Ga(e,t){if(typeof window>"u")return null;let n=os(e);try{let r=localStorage.getItem(n);if(!r)return null;let o=JSON.parse(r);return typeof o.createdAt!="number"||Date.now()-o.createdAt<0||Date.now()-o.createdAt>Yl||o.sessionId!==e||o.nonce!==t||typeof o.clientSecret!="string"||typeof o.providerObjectId!="string"||typeof o.paymentMethodType!="string"?(Wa(e),null):o}catch{return Wa(e),null}}function au(e){if(typeof window>"u")return!1;try{return localStorage.setItem(os(e.sessionId),JSON.stringify(e)),!0}catch{return!1}}function Ol(e,t,n){let r=Ga(e,t);return!r||r.clientSecret!==n?!1:Wa(e)}function Gi(e,t,n){if(typeof window>"u")return;Ga(e,t)?.clientSecret===n&&Wa(e)}function iu(e){return typeof e.payment_method=="string"?e.payment_method:typeof e.payment_method?.id=="string"?e.payment_method.id:null}function Yi(e,t,n){if(!e||typeof e.id!="string"||t&&e.id!==t)return{kind:"ambiguous"};if(e.status==="canceled"||e.status==="requires_payment_method")return{kind:"terminal"};let r=n?e.status==="succeeded":Yo(e.status),o=iu(e);return!r||!o?{kind:"ambiguous"}:{kind:"confirmed",intentId:e.id,paymentMethodId:o}}async function Nl(e,t,n){let r=null;try{return await Promise.race([sl(e,t),new Promise(o=>{r=window.setTimeout(()=>{r!==null&&n?.delete(r),o(null)},ou),n?.add(r)})])}finally{r!==null&&(window.clearTimeout(r),n?.delete(r))}}function su(e){return e==="provider_sdk"?"PROVIDER_RUNTIME_FAILED":"REQUEST_TIMEOUT"}function Jl(e){return e instanceof pr&&(e.type==="validation_error"||e.statusCode===400||e.statusCode===422)}async function Ja(e,t,...n){let r=n[2].provider;t?.({class:"lifecycle",name:"payment.intent.started",provider:r});try{return await new Eo(e,{telemetry:!1}).createSessionIntent(...n)}catch(o){throw Jl(o)||t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"intent_create",provider:r}),o}}var ca="flopay_paypal_resume",lu=250,Ll="Just a moment \u2014 we are finalizing your order. Please press pay again.",cu="We are still confirming your last payment with your bank. Please wait a moment before trying again.";function as(e,t,n,r){e?.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:"provider_runtime",stage:"provider_load",provider:t,paymentMethodCategory:n,requestCategory:"provider_sdk",...r?{terminalReason:r}:{}})}async function Xa({billingApiUrl:e,sessionId:t,nonce:n,request:r}){if(!(!t||!n))try{await new Eo(e,{telemetry:!1}).reportSessionIntentDecline(t,n,r)}catch{}}function du(e){return e instanceof pr&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function Ji(e){return e?.html?{html:e.html,...e.messageToken?{messageToken:e.messageToken}:{},...e.expectedOrigin?{expectedOrigin:e.expectedOrigin}:{}}:null}function Xl({event:e,fallbackEmail:t,fallbackName:n}){let r=e.billingDetails,o=t?.trim(),i=Yr(n),s=i.firstName?i:Yr(r?.name);return On({email:fn(o)?o:r?.email?.trim(),firstName:s.firstName,lastName:s.lastName})}async function uu({event:e,prepared:t,email:n,billingName:r,methodLabel:o,collect:i}){let s=Xl({event:e,fallbackEmail:t?.accountPatch?.email??n,fallbackName:[t?.accountPatch?.firstName,t?.accountPatch?.lastName].join(" ").trim()||r});return fn(s.email)?s:i(o,s)}var pu=`
|
|
5
5
|
.paypal-buttons { margin: 0 !important; vertical-align: top !important; }
|
|
6
6
|
@keyframes flopay-spin { to { transform: rotate(360deg); } }
|
|
7
7
|
@keyframes flopay-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }
|
|
@@ -22,7 +22,7 @@ ${pt.join(`
|
|
|
22
22
|
0% { opacity: 1; transform: translateX(0) scale(1); }
|
|
23
23
|
100% { opacity: 0; transform: translateX(16px) scale(0.97); }
|
|
24
24
|
}
|
|
25
|
-
`,La=44,ta=180,kl=`flopay-card-enter ${ta}ms cubic-bezier(0, 0, 0.2, 1) both`,_l=`flopay-card-exit ${ta}ms cubic-bezier(0.4, 0, 0.2, 1) both`,tu=`flopay-buttons-enter ${ta}ms cubic-bezier(0, 0, 0.2, 1) both`,nu=`flopay-buttons-exit ${ta}ms cubic-bezier(0.4, 0, 0.2, 1) both`;function ru(e){return e.gateway==="stripe"?"stripe":e.gateway==="paypal"||e.isPaypal?"paypal":void 0}function Yi(e){if(!e.themeBundle&&!e.explicitPrimaryColor)return{backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:e.resolvedBorderRadius,boxShadow:"0 1px 2px rgba(0,0,0,0.04)"};let t=e.themeBundle?e.submitButtonStyle??{}:{};return{backgroundColor:e.resolvedPrimaryColor,color:t.color??"white",border:t.border??"none",borderRadius:t.borderRadius??e.resolvedBorderRadius,boxShadow:t.boxShadow}}var ou={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"};function au(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 ji={width:"100%",minHeight:La,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 iu(e){switch(e){case"paypal":return"PayPal";case"apple_pay":return"Apple Pay";case"google_pay":return"Google Pay";default:return"Card"}}function Rl(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function $i(e){return e==="paypal"?"PayPal":Jr(e)}function su(e,t){let n=`We couldn't open ${$i(e)}. Try again or choose another payment method.`;return t?`${n} Allow pop-ups for this site, then try again.`:n}function lu(e){let t=Ed(e);return`Enter a valid ${qi(e)}${t?` (e.g. ${t})`:""}`}function cu(e,t,n){let r=xd(e),o=t.trim(),i=n&&r,s=i&&!o,l=i&&!!o&&!Md(e,o);return{visible:n,supported:r,required:i,empty:s,malformed:l}}function du(e,t){let n=e.trim(),r=t&&!n,o=t&&!!n&&!cn(n);return{required:t,empty:r,malformed:o,value:n}}function El(e,t){return t instanceof dr?t:new dr(t instanceof Error?t.message:`${iu(e)} before-click hook failed.`,"validation_error")}function Ui(){return c("style",{children:eu})}function uu(e){return typeof e=="number"?`${e}px`:e}function Ol(e,t){let n=e.availablePaymentMethods;return n&&t.some(r=>n[r])?"ready":"unavailable"}function zl({state:e,placeholderTestId:t,borderRadius:n=8,children:r}){return e==="unavailable"||e==="load_error"?null:ze("div",{style:{position:"relative",minHeight:44},children:[c("div",{"data-testid":t,"aria-hidden":e==="ready",style:{position:"absolute",inset:0,height:44,borderRadius:n,background:"#e5e7eb",animation:e==="ready"?void 0:"flopay-pulse 1.5s ease-in-out infinite",opacity:e==="ready"?0:1,transform:e==="ready"?"scale(0.985)":"scale(1)",transition:"opacity 140ms ease-out, transform 140ms ease-out",pointerEvents:"none"}}),c("div",{style:{minHeight:44,opacity:e==="ready"?1:0,transform:e==="ready"?"translateY(0)":"translateY(2px)",transition:"opacity 140ms ease-out, transform 140ms ease-out",pointerEvents:e==="ready"?"auto":"none"},children:r})]})}function Tl(e){return e!=="unavailable"&&e!=="load_error"}function Ji(e){return c(mu,{...e})}function Al({sessionId:e,nonce:t,email:n,billingApiUrl:r,onTokenizedBody:o,onErrorChange:i,isProcessing:s=!1,onButtonClick:l,onDecline:p,onTechnicalFailure:f,runBeforeButtonClick:C,billingName:h,onBuyerIdentityReady:m,onLoadStateChange:w,placeholderBorderRadius:_}){let ae=Br(),{emitInstrument:Y}=Io(er),Pe=Hi(),S=Vi(),[G,X]=le("loading");gt(()=>{w?.(G)},[G,w]);let[ce,Te]=le(!1),Fe=!cn(n?.trim())||!h?.trim(),{request:ve,collect:Ue,finish:bt}=mo(),ot=me(!1),$e=me(null),De=me(null),[ye,we]=le(0),[Qe,Z]=le(!1),Ie=me(!1),be=me(new Map),{startAttempt:ct,finishAttempt:dt,invalidateAttempt:U,isAttemptInvalidated:V,isAttemptCurrent:de}=Wo((re,Q,L)=>{f?.(re,Q,{...L,popupBlocked:L?.popupBlocked??Ir(Q)}),Z(!0),we(Ae=>Ae+1)});gt(()=>{Qe&&De.current?.focus()},[Qe,ye]);let fe=Ze(()=>{we(re=>re+1)},[]),ut=Ze((re,Q,L)=>{U(L),f?.("paypal",re,{code:Q,popupBlocked:Ir(re)}),Z(!0),fe()},[U,f,fe]),Ne=Ze(()=>{window.setTimeout(()=>{($e.current?.querySelector("iframe")??$e.current)?.focus()},0)},[]);gt(()=>{Ie.current&&(Ie.current=!1,Ne())},[Ne,ye]);let x=Ze(()=>{Z(!1),i?.(null),Ne()},[Ne,i]);gt(()=>{if(!Pe||ot.current)return;let re=new URLSearchParams(window.location.search),Q=re.get("payment_intent"),L=re.get("payment_intent_client_secret"),Ae=re.get("redirect_status");if(!Q||!L)return;ot.current=!0;let xe;try{let qe=localStorage.getItem(ea);if(qe){let ke=JSON.parse(qe);ke.clientSecret===L&&(xe={...ke.accountPatch?{accountPatch:ke.accountPatch}:{},...ke.sessionId?{sessionId:ke.sessionId}:{},...ke.nonce?{nonce:ke.nonce}:{}})}}catch{}try{localStorage.removeItem(ea)}catch{}let Me=new URL(window.location.href);Me.searchParams.delete("payment_intent"),Me.searchParams.delete("payment_intent_client_secret"),Me.searchParams.delete("redirect_status"),window.history.replaceState({},"",Me.toString()),(async()=>{try{if(Te(!0),Ae==="failed"){let Ee="PayPal payment was declined. Please try again.";i?.(Ee),p?.(nn("paypal",Ee));return}let{paymentIntent:qe,error:ke}=await Pe.retrievePaymentIntent(L);if(ke){i?.(ke.message??"Failed to retrieve PayPal payment status.");return}if(qe&&(qe.status==="requires_capture"||qe.status==="succeeded")){let Ee=typeof qe.payment_method=="string"?qe.payment_method:qe.payment_method?.id;o({id:Ee??qe.id,type:"card",threeDSecureActionResultTokenId:qe.id,isPaypal:!0},xe)}else{let Ee="PayPal payment was not completed. Please try again.";i?.(Ee),p?.(nn("paypal",Ee))}}catch(qe){i?.(qe instanceof Error?qe.message:"Failed to complete PayPal payment.")}finally{Te(!1)}})()},[Pe,o,i,p]);let at=Ze(async re=>{if(s||ce){re.reject();return}let Q=C?await C("paypal"):{proceed:!0};if(!Q.proceed){be.current.delete(ye),re.reject();return}let L=ct("paypal");be.current.set(ye,{generation:L,accountPatch:Q.accountPatch,sessionId:Q.sessionId,nonce:Q.nonce}),Z(!1),l?.("paypal"),re.resolve()},[s,l,C,ct,ce,ye]),Ye=Ze(async re=>{if(!Pe||!S)return;let Q=be.current.get(ye);if(Q&&!de(Q.generation)){be.current.delete(ye);return}if(!Q&&V()||Q&&!dt(Q.generation))return;Q||dt();let L=Q??null;if(be.current.delete(ye),!L&&C){let Ee=await C("paypal");if(!Ee.proceed){re.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}L={accountPatch:Ee.accountPatch,sessionId:Ee.sessionId,nonce:Ee.nonce}}let Ae=L?.sessionId??e,xe=L?.nonce??t,Me=await Qd({event:re,prepared:L,email:n,billingName:h,methodLabel:"PayPal",collect:Ue});if(!Me){re.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let qe=Me.email,ke={...L?.accountPatch,...Bn(Me,!0)};try{if(Te(!0),i?.(null),!Ae||!cn(qe))throw new Error("Missing sessionId or email for PayPal payment");await m?.(Me);let Ee=Pe.createPaymentMethod,{error:ee,paymentMethod:dn}=await Ee({type:"paypal"});if(ee){ut(ee,"stripe_paypal_create_payment_method_failed",Q?.generation),re.paymentFailed({reason:"fail"});return}let Yt=await Oa(r,Y,Ae,xe??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:dn?.id??null,intentKind:"payment"});if(Yt.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let H=Yt.clientSecret,Je={return_url:window.location.href};if(dn?.id&&(Je.payment_method=dn.id),typeof window<"u")try{localStorage.setItem(ea,JSON.stringify({clientSecret:H,sessionId:Ae,nonce:xe,accountPatch:ke}))}catch{}let{error:$,paymentIntent:K}=await Pe.confirmPayment({clientSecret:H,confirmParams:Je,redirect:"if_required"});if($){if(typeof window<"u")try{localStorage.removeItem(ea)}catch{}if(Ho($)){let u=$.message??"Your payment was declined.";i?.(u),p?.(nn("paypal",u,{code:wr($),declineCode:fo($)})),await za({billingApiUrl:r,sessionId:Ae,nonce:xe,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:wr($)??"provider_declined"}})}else ut($,"stripe_paypal_confirm_failed",Q?.generation);return}if(typeof window<"u")try{localStorage.removeItem(ea)}catch{}let ie=typeof K?.payment_method=="string"?K.payment_method:K?.payment_method?.id;o({id:ie??K?.id,type:"card",threeDSecureActionResultTokenId:K?.id,isPaypal:!0},{accountPatch:ke,paymentMethodCategory:"paypal",sessionId:Ae,nonce:xe});return}catch(Ee){ut(Ee,"stripe_paypal_failed",Q?.generation)}finally{Te(!1)}},[Pe,S,e,t,n,h,Ue,m,r,Y,o,i,p,C,ut,dt,de,V,ye]);return ze(Yr,{children:[c(zl,{state:G,placeholderTestId:"flopay-paypal-placeholder",borderRadius:_,children:ze("div",{ref:$e,tabIndex:-1,"data-testid":"flopay-paypal-focus-target",role:"group","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[Qe&&c("button",{ref:De,type:"button","data-testid":"flopay-paypal-retry-button",onClick:x,style:ji,children:"Try PayPal again"}),ve&&c(yo,{identity:ve.identity,methodLabel:ve.methodLabel,onComplete:bt,onCancel:()=>bt(null)},ve.id),c("div",{style:{display:ve?"none":void 0},children:c(Bl,{onReady:re=>X(Ol(re,["paypal"])),onLoadError:()=>{X("load_error"),Gi(Qt(ae),"paypal","paypal")},onClick:at,onConfirm:Ye,onCancel:()=>{let re=be.current.get(ye);be.current.delete(ye),Qt(ae)?.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),U(re?.generation),Z(!1),Ie.current=!0,fe()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:Fe,emailRequired:Fe,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},ye)})]})}),ce&&c(fr,{status:"processing"})]})}function xl({sessionId:e,nonce:t,email:n,billingApiUrl:r,intentKind:o,expressMethods:i,onTokenizedBody:s,onErrorChange:l,onButtonClick:p,onDecline:f,onTechnicalFailure:C,runBeforeButtonClick:h,billingName:m,onBuyerIdentityReady:w,onLoadStateChange:_,placeholderBorderRadius:ae}){let Y=Br(),{emitInstrument:Pe}=Io(er),S=Hi(),G=Vi(),[X,ce]=le("loading");gt(()=>{_?.(X)},[X,_]);let[Te,Fe]=le(!1),ve=me(!cn(n?.trim())||!m?.trim()).current,{request:Ue,collect:bt,finish:ot}=mo(),$e=me(null),De=me(null),[ye,we]=le(0),[Qe,Z]=le(!1),[Ie,be]=le(()=>Na(e,t)?"blocked":"idle"),[ct,dt]=le("google_pay"),U=me(null),V=me(!0),de=me(!1),fe=me("google_pay"),ut=me("google_pay"),Ne=me(null),x=me(null),at=me(new Set);gt(()=>(V.current=!0,()=>{V.current=!1;for(let $ of at.current)window.clearTimeout($);at.current.clear()}),[]);let Ye=me(new Map),{startAttempt:re,finishAttempt:Q,invalidateAttempt:L,isAttemptInvalidated:Ae,isAttemptCurrent:xe,generationRef:Me}=Wo(($,K,ie)=>{C?.($,K,{...ie,popupBlocked:ie?.popupBlocked??Ir(K)}),dt($),Z(!0),we(u=>u+1)});gt(()=>{Qe&&De.current?.focus()},[Qe,ye]);let qe=Ze(()=>{we($=>$+1)},[]),ke=Ze(($,K,ie,u)=>{L(u),C?.($,K,{code:ie,popupBlocked:Ir(K)}),dt($),Z(!0),qe()},[L,C,qe]),Ee=Ze(()=>{window.setTimeout(()=>{($e.current?.querySelector("iframe")??$e.current)?.focus()},0)},[]);gt(()=>{de.current&&(de.current=!1,Ee())},[Ee,ye]);let ee=Ze(()=>{Z(!1),l?.(null),Ee()},[Ee,l]),dn=Ze(()=>{U.current?.()},[]);gt(()=>{let $=Na(e,t);if(!$)return;let K=!1,ie=!1,u=async()=>{if(!ie){ie=!0,K||be("checking");try{let B=await wl(S,$.clientSecret,at.current);if(K)return;let _e=Oi(B,$.providerObjectId,Fi($.clientSecret));if(_e.kind==="confirmed"){if(!Sl(e,t,$.clientSecret))return;U.current=null,be("idle"),s({id:_e.paymentMethodId,type:"card",threeDSecureActionResultTokenId:_e.intentId},{...$.accountPatch?{accountPatch:$.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t});return}if(_e.kind==="terminal"){Li(e,t,$.clientSecret),U.current=null,be("idle"),dt($.paymentMethodType),Z(!0),qe();return}be("blocked")}catch{K||be("blocked")}finally{ie=!1}}};return U.current=u,be("blocked"),()=>{K=!0,U.current===u&&(U.current=null)}},[t,s,qe,e,S]);let Yt=Ze(async $=>{let K=!1,ie=je=>{K||(K=!0,$.paymentFailed({reason:"fail",...je?{message:je}:{}}))};if(!S||!G){ie();return}let u=Ye.current.get(ye);if(u&&!xe(u.generation)){Ye.current.delete(ye),ie();return}if(!u&&Ae()){ie();return}if(u&&!Q(u.generation)){ie();return}u||Q();let B=$.expressPaymentType??u?.method??fe.current,_e=u??null,Ke=Rl(B),Re;B==="apple_pay"?Re="apple_pay":B==="google_pay"&&(Re="google_pay");let $t=u?.generation??Me.current,N=Qt(Y),Ct=N?.now()??globalThis.performance?.now()??Date.now(),Et=new AbortController,pt=!1,un=!1,O=null,Ot=e,Cn="processing",pn="other",mn="provider_runtime",_n,Fn=new Promise((je,He)=>{_n=He}),Dn=window.setTimeout(()=>{pt=!0,Et.abort(),_n(Di)},Kd),Jt=async(je,He,St)=>{Cn=je,pn=He,mn=He==="intent_create"||He==="session_claim"?"transport_error":"provider_runtime";let rn=N?.now()??globalThis.performance?.now()??Date.now();try{return await Promise.race([St,Fn])}finally{let wt=N?.now()??globalThis.performance?.now()??Date.now();N?.performance({stage:je,durationMs:Math.max(0,wt-rn),durationMode:"machine",requestCategory:He,paymentMethodCategory:"wallet",provider:"stripe",...pt?{statusClass:"timeout"}:{}})}};try{if(Fe(!0),l?.(null),!_e&&h){let se=await Jt("processing","other",h(Ke));if(!se.proceed){ie();return}_e={accountPatch:se.accountPatch,sessionId:se.sessionId,nonce:se.nonce}}let je=_e?.sessionId??e;Ot=je;let He=_e?.nonce??t,St=Ne.current??_e?.accountPatch,rn=Ll({event:$,fallbackEmail:St?.email??n,fallbackName:[St?.firstName,St?.lastName].join(" ").trim()||m});if(!cn(rn.email)){ie("Buyer details are required."),bt($i(B),rn).then(se=>{se&&(Ne.current=se)});return}Ne.current=null;let wt={..._e?.accountPatch,...Bn(rn,!0)};await Jt("processing","session_claim",Promise.resolve(w?.(rn)));let{error:$n}=await Jt("tokenization","provider_sdk",G.submit());if($n){ie(),ke(B,$n,"stripe_wallet_submit_failed",u?.generation);return}if(!je)throw new Error("Missing sessionId or email for payment.");let mt={provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:B,paymentMethodId:null,intentKind:o},Tt=JSON.stringify({sessionId:je,nonce:He??"",request:mt}),zt=x.current,yn=zt?.retryIdentity===Tt?zt.authorizationAttemptId:Dd();x.current={authorizationAttemptId:yn,retryIdentity:Tt};let Ut=await Jt("processing","intent_create",Oa(r,Pe,je,He??"",{...mt,authorizationAttemptId:yn},{signal:Et.signal}));if(Ut.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let At=Ut.clientSecret,Sn=Wd({createdAt:Date.now(),sessionId:je,...He?{nonce:He}:{},clientSecret:At,providerObjectId:Ut.providerObjectId,paymentMethodType:B,accountPatch:wt});window.clearTimeout(Dn),un=!0,N?.performance({stage:"callback",durationMs:Math.max(0,(N?.now()??globalThis.performance?.now()??Date.now())-Ct),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe"});let wn=N?.now()??globalThis.performance?.now()??Date.now(),It={stage:"provider_confirmation",provider:"stripe",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",...Re?{walletType:Re}:{},attempt:$t},te=!1,on=null;N?.log({name:"payment.provider_confirmation.started",...It}),O=window.setTimeout(()=>{O!==null&&at.current.delete(O),te=!0;let se=N?.now()??globalThis.performance?.now()??Date.now();N?.error({errorCode:"PROVIDER_RUNTIME_FAILED",...It,operationOutcome:"watchdog_expired",durationMs:Math.max(0,se-wn),statusClass:"timeout",failureCategory:"provider_runtime"}),N?.flush?.().catch(()=>{}),on?.()},Vd),at.current.add(O);let Kn=se=>{O!==null&&(window.clearTimeout(O),at.current.delete(O),O=null);let M=N?.now()??globalThis.performance?.now()??Date.now(),Oe=Math.max(0,M-wn),D=se;return te&&(se==="resolved"?D="resolved_late":se==="returned_error"?D="returned_error_late":D="rejected_late"),N?.log({name:"payment.provider_confirmation.returned",...It,operationOutcome:D}),N?.performance({...It,durationMs:Oe,durationMode:"buyer",operationOutcome:D}),{durationMs:Oe,operationOutcome:D}},Ht=!1,Kt=!1,an=se=>{if(!se||typeof se!="object")return null;let M=se;if(M.error)return null;let Oe=M.setupIntent??M.paymentIntent,D=Oi(Oe??null,void 0,!!M.setupIntent);return D.kind==="confirmed"?D:null},nr=se=>{if(Ht||u&&Me.current!==u.generation)return;let M=an(se);if(!M)return;if(Sn&&!Sl(je,He,At)){Ht=!0;return}let{intentId:Oe,paymentMethodId:D}=M;Ht=!0,Kt=!0,x.current=null,U.current=null,V.current&&(be("idle"),Fe(!1));let kt=`${Fl}:${je}`;if(typeof window<"u")try{localStorage.setItem(kt,JSON.stringify({createdAt:Date.now(),sessionId:je,nonce:He,accountPatch:wt,paymentMethodId:D,providerIntentId:Oe,paymentMethodType:B}))}catch{}try{s({id:D,type:"card",threeDSecureActionResultTokenId:Oe},{accountPatch:wt,paymentMethodCategory:"wallet",sessionId:je,nonce:He})}finally{if(typeof window<"u")try{localStorage.removeItem(kt)}catch{}}},Nn=!1;on=async()=>{if(!(Nn||Ht||Kt)){Nn=!0,V.current&&be("checking");try{let se=await wl(S,At,at.current);if(Ht||Kt)return;let M=Fi(At),Oe=Oi(se,Ut.providerObjectId,M);if(Oe.kind==="confirmed"){nr(M?{setupIntent:se}:{paymentIntent:se});return}if(Oe.kind==="terminal"){if(Kt=!0,Li(je,He,At),x.current=null,U.current=null,!V.current)return;be("idle"),ie(),ke(B,new Error("Wallet confirmation did not complete."),"stripe_wallet_confirmation_terminal",u?.generation);return}V.current&&!Kt&&(be("blocked"),Fe(!1))}catch{V.current&&!Kt&&(be("blocked"),Fe(!1))}finally{Nn=!1}}},U.current=on;let Wt,Le;try{let se=await(Fi(At)?S.confirmSetup({elements:G,clientSecret:At,redirect:"if_required"}):S.confirmPayment({elements:G,clientSecret:At,redirect:"if_required"}));if(!se||typeof se!="object"||(Wt=se,!Wt.error&&!an(Wt)))throw Ni;Le=Kn(Wt.error?"returned_error":"resolved")}catch(se){let M=se===Ni,Oe=Kn(M?"returned_error":"rejected");if(N?.error({...M?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response"}:pi(se),...It,operationOutcome:Oe.operationOutcome,durationMs:Oe.durationMs,statusClass:"unknown"}),!V.current||Ht)return;await on?.();return}let fn=Wt.error;if(fn){if(!V.current||Ht)return;if(Ho(fn)){Kt=!0,Li(je,He,At),x.current=null,U.current=null,be("idle");let se=fn.message??"Your payment was declined.";ie(se),l?.(se),f?.(nn(Ke,se,{code:wr(fn),declineCode:fo(fn)})),za({billingApiUrl:r,sessionId:je,nonce:He,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:B,providerDeclineReason:wr(fn)??"provider_declined",...Ut.intentKind==="payment"&&Ut.providerObjectId.startsWith("pi_")?{providerIntentId:Ut.providerObjectId}:{}}})}else N?.error({...pi(fn),...It,operationOutcome:Le.operationOutcome,durationMs:Le.durationMs,statusClass:"unknown"}),await on?.();return}if(nr(Wt),!Ht)throw new Error("Invalid provider returned for APM intent")}catch(je){if(je===Di){let He=N?.now()??globalThis.performance?.now()??Date.now();N?.error({errorCode:Yd(pn),stage:Cn,requestCategory:pn,paymentMethodCategory:"wallet",provider:"stripe",...Re?{walletType:Re}:{},operationOutcome:"watchdog_expired",checkoutSessionId:Ot,durationMs:Math.max(0,He-Ct),statusClass:"timeout",failureCategory:mn,attempt:$t}),N?.flush?.().catch(()=>{})}ie(),ke(B,je,je===Di?"stripe_wallet_authorization_timeout":"stripe_wallet_failed",u?.generation)}finally{if(window.clearTimeout(Dn),O!==null&&(window.clearTimeout(O),at.current.delete(O)),!un){let je=N?.now()??globalThis.performance?.now()??Date.now();N?.performance({stage:"callback",durationMs:Math.max(0,je-Ct),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe",...pt?{statusClass:"timeout"}:{}})}V.current&&Fe(!1)}},[S,G,e,t,n,m,bt,w,r,Pe,o,s,l,f,h,ke,Q,xe,Ae,Me,Y,ye]),H=Ft(()=>{let $=["applePay","googlePay","paypal","link","amazonPay","klarna"],K=new Set(["applePay","googlePay"]),ie=new Set(i.map(bl)),u={};for(let B of $)ie.has(B)?u[B]=K.has(B)?"always":"auto":u[B]="never";return u},[i]),Je=Ft(()=>i.map(bl),[i]);return ze(Yr,{children:[c(zl,{state:X,placeholderTestId:"flopay-wallet-placeholder",borderRadius:ae,children:ze("div",{ref:$e,tabIndex:-1,"data-testid":"flopay-wallet-focus-target",role:"group","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[Qe&&ze("button",{ref:De,type:"button","data-testid":"flopay-wallet-retry-button",onClick:ee,style:ji,children:["Try ",$i(ct)," again"]}),Ie!=="idle"&&ze("div",{role:"status","aria-live":"polite",children:[c("p",{children:"We are still confirming your payment. Check its status before trying again."}),c("button",{type:"button",onClick:dn,disabled:Ie==="checking",style:ji,children:Ie==="checking"?"Checking payment status\u2026":"Check payment status"})]}),Ue&&c(yo,{identity:Ue.identity,methodLabel:Ue.methodLabel,onComplete:ot,onCancel:()=>ot(null)},Ue.id),Ie==="idle"&&c("div",{style:{display:Ue?"none":void 0},children:c(Bl,{onReady:$=>{ce(Ol($,Je))},onLoadError:$=>{ce("load_error"),Gi(Qt(Y),"stripe","wallet")},onClick:async $=>{fe.current=$.expressPaymentType,ut.current=Rl($.expressPaymentType);let K=!0,ie=window.setTimeout(()=>{K=!1,$.reject()},$d),u=h?await h(ut.current):{proceed:!0};if(window.clearTimeout(ie),!K)return;if(!u.proceed){Ye.current.delete(ye),$.reject();return}let B=re($.expressPaymentType);Ye.current.set(ye,{generation:B,method:$.expressPaymentType,accountPatch:u.accountPatch,sessionId:u.sessionId,nonce:u.nonce}),Z(!1),p?.(ut.current),$.resolve()},onConfirm:Yt,onCancel:()=>{let $=Ye.current.get(ye);Ye.current.delete(ye),Qt(Y)?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet"}),L($?.generation),x.current=null,Z(!1),de.current=!0,qe()},options:{buttonType:{applePay:"plain",googlePay:"plain"},paymentMethods:H,emailRequired:ve,billingAddressRequired:ve,layout:{maxColumns:1,overflow:"never"}}},ye)})]})}),Te&&c(fr,{status:"processing"})]})}function Ul(e,t){return{...e,paymentMethodTypes:[t],...t==="revolut_pay"||t==="sepa_debit"||t==="us_bank_account"?{setupFutureUsage:"off_session"}:null}}function pu({method:e,themeId:t,submitting:n=!1,disabled:r=!1,highlighted:o=!1,hasNextStep:i=!1,onClick:s,backgroundColor:l,borderColor:p,textColor:f,borderRadius:C,fontFamily:h}){let m=Od(e,t),w=hl[e],[_,ae]=le(!1),Y=!!w&&!_,Pe=m?.backgroundColor??l??"#ffffff",S=m?.borderColor??p??"#d1d5db",G=m?.textColor??f??"#262833";return c("button",{type:"button","data-testid":`flopay-stripe-method-button-${e}`,"data-method":e,onClick:()=>{!n&&!r&&s()},disabled:n||r,"aria-busy":n||void 0,style:{position:"relative",width:"100%",boxSizing:"border-box",height:La,padding:"0 1rem",backgroundColor:Pe,color:G,border:`1px solid ${S}`,borderRadius:C??8,fontSize:"0.95rem",fontWeight:600,fontFamily:h,cursor:n||r?"not-allowed":"pointer",opacity:r&&!n?.55:1,animation:n?"flopay-pulse 1.5s ease-in-out infinite":void 0,display:"flex",alignItems:"center",justifyContent:"center",gap:8,transition:"transform 0.1s, opacity 140ms ease-out, border-color 140ms ease-out",boxShadow:o?"0 0 0 2px rgba(74, 73, 255, 0.15)":void 0},children:n?c("span",{style:{margin:"0 auto"},children:`Connecting to ${Jr(e)}\u2026`}):ze(Yr,{children:[ze("span",{style:{display:"inline-flex",alignItems:"center",gap:Ad(e)?8:0},children:[Y?c("img",{src:w,alt:"","aria-hidden":"true",onError:()=>ae(!0),loading:"lazy",decoding:"async",width:30,height:20,style:{width:30,height:20,flexShrink:0,borderRadius:3,objectFit:"contain",display:"inline-flex"}}):null,!Y&&m?.logoSvg?c("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:m.logoSvg}}):null,c("span",{children:Jr(e)})]}),i&&c("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:G,strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{position:"absolute",right:"1rem",top:"50%",transform:"translateY(-50%)",flexShrink:0,opacity:.7},"aria-hidden":"true",children:c("path",{d:"M9 18l6-6-6-6"})})]})})}function Ki({method:e,sessionId:t,nonce:n,email:r,billingName:o,onBuyerIdentityReady:i,billingApiUrl:s,onTokenizedBody:l,onErrorChange:p,onDecline:f,onCancel:C,runBeforeButtonClick:h,onButtonClick:m,isProcessing:w,submitButtonColor:_,submitButtonBorderRadius:ae,submitButtonStyle:Y,errorText:Pe}){let S=Br(),{emitInstrument:G}=Io(er),X=Hi(),ce=Vi(),[Te,Fe]=le(!1),ve=me(!1),[Ue,bt]=le(!1),[ot,$e]=le("loading"),[De,ye]=le(""),we=!cn(r?.trim()),Qe=!we||cn(De.trim()),Z=Ze(async()=>{if(!X||!ce||w||ve.current||!Ue)return;ve.current=!0,Fe(!0);let Ie=h?await h("card"):{proceed:!0};if(!Ie.proceed){ve.current=!1,Fe(!1);return}m?.("card");let be=Ie.sessionId??t,ct=Ie.nonce??n,dt=Vr(o?.trim()),U=Bn({email:Ie.accountPatch?.email?.trim()||r?.trim()||De.trim(),firstName:Ie.accountPatch?.firstName?.trim()||dt.firstName,lastName:Ie.accountPatch?.lastName?.trim()||dt.lastName}),V=U.email,de=Bn({...Ie.accountPatch,...U});try{if(p?.(null),!cn(V))throw new Error("A valid email address is required for payment.");await i?.(U);let fe=await ce.submit();if(fe.error){p?.(fe.error.message??"Payment failed.");return}let ut=[U.firstName,U.lastName].filter(Boolean).join(" "),Ne=await X.createPaymentMethod({elements:ce,params:{billing_details:{email:V,...ut?{name:ut}:{}}}});if(Ne.error||!Ne.paymentMethod){p?.(Ne.error?.message??"Failed to create payment method.");return}let x=Ne.paymentMethod;if(!be||!V)throw new Error("Missing sessionId or email for payment.");let at=x.type||e,Ye=await Oa(s,G,be,ct??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:at,paymentMethodId:null,intentKind:"payment"});if(Ye.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let re=Ye.clientSecret;if(typeof window<"u")try{localStorage.setItem(hr,JSON.stringify({clientSecret:re,sessionId:be,nonce:ct,accountPatch:de,paymentMethodId:x.id,paymentMethodType:x.type??e,gateway:"stripe"}))}catch{}let{error:Q,paymentIntent:L}=await X.confirmPayment({clientSecret:re,confirmParams:{return_url:window.location.href,payment_method:x.id},redirect:"if_required"});if(Q){if(typeof window<"u")try{localStorage.removeItem(hr)}catch{}let Me=Q.message??"Payment failed.";p?.(Me),f?.(nn("card",Me,{code:Q.code})),await za({billingApiUrl:s,sessionId:be,nonce:ct,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:Q.code??"provider_declined"}});return}let Ae=L?.status;if(!$o(Ae)){if(typeof window<"u")try{localStorage.removeItem(hr)}catch{}let Me=Ae==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";p?.(Me),f?.(nn("card",Me,{code:Ae??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(hr)}catch{}let xe=typeof L?.payment_method=="string"?L.payment_method:L?.payment_method?.id;l({id:xe??x.id,type:"card",threeDSecureActionResultTokenId:L?.id,gateway:"stripe",paymentMethodType:x.type??e},{accountPatch:de,paymentMethodCategory:"apm",sessionId:be,nonce:ct})}catch(fe){p?.(fe instanceof Error?fe.message:"Payment failed. Please try again.")}finally{ve.current=!1,Fe(!1)}},[X,ce,w,Ue,h,m,t,n,r,o,De,i,s,G,e,l,p,f]);return ze("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[we&&c("div",{"data-testid":"flopay-apm-identity-fields",style:{display:"flex",flexDirection:"column",gap:"0.75rem",marginBottom:"0.75rem"},children:we&&ze("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",c("input",{type:"email",autoComplete:"email",required:!0,value:De,onChange:Ie=>ye(Ie.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]})}),c(Ud,{onReady:()=>$e("ready"),onLoadError:()=>{$e("load_error"),Gi(Qt(S),"stripe","apm")},onChange:Ie=>{bt(!!Ie.complete)},options:{layout:{type:"accordion",defaultCollapsed:!1,radios:"never"},fields:{billingDetails:{email:"never"}},defaultValues:{billingDetails:{...o?.trim()?{name:o.trim()}:{},...cn(r?.trim())?{email:r?.trim()}:{}}}}}),c("button",{type:"button","data-testid":`flopay-stripe-method-pay-${e}`,onClick:()=>{Z()},disabled:!Ue||!Qe||Te||w||ot!=="ready",style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:_,color:"white",border:"none",borderRadius:ae,fontSize:"1rem",fontWeight:600,cursor:!Ue||!Qe||Te||w||ot!=="ready"?"not-allowed":"pointer",opacity:!Ue||!Qe||Te||w||ot!=="ready"?.5:1,transition:"opacity 120ms ease-out",...Y??{}},children:Te?"Processing\u2026":`Pay with ${Jr(e)}`}),Pe&&c(ho,{margin:"0.75rem 0 0",children:Pe})]})}function Ml({sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:i,paymentElementMethods:s,stripeInstance:l,paymentElementBaseOptions:p,onTokenizedBody:f,onErrorChange:C,onButtonClick:h,onDecline:m,runBeforeButtonClick:w,onLoadStateChange:_,isProcessing:ae=!1,submitButtonColor:Y="#4A49FF",submitButtonBorderRadius:Pe=8,submitButtonStyle:S,buttonAppearance:G,themeId:X,onExpandApm:ce,expandedApmMethod:Te}){let{emitInstrument:Fe}=Io(er),[ve,Ue]=le(null),[bt,ot]=le(null),$e=me(!1),{request:De,collect:ye,finish:we}=mo();gt(()=>{s.length>0&&l?_?.("ready"):l||_?.("loading")},[s.length,l,_]);let Qe=Ze(async U=>{if(!l||$e.current||ae)return;$e.current=!0,ot(U);let V=w?await w("card"):{proceed:!0};if(!V.proceed){$e.current=!1,ot(null);return}h?.("card");let de=V.sessionId??e,fe=V.nonce??t,ut=Vr([V.accountPatch?.firstName,V.accountPatch?.lastName].filter(Boolean).join(" ")||r),Ne=Bn({email:V.accountPatch?.email?.trim()||n?.trim(),firstName:V.accountPatch?.firstName?.trim()||ut.firstName,lastName:V.accountPatch?.lastName?.trim()||ut.lastName});if(!cn(Ne.email)){ot(null);let Ye=await ye(Jr(U),Ne);if(!Ye){$e.current=!1;return}Ne=Ye,ot(U)}let x=Ne.email,at=Bn({...V.accountPatch,...Ne});try{if(C?.(null),!de||!cn(x))throw new Error("Missing sessionId or email for payment.");await o?.(Ne);let Ye=await Oa(i,Fe,de,fe??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:U,paymentMethodId:null,intentKind:"payment"});if(Ye.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let re=Ye.clientSecret;if(typeof window<"u")try{localStorage.setItem(hr,JSON.stringify({clientSecret:re,sessionId:de,nonce:fe,accountPatch:at,paymentMethodType:U,gateway:"stripe"}))}catch{}let{error:Q,paymentIntent:L}=await l.confirmPayment({clientSecret:re,confirmParams:{return_url:window.location.href,payment_method_data:{type:U,billing_details:{name:[Ne.firstName,Ne.lastName].filter(Boolean).join(" "),...x?{email:x}:{}}}},redirect:"if_required"});if(Q){if(typeof window<"u")try{localStorage.removeItem(hr)}catch{}let Me=Q.message??"Payment failed.";C?.(Me),m?.(nn("card",Me,{code:Q.code})),await za({billingApiUrl:i,sessionId:de,nonce:fe,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:U,providerDeclineReason:Q.code??"provider_declined"}});return}let Ae=L?.status;if(!$o(Ae)){if(typeof window<"u")try{localStorage.removeItem(hr)}catch{}let Me=Ae==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";C?.(Me),m?.(nn("card",Me,{code:Ae??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(hr)}catch{}let xe=typeof L?.payment_method=="string"?L.payment_method:L?.payment_method?.id;f({id:xe??L?.id,type:"card",threeDSecureActionResultTokenId:L?.id,gateway:"stripe",paymentMethodType:U},{accountPatch:at,paymentMethodCategory:"apm",sessionId:de,nonce:fe})}catch(Ye){C?.(Ye instanceof Error?Ye.message:"Payment failed. Please try again.")}finally{$e.current=!1,ot(null)}},[l,ae,w,h,e,t,n,ye,i,Fe,r,o,f,C,m]),[Z,Ie]=le(null),be=ce?Te??null:Z,ct=Ze(U=>{$e.current||ae||be&&be!==U||(Pl(U)?ce?ce(U):Ie(U):Qe(U))},[be,ae,Qe,ce]),dt=Ft(()=>Z?Ul(p,Z):null,[Z,p]);return c("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:De?c(yo,{identity:De.identity,methodLabel:De.methodLabel,onComplete:we,onCancel:()=>we(null)},De.id):s.map(U=>{let V=Te===U,de=bt===U,fe=bt!==null&&bt!==U||Te!=null&&Te!==U;return ze(qd.Fragment,{children:[c(pu,{method:U,themeId:X,submitting:de,disabled:fe,highlighted:V,hasNextStep:Pl(U),onClick:()=>ct(U),backgroundColor:G?.backgroundColor,borderColor:G?.borderColor,textColor:G?.textColor,borderRadius:G?.borderRadius,fontFamily:G?.fontFamily}),!ce&&Z===U&&dt&&l&&c(Gr,{stripe:l,options:dt,children:c(Ki,{method:U,sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:i,onTokenizedBody:f,onErrorChange:C,onDecline:m,onCancel:()=>Ie(null),runBeforeButtonClick:w,onButtonClick:h,isProcessing:ae,submitButtonColor:Y,submitButtonBorderRadius:Pe,submitButtonStyle:S})},U)]},U)})})}function mu({sessionId:e,nonce:t,billingApiUrl:n,telemetry:r,email:o,userId:i,onComplete:s,onError:l,onDecline:p,onTokenizedBody:f,firstName:C,lastName:h,chv:m,className:w,submitLabel:_,isProcessing:ae,error:Y,onErrorChange:Pe,showPayPal:S=!0,showStripe:G=!0,enabledPaymentMethods:X,enabledPaymentMethodCountries:ce,showApplePay:Te=!0,showGooglePay:Fe=!0,layout:ve="default",theme:Ue,buttonsTheme:bt,buttonsStyles:ot,appearance:$e,cardButtonContent:De,cardBackButtonContent:ye,cardTitleContent:we,showSecurityFooter:Qe,onButtonClick:Z,onBeforeButtonClick:Ie,onBuyerIdentityReady:be,enableAVS:ct,cardFieldOrder:dt,cardPreFormSlot:U,avsLayout:V="row",country:de,zip:fe,addressLine1:ut,addressLine2:Ne,city:x,state:at,onCountryChange:Ye,onZipChange:re,avsCheck:Q,checkoutType:L,checkoutLayout:Ae,totalAmount:xe=0,currency:Me="usd",initialCardOpen:qe=!1,directPaypal:ke,isSubscription:Ee=!1,session:ee,dataAttachmentPending:dn=!1,dataAttachmentRequiresIdentity:Yt=!1,debug:H=!1}){let Je=Br(),$=mi(),K=Io(cr),{emitInstrument:ie}=Io(er),u=ee??K.session,B=u?.gateways?.paypal?.providerObjectType??ke?.providerObjectType,_e=dn||K.claimPending===!0,Ke=Yt||K.claimRequiresIdentity===!0,Re=_e&&!Ke,$t=rl(),N=n||$t,[Ct,Et]=le(!1),[pt,un]=le(null),[O,Ot]=le(de??"US"),[Cn,pn]=le(fe??""),[mn,_n]=le(ut??""),[Fn,Dn]=le(Ne??""),[Jt,je]=le(x??""),[He,St]=le(at??""),[rn,wt]=le(""),[$n,mt]=le({}),Tt=me(fe??""),zt=me(de??"US"),yn=me(ut??""),Ut=me(Ne??""),At=me(x??""),Sn=me(at??""),wn=me(""),It=me({});gt(()=>{let a=(b,j,Be,W,st)=>{if(It.current[b])return;let tt=j?.trim();!tt||tt===Be.current||(Be.current=tt,W(tt),st?.(tt))};a("country",de,zt,Ot,Ye),a("zip",fe,Tt,pn,re),a("addressLine1",ut,yn,_n),a("addressLine2",Ne,Ut,Dn),a("city",x,At,je),a("state",at,Sn,St)},[de,fe,ut,Ne,x,at,Ye,re]);let te=Ft(()=>Nd(ct),[ct]),on=te!==null,Kn=Ft(()=>Bi(ee),[ee]),Ht=!!ee?.vault?.html,Kt=!!ee?.gateways?.pcivault,an=ci(ee),Nn=!!(ee?.gateways?.stripe?.enabledPaymentMethods??X)?.includes("card")||Ar(ee),Wt=Ht||Nn||Kt,Le=!!(G&&Wt&&e),[fn,se]=le(()=>ve!=="buttons"||qe?e??null:null),[M,Oe]=le(0),D=ve!=="buttons"||qe||!!e&&fn===e,kt=ee?.captureMethod,xt=me(Je);gt(()=>{xt.current=Je},[Je]);let[Gt,Vn]=le(null);gt(()=>{if(!Le||!e||!D){Vn(null);return}let a=xt.current?xt.current.cardCapture({sessionId:e,captureMethod:kt}):new wd({sessionId:e,captureMethod:kt,billingApiUrl:N,telemetry:r});return Vn({sessionId:e,captureMethod:kt,billingApiUrl:N,telemetry:r,capture:a}),()=>{a.unmount()}},[Le,e,D,kt,N,r]);let ge=Le&&e&&D&&Gt?.sessionId===e&&Gt.captureMethod===kt&&Gt.billingApiUrl===N&&Gt.telemetry===r?Gt.capture:null,sn=Ft(()=>{let a=O,b=te?rt(te.postal_code,a):!1;return cu(a,Cn,b)},[te,O,Cn]),{avsInvalid:Hn,invalidAvsFields:Pr}=Ft(()=>{let a={line1:!1,city:!1,state:!1,zip:!1};if(!Le||!te)return{avsInvalid:!1,invalidAvsFields:a};let b=O,j=(st,tt)=>rt(st,b)&&!tt.trim(),Be={line1:j(te.address_line_1,mn),city:j(te.city,Jt),state:j(te.state,He),zip:sn.empty||sn.malformed};return{avsInvalid:Be.line1||Be.city||Be.state||Be.zip,invalidAvsFields:Be}},[Le,te,O,mn,Jt,He,sn]),[rr,zr]=le(!1),[Ur,or]=le(!1),[Er,Rn]=le(!1),[ar,Dt]=le({line1:!1,city:!1,state:!1}),Ln=me(!1),Wn=me({email:!1,line1:!1,city:!1,state:!1,zip:!1}),Gn=me(!1),yt=Ze(a=>{Wn.current[a]=!0,Gn.current=!0},[]),En=Ze(a=>!Ln.current&&Wn.current[a],[]),Yn=Ze(a=>{En(a)&&Dt(b=>b[a]?b:{...b,[a]:!0})},[En]),[ir,gn]=le(()=>zi(ee?.vault)),[We,hn]=le(qe&&Wt?"card":"buttons"),[ln,On]=le(null),br=We==="expanding"||We==="card",qr=ee?.gateways?.stripe&&!an?"stripe":void 0,Cr=Ze(()=>{ie?.({class:"card_surface",provider:qr})},[qr,ie]),zn=me(null),vn=Ze(a=>{zn.current&&clearTimeout(zn.current),zn.current=setTimeout(()=>{zn.current=null,a()},ta)},[]);gt(()=>()=>{zn.current&&clearTimeout(zn.current)},[]);let Xr=Ze(()=>{Cr(),se(e??null),Oe(a=>a+1),hn("expanding"),vn(()=>hn("card"))},[vn,Cr,e]),Tn=Ze(()=>{hn("collapsing"),vn(()=>hn("buttons"))},[vn]),Tr=Ze(a=>{On(a),hn("apm-expanding"),vn(()=>hn("apm-form"))},[vn]),In=Ze(()=>{hn("apm-collapsing"),vn(()=>{hn("buttons"),On(null)})},[vn]);gt(()=>{ve==="buttons"&&qe&&Wt&&(se(e??null),hn("card"))},[ve,qe,Wt,e]);let[Un,et]=le(null),Jn=me(!1),Xt=me(null),_t=me("idle"),[T,E]=le(!1),F=me(T);F.current=T;let[z,it]=le(()=>ke?.existingOrderId?{orderId:ke.existingOrderId,attempts:1}:null),R=me(z);gt(()=>{R.current=z},[z]);let d=me(null),A=Ft(()=>{if(be||K.claimBuyerIdentity||ee?.buyerIdentified!==!1||!e||!t)return;let a=`${N}|${e}|${t}`;d.current?.key!==a&&(d.current={key:a,claim:uo(new wo(N,{telemetry:!1}),e,t,{...i?{userId:i}:{},...C?{firstName:C}:{},...h?{lastName:h}:{}})});let b=d.current.claim;return async j=>{await b(j)}},[be,K.claimBuyerIdentity,ee?.buyerIdentified,e,t,N,i,C,h]),g=be??K.claimBuyerIdentity??A,P=Y??pt,I=Ft(()=>zd(Ue),[Ue]),v=Ft(()=>{let a=I?.buttonsLayout??Ld(bt);return ot?{...a,...ot,cardButton:{...a.cardButton,...ot.cardButton},cardFormContainer:{...a.cardFormContainer,...ot.cardFormContainer},backButton:{...a.backButton,...ot.backButton},backButtonIcon:{...a.backButtonIcon,...ot.backButtonIcon},submitButton:{...a.submitButton,...ot.submitButton},title:{...a.title,...ot.title}}:a},[I,bt,ot]),q=$e??I?.appearance,Ve=Ft(()=>Us({appearance:q,buttonsStyles:v,layout:ve}),[q,v,ve]),Nt=K.inlineSessionPatchProcessing??!1,Ce=(ae??Ct)||Nt,ne=N.replace(/\/+$/,""),y=Ft(()=>ui({userId:i,email:o,firstName:C,lastName:h,country:de,zip:fe},$n),[i,o,C,h,de,fe,$n]),k=[y.firstName,y.lastName].filter(a=>!!a?.trim()).join(" "),J=!cn(y.email?.trim()),ue=me(null);Le&&ue.current===null&&(ue.current=J);let Se=Le&&(ue.current??J),pe=Ft(()=>du(rn,Se),[rn,Se]),Ge=pe.empty||pe.malformed,ht=Ft(()=>Je?Je.getRawProvider():null,[Je]),tn=Ft(()=>$?$.getRawProvider():null,[$]),qn=xe||100,Zr=Me.toLowerCase(),Ka=Ft(()=>q?Id(q):null,[q]),Qr=Ka,ss=Ft(()=>{let a=Ka??{},b=a.rules??{};return{...a,rules:{...b,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...b[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...b[".AccordionItemContents"]??{}}}}},[Ka]),ls=Ft(()=>({...Xs(xe,ee?.captureMethod),currency:Zr,...Qr?{appearance:Qr}:null}),[xe,Zr,ee?.captureMethod,Qr]),cs=Ft(()=>({mode:"payment",amount:qn,currency:Zr,captureMethod:"manual",setupFutureUsage:"off_session",...Qr?{appearance:Qr}:null}),[qn,Zr,Qr]),he=Ze(a=>{un(a),Pe?.(a)},[Pe]),Va=me(""),[ds,Ql]=le(!1),Ha=Ze(()=>{Ql(!0)},[]);gt(()=>{if(!Le||!Se||!g||!ds||Ge||Va.current)return;let a=Bn({email:cn(y.email?.trim())?y.email?.trim():wn.current.trim(),firstName:y.firstName?.trim(),lastName:y.lastName?.trim()});Va.current=JSON.stringify(a),mt(b=>({...b,...a})),Promise.resolve(g(a)).catch(b=>{Va.current="",he(b instanceof Error?b.message:"Failed to attach buyer details.")})},[Le,Se,g,ds,Ge,y.email,y.firstName,y.lastName,he]),gt(()=>{!Le||!ge||ge.setCardFieldOrder?.(dt??null,te==null&&!Se)},[Le,ge,dt,te,Se]),gt(()=>{(We==="expanding"||We==="collapsing"||We==="apm-expanding"||We==="apm-collapsing")&&he(null)},[We,he]);let pr=Ze((a,b,j)=>{p?.(nn(a,b,j))},[p]),eo=Ze((a,b,j)=>{let Be=j?.popupBlocked??Ir(b),W=su(a,Be),st=Hr(j?.code)??wr(b)??"external_payment_method_failed",tt=new dr(W,"api_error",{code:"external_payment_method_failed",param:a});et(null),ve==="buttons"&&(hn("buttons"),On(null)),he(W),l?.(tt),console.error("[FloPay] External payment method failed:",{method:a,code:st,popupBlocked:Be})},[ve,l,he]);gt(()=>{if(!Le||!e){gn(null);return}let a=zi(ee?.vault);if(a){gn(a);return}if(!D){gn(null);return}gn(null);let b=!0;return new wo(ne).getVaultCapture(e,t).then(j=>{if(!b)return;let Be=zi(j);Be?gn(Be):he("Failed to load the secure card form.")}).catch(j=>{b&&he(j instanceof Error?j.message:"Failed to load the secure card form.")}),()=>{b=!1}},[Le,D,M,e,ee?.vault,ne,t,he]);let sr=me({onComplete:s,onError:l,updateError:he,emitDecline:pr,resolvedAccount:y,avsConfig:te,avsCheckProp:Q,sessionId:e,nonce:t,baseUrl:ne,captureMethod:ee?.captureMethod,paymentId:ee?.paymentId,authorizationExpiresAt:ee?.authorizationExpiresAt,serverSideCardGateway:an});sr.current={onComplete:s,onError:l,updateError:he,emitDecline:pr,resolvedAccount:y,avsConfig:te,avsCheckProp:Q,sessionId:e,nonce:t,baseUrl:ne,captureMethod:ee?.captureMethod,paymentId:ee?.paymentId,authorizationExpiresAt:ee?.authorizationExpiresAt,serverSideCardGateway:an};let Wa=me(!1),us=Ze(()=>{let a=sr.current,b=a.resolvedAccount.email?.trim(),j=cn(b)?b:wn.current.trim();if(!cn(j))return null;let Be=a.resolvedAccount.firstName?.trim(),W=a.resolvedAccount.lastName?.trim(),st=zt.current||a.resolvedAccount.country||"US",tt=a.avsConfig?rt(a.avsConfig.state,st):!1,yr=a.avsConfig?rt(a.avsConfig.address_line_1,st):!1,Xe=a.avsConfig?rt(a.avsConfig.postal_code,st):!1,Mt=a.avsConfig?rt(a.avsConfig.city,st):!1,ft=a.avsConfig?rt(a.avsConfig.address_line_2,st):!1,nt=yr&&!tt&&Xe?vl(st,(Tt.current??"").trim()):null,Mn=tt?Sn.current:nt;return{accountData:{userId:a.resolvedAccount.userId??"",email:j,...Be?{firstName:Be}:{},...W?{lastName:W}:{},...Xe&&Tt.current?{zip:Tt.current}:{},...Mt&&At.current?{city:At.current}:{},...Mn?{state:Mn}:{},...yr&&yn.current?{addressLine1:yn.current}:{},...ft&&Ut.current?{addressLine2:Ut.current}:{},country:st},...a.avsCheckProp===void 0?{}:{avsCheck:a.avsCheckProp},...a.avsConfig?{avsConfig:{country:rt(a.avsConfig.country,st),postal_code:Xe,address_line_1:yr,address_line_2:ft,city:Mt,state:tt}}:{}}},[]),ps=me(_e);ps.current=_e,gt(()=>{_e||P!==Il||sr.current.updateError(null)},[_e,P]),gt(()=>{!Le||!ge||ge.setSubmitGate?.(Hn||_e||Ge||T)},[Le,ge,Hn,_e,Ge,T]),gt(()=>{if(!Le||!ge)return;Wa.current=!1;let a=null,b=()=>{a&&clearTimeout(a),a=setTimeout(()=>{a=null,_t.current="idle",et(null)},400)},j=ge.on("submitting",()=>{zr(!0),Xt.current&&clearTimeout(Xt.current),_t.current="validation-window",Xt.current=setTimeout(()=>{Xt.current=null,_t.current==="validation-window"&&(_t.current="processing")},Jd),et("processing");let Xe=sr.current;if(!Xe.sessionId||!Xe.nonce)return;let Mt=us();if(!Mt){Xe.updateError("Enter a valid email address."),_t.current="idle",et(null);return}new wo(Xe.baseUrl).patchAccountSnapshot(Xe.sessionId,Xe.nonce,Mt,{telemetryMode:"best_effort"}).catch(ft=>{if(!Zd(ft))return;let nt=ft instanceof Error?ft.message:"Please check your billing address and try again.";Xe.updateError(nt),_t.current="idle",et(null),Xe.onError?.(ft instanceof dr?ft:new dr(nt,"api_error"))})}),Be=ge.on("complete",async Xe=>{if(bo(Xe.sessionId??sr.current.sessionId),_t.current="terminal",E(!1),et("success"),await new Promise(Mn=>setTimeout(Mn,600)),Wa.current)return;Wa.current=!0;let Mt=sr.current,ft=Bi(Mt)||Xe.outcome==="authorized",nt=Mt.serverSideCardGateway?{}:{paymentIntentId:Xe.intentId};sr.current.onComplete?.(ft?{status:"authorized",...nt,paymentId:Xe.paymentId??Mt.paymentId,sessionId:Xe.sessionId??Mt.sessionId,authorizationExpiresAt:Xe.authorizationExpiresAt??Mt.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",...nt,checkoutMethod:"card"})}),W=ge.on("decline",Xe=>{let Mt=sr.current,ft=Xe.message??"Your payment was declined. Please try another card or contact your bank.";_t.current="terminal",E(!1),Mt.updateError(ft),et("error");let nt=Xe.failureOutcome??Bd(Xe.declineReason)??"authorization_declined";Mt.emitDecline("card",ft,{code:nt,declineCode:nt}),b()}),st=ge.on("error",Xe=>{let Mt=sr.current,ft=Xe.message??"There was a problem processing your payment. Please try again.";_t.current="terminal",E(!1),Mt.updateError(ft),et("error"),Mt.onError?.(new dr(ft,"api_error",{code:Xe.failureOutcome??"capture_failed"})),b()}),tt=ge.on("challenge_dismissed",()=>{Xt.current&&(clearTimeout(Xt.current),Xt.current=null),_t.current="processing",E(!0),et(null)}),yr=ge.on("blocked",()=>{if(F.current){sr.current.updateError(Xd);return}if(!ps.current){zr(!0);return}Ha(),sr.current.updateError(Il)});return()=>{a&&(clearTimeout(a),a=null),Xt.current&&(clearTimeout(Xt.current),Xt.current=null),_t.current="idle",E(!1),et(null),j(),Be(),W(),st(),tt(),yr()}},[Le,ge,Ha,us]);let mr=!!ke?.clientId,To=Array.isArray(X),sa=To&&X.length>0,ec=To&&X.includes("paypal"),{expressMethods:la,paymentElementMethods:Ao}=Ft(()=>Fd(X,{excludePaypal:mr}),[X,mr]),ms=mr||!!$,tc=Ft(()=>ms?la.filter(a=>a!=="paypal"):la,[la,ms]),nc=Ft(()=>{let a=[];return Te&&a.push("apple_pay"),Fe&&a.push("google_pay"),a},[Te,Fe]),to=To?tc:nc,rc=G&&to.length>0,Ga=on?O:de,ca=Ft(()=>{let a=Ga?.trim().toUpperCase();return a?ce?Ao.filter(b=>{let j=ce[b];return!j||j.length===0||j.includes(a)}):Rd(Ao,Ga):Ao},[Ao,Ga,ce]),Ya=Ft(()=>({mode:"payment",amount:qn,currency:Zr,paymentMethodCreation:"manual",appearance:ss}),[qn,Zr,ss]),[ys,fs]=le("loading"),[gs,hs]=le("loading"),[vs,Ps]=le("loading"),[oc,Ja]=le(!1),[bs,Xa]=le("loading"),[Za,ac]=le();gt(()=>{ac(ba())},[]);let da=Za?.inAppBrowser,ua=Za?Ca(Za,ke?.approvalPresentation,B??(Ee?"subscription":"order")):"popup",Cs=S&&(mr||(To?ec:da===!1)),Ss=G&&rc,xo=(!Re||!!K.waitForDataAttachment)&&Cs&&mr,ws=bs==="retrying"||bs==="exhausted",Mo=!Re&&Cs&&!!tn&&(!mr||ws),no=!Re&&Ss&&!!ht,Bo=!Re&&G&&sa&&ca.length>0&&!!ht,ic=xo&&!ws?oc:Mo&&Tl(ys),sc=no&&Tl(gs),lc=Bo&&vs!=="load_error",Is=a=>a==="loading"||a==="ready",ks=xo||Mo&&Is(ys)||no&&Is(gs)||Bo&&vs!=="load_error",pa=me(!1);gt(()=>{if(!pa.current){if(!G&&!S){pa.current=!0;let a=new dr("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");l?.(a),he(a.message)}else if(!G&&S&&!mr&&!tn){pa.current=!0;let a=new dr("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");l?.(a),he(a.message)}else if(da!==void 0&&!Re&&!Wt&&!ks){pa.current=!0;let a=new dr("FloPay: this checkout session has no vault card capability and no usable supported non-card payment methods. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});l?.(a),he(a.message)}}},[G,S,mr,tn,da,Re,Wt,ks,l,he]);let _s=me(!1);gt(()=>{if(_s.current||!sa)return;let a=[];Te!==!0&&a.push("showApplePay"),Fe!==!0&&a.push("showGooglePay"),a.length!==0&&(_s.current=!0,console.warn(`[FloPay] ${a.join(" / ")} ${a.length===1?"is":"are"} deprecated: the Apple Pay / Google Pay surface is now driven by \`gateways.stripe.enabledPaymentMethods\` on the session response. Remove the legacy prop(s) to silence this warning.`))},[sa,Te,Fe]);let Rs=Ze((a,b)=>K.applyInlineSessionPatch?K.applyInlineSessionPatch(a).then(j=>({error:null,sessionId:j.sessionId||e,nonce:j.session?.clientSecret||t})).catch(j=>{let Be=El(b,j);return he(Be.message),l?.(Be),{error:Be,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[K.applyInlineSessionPatch,t,l,e,he]),lr=Ze(async a=>{if(a!=="card"&&Re&&await K.waitForDataAttachment?.(),!Ie)return{proceed:!0};try{let b=await Ie({method:a,sessionId:e||void 0,createSession:K.inlineSessionDraft});if(b===!1)return{proceed:!1};if(b&&typeof b=="object"){b.account&&mt(Be=>({...Be??{},...b.account}));let j=await Rs(b,a);return j.error?{proceed:!1,accountPatch:b.account}:{proceed:!0,accountPatch:b.account,sessionId:j.sessionId,nonce:j.nonce}}return{proceed:!0}}catch(b){let j=El(a,b);return he(j.message),l?.(j),{proceed:!1}}},[Rs,K.inlineSessionDraft,K.waitForDataAttachment,Re,Ie,l,e,he]),Es=Ze(async(a,b)=>{if(Jn.current)return;Jn.current=!0,Et(!0),et("processing"),he(null);let j=b?.sessionId??e,Be=b?.nonce??t,W=ui(y,b?.accountPatch),st=b?.completionPaymentMethodId??Ko(a),tt=a.originalPaymentMethodId?{...a,originalPaymentMethodId:void 0}:a,yr=ru(a),Xe=()=>{ie?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"process_payment",provider:yr})};try{let ft=await new wo(ne).processPayment(W.userId??"",{sessionId:j,nonce:Be,paymentMethodCategory:b?.paymentMethodCategory??au(a),tokenizedData:tt,accountData:{...b?.accountPatch,userId:W.userId??"",email:W.email??"",firstName:W.firstName||void 0,lastName:W.lastName||void 0,...te?(()=>{let vt=zt.current,Zn=rt(te.state,vt),kn=rt(te.address_line_1,vt),Zt=rt(te.postal_code,vt),Kr=kn&&!Zn&&Zt?vl(vt,(Tt.current??"").trim()):null,zo=Zn?Sn.current:Kr;return{country:vt,...Zt&&Tt.current?{zip:Tt.current}:{},...rt(te.city,vt)&&At.current?{city:At.current}:{},...zo?{state:zo}:{},...kn&&yn.current?{addressLine1:yn.current}:{},...rt(te.address_line_2,vt)&&Ut.current?{addressLine2:Ut.current}:{}}})():{}},chv:m,avsCheck:Q??!1,checkoutType:L,checkoutLayout:Ae,avsConfig:te?{country:rt(te.country,zt.current),postal_code:rt(te.postal_code,zt.current),address_line_1:rt(te.address_line_1,zt.current),address_line_2:rt(te.address_line_2,zt.current),city:rt(te.city,zt.current),state:rt(te.state,zt.current)}:void 0});if(ft.ok){let vt=ft.status===204?null:await ft.json().catch(()=>null),Zn=Bi(ee)||vt?.status==="authorized";bo(j),et("success"),it(null),await new Promise(Kr=>setTimeout(Kr,600));let kn;typeof vt?.paymentId=="string"?kn=vt.paymentId:ee?.paymentId&&(kn=ee.paymentId);let Zt;typeof vt?.authorizationExpiresAt=="string"?Zt=vt.authorizationExpiresAt:ee?.authorizationExpiresAt&&(Zt=ee.authorizationExpiresAt),s?.(Zn?{status:"authorized",...kn===void 0?{}:{paymentId:kn},sessionId:typeof vt?.sessionId=="string"?vt.sessionId:j,...Zt===void 0?{}:{authorizationExpiresAt:Zt},paymentIntentId:a.threeDSecureActionResultTokenId,paymentMethodId:st,checkoutMethod:a.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:a.threeDSecureActionResultTokenId,paymentMethodId:st,checkoutMethod:a.isPaypal?"paypal":"card"});return}let nt=await ft.json().catch(()=>null);if(nt?.type==="paypal_redirect_required"){let vt=nt.threeDSecureToken,Zn=nt.paymentMethodId||a.id||"";if(!Je||!vt){et("error"),he("PayPal authorization required but no token provided.");return}try{let kn=$?.getRawProvider();if(!kn){he("PayPal is not available.");return}let Zt={return_url:window.location.href};Zn&&(Zt.payment_method=Zn);let{error:Kr}=await kn.confirmPayment({clientSecret:vt,confirmParams:Zt,redirect:"if_required"});if(Kr){et("error");let zo=Kr.message??"PayPal payment failed.";he(zo),pr("paypal",zo,{code:Kr.code})}}catch(kn){et("error"),he(kn instanceof Error?kn.message:"PayPal authorization failed.")}return}if(nt?.type==="paypal_direct_required"){let vt=nt.orderId;if(!vt){et("error"),he("PayPal retry required but no order id provided.");return}let Zn=R.current?.attempts??0;if(Zn>=2){et("error"),he("PayPal payment could not be completed after multiple attempts."),pr("paypal","paypal_direct_required retry limit exceeded");return}Ja(!1),Xa("loading"),it({orderId:vt,attempts:Zn+1}),et(null);return}_d(ft.status,nt)||Xe(),et("error");let Mn=nt?.message??"Payment failed. Please try again.";he(Mn),pr(a.isPaypal?"paypal":"card",Mn,{code:nt?.code??nt?.gatewayErrorCode,declineCode:nt?.declineCode??nt?.gatewayDeclineReason}),await new Promise(vt=>setTimeout(vt,400))}catch(Mt){Nl(Mt)||Xe(),et("error"),he(Mt instanceof Error?Mt.message:"An unexpected error occurred"),await new Promise(ft=>setTimeout(ft,400))}finally{Et(!1),et(null),Jn.current=!1}},[ne,e,t,y,te,Q,L,Ae,m,Je,$,ee,s,he,pr,ie]),An=Ze((a,b)=>{f?f(a):Es(a,b)},[f,Es]),Fo=`${Fl}:${e}`;gt(()=>{if(typeof window>"u")return;let a=localStorage.getItem(Fo);if(!a)return;let b;try{b=JSON.parse(a)}catch{localStorage.removeItem(Fo);return}if(!b||typeof b.createdAt!="number"||Date.now()-b.createdAt<0||Date.now()-b.createdAt>Dl||typeof b.paymentMethodId!="string"||typeof b.providerIntentId!="string"||typeof b.paymentMethodType!="string"||b.sessionId!==e||!t||b.nonce!==t||!to.includes(b.paymentMethodType)){localStorage.removeItem(Fo);return}localStorage.removeItem(Fo),An({id:b.paymentMethodId,type:"card",threeDSecureActionResultTokenId:b.providerIntentId,gateway:"stripe",paymentMethodType:b.paymentMethodType},{...b.accountPatch?{accountPatch:b.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t})},[An,t,e,Fo,to]);let Ts=me(!1);gt(()=>{if(typeof window>"u"||Ts.current)return;let a=new URLSearchParams(window.location.search),b=a.get("payment_intent"),j=a.get("payment_intent_client_secret"),Be=a.get("redirect_status");if(!b||!j||!Je)return;let W=Je.getRawProvider();if(!W)return;let st=nt=>{let Mn=localStorage.getItem(nt);if(!Mn)return null;try{return JSON.parse(Mn)}catch{return localStorage.removeItem(nt),null}},tt=st(hr)??st(Cl),yr;if(tt?.clientSecret){if(tt.clientSecret!==j)return;yr={...tt.accountPatch?{accountPatch:tt.accountPatch}:{},...tt.sessionId?{sessionId:tt.sessionId}:{},...tt.nonce?{nonce:tt.nonce}:{}}}else if(tt?.sessionId&&tt.sessionId!==e)return;Ts.current=!0,localStorage.removeItem(hr),localStorage.removeItem(Cl);let Xe=new URL(window.location.href);Xe.searchParams.delete("payment_intent"),Xe.searchParams.delete("payment_intent_client_secret"),Xe.searchParams.delete("redirect_status"),window.history.replaceState({},"",Xe.toString());let Mt=tt?.paymentMethodType??tt?.tokenType??"card",ft="card";(async()=>{if(Be==="failed"){let Zt="Payment was declined. Please try again.";he(Zt),pr(ft,Zt);return}let{paymentIntent:nt,error:Mn}=await W.retrievePaymentIntent(j);if(Mn){let Zt=Mn.message??"Failed to retrieve payment status.";he(Zt),pr(ft,Zt,{code:Mn.code});return}let vt=nt?.status,Zn=$o(vt);if(!nt||!Zn){let Zt=vt==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";he(Zt),pr(ft,Zt,{code:vt??"missing_payment_intent"});return}let kn=typeof nt.payment_method=="string"?nt.payment_method:nt.payment_method?.id;An({id:kn??tt?.paymentMethodId??tt?.tokenId??nt.id,type:"card",threeDSecureActionResultTokenId:nt.id,gateway:tt?.gateway??"stripe",paymentMethodType:Mt},yr)})()},[e,An,Je,he,pr]);let Qa=Ze(a=>{a.preventDefault()},[]);if(!(Le||Je!==null))return c("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let Do=ve==="buttons",xn=q?.variables,cc=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),ei=xn?.colorBackground,dc=ei&&!cc.has(ei)?ei:void 0,No=v.cardInputBorder??(Do?"#e5e7eb":"#A4A4FF"),As=xn?.colorDanger??"#dc2626",qt=a=>Pr[a]&&(ar[a]||rr),ma=Ge&&(Er||rr),Xn=a=>a?As:No,ya=(sn.malformed||sn.empty)&&(Ur||rr),uc=Xn(ya),ti=v.cardFormContainer?.backgroundColor??dc??(Do?"white":"#EDEDFF"),ro=v.cardInputBackground??xn?.colorBackground??"white",ni=io(ye),xs=io(we),oo=v.nameInput,Ms=v.cardInputFontSize??uu(oo?.fontSize)??xn?.fontSizeBase??"16px",Bs=typeof oo?.fontFamily=="string"?oo.fontFamily:xn?.fontFamily??"Poppins, sans-serif",Fs=zs(oo?.fontWeight)??400,pc=v.cardInputColor??(typeof oo?.color=="string"?oo.color:void 0)??xn?.colorText??"#262833",mc=v.cardInputPlaceholderColor??"#9ca3af",Vt=xn?.borderRadius??"8px",jr=xn?.borderRadius??v.cardButton?.borderRadius??Vt,$r=xn?.colorPrimary??"#4A49FF",yc=xn?.colorPrimaryHover??qo($r,.12),ri=xn?.colorText??"#262833",oi={fontSize:Ms,fontFamily:Bs,fontWeight:Fs,color:pc,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},Lo={marginTop:"0.375rem",...oi,fontSize:"0.75rem",lineHeight:1.4,color:As},fc={"--flopay-input-placeholder-color":mc,"--flopay-input-font-size":Ms,"--flopay-input-font-family":Bs,"--flopay-input-font-weight":String(Fs)},Oo=v.cardFormContainer??{},ai=Oo.padding??(Do?"0":"1rem"),ii=Oo.borderRadius??Vt,gc=ge&&ir?c(si,{capture:ge,html:ir.html,messageToken:ir.messageToken,expectedOrigin:ir.expectedOrigin,theme:Ve,submitLabel:_,onReady:()=>{if(!Se&&!te||typeof document>"u")return;let a=()=>{let j=(document.querySelector('[data-testid="flopay-vault-identity-fields"]')??document.querySelector('[data-testid="flopay-avs-fields"]'))?.querySelector("input:not([disabled]), select:not([disabled])");if(j){Ln.current=!0;try{j.focus()}finally{Ln.current=!1}}};Gn.current||a()},onError:a=>he(a),onValidation:a=>{let b=_t.current;(b==="idle"||b==="validation-window")&&(he(a),a&&_t.current==="validation-window"&&(Xt.current&&(clearTimeout(Xt.current),Xt.current=null),_t.current="idle",et(null)))}}):c("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"}),Ds=ze("div",{onFocusCapture:a=>{["INPUT","SELECT","TEXTAREA","IFRAME"].includes(a.target.tagName)&&Cr()},style:{backgroundColor:ti,borderRadius:ii,...Oo,padding:ai,...fc,display:"flex",flexDirection:"column"},children:[c("style",{children:`
|
|
25
|
+
`,Ya=44,da=180,zl=`flopay-card-enter ${da}ms cubic-bezier(0, 0, 0.2, 1) both`,Ul=`flopay-card-exit ${da}ms cubic-bezier(0.4, 0, 0.2, 1) both`,yu=`flopay-buttons-enter ${da}ms cubic-bezier(0, 0, 0.2, 1) both`,mu=`flopay-buttons-exit ${da}ms cubic-bezier(0.4, 0, 0.2, 1) both`;function fu(e){return e.gateway==="stripe"?"stripe":e.gateway==="paypal"||e.isPaypal?"paypal":void 0}function is(e){if(!e.themeBundle&&!e.explicitPrimaryColor)return{backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:e.resolvedBorderRadius,boxShadow:"0 1px 2px rgba(0,0,0,0.04)"};let t=e.themeBundle?e.submitButtonStyle??{}:{};return{backgroundColor:e.resolvedPrimaryColor,color:t.color??"white",border:t.border??"none",borderRadius:t.borderRadius??e.resolvedBorderRadius,boxShadow:t.boxShadow}}var gu={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"};function hu(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 Qi={width:"100%",minHeight:Ya,margin:"0 0 0.5rem",padding:"0.75rem 0.875rem",border:"1px solid #2563eb",borderRadius:8,background:"#eff6ff",color:"#1d4ed8",fontSize:"0.95rem",fontWeight:700,cursor:"pointer"};function vu(e){switch(e){case"paypal":return"PayPal";case"apple_pay":return"Apple Pay";case"google_pay":return"Google Pay";default:return"Card"}}function ql(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function es(e){return e==="paypal"?"PayPal":eo(e)}function bu(e){let t=Ud(e);return`Enter a valid ${Zi(e)}${t?` (e.g. ${t})`:""}`}function Pu(e,t,n){let r=$d(e),o=t.trim(),i=n&&r,s=i&&!o,l=i&&!!o&&!Kd(e,o);return{visible:n,supported:r,required:i,empty:s,malformed:l}}function Cu(e,t){let n=e.trim(),r=t&&!n,o=t&&!!n&&!fn(n);return{required:t,empty:r,malformed:o,value:n}}function jl(e,t){return t instanceof pr?t:new pr(t instanceof Error?t.message:`${vu(e)} before-click hook failed.`,"validation_error")}function Xi(){return d("style",{children:pu})}function wu(e){return typeof e=="number"?`${e}px`:e}function Zl(e,t){let n=e.availablePaymentMethods;return n&&t.some(r=>n[r])?"ready":"unavailable"}function Ql({state:e,placeholderTestId:t,borderRadius:n=8,children:r}){return e==="unavailable"||e==="load_error"?null:Oe("div",{style:{position:"relative",minHeight:44},children:[d("div",{"data-testid":t,"aria-hidden":e==="ready",style:{position:"absolute",inset:0,height:44,borderRadius:n,background:"#e5e7eb",animation:e==="ready"?void 0:"flopay-pulse 1.5s ease-in-out infinite",opacity:e==="ready"?0:1,transform:e==="ready"?"scale(0.985)":"scale(1)",transition:"opacity 140ms ease-out, transform 140ms ease-out",pointerEvents:"none"}}),d("div",{style:{minHeight:44,opacity:e==="ready"?1:0,transform:e==="ready"?"translateY(0)":"translateY(2px)",transition:"opacity 140ms ease-out, transform 140ms ease-out",pointerEvents:e==="ready"?"auto":"none"},children:r})]})}function $l(e){return e!=="unavailable"&&e!=="load_error"}function ss(e){return d(ku,{...e})}function Kl({sessionId:e,nonce:t,email:n,billingApiUrl:r,onTokenizedBody:o,onErrorChange:i,isProcessing:s=!1,onButtonClick:l,onDecline:y,onTechnicalFailure:f,runBeforeButtonClick:b,billingName:g,onBuyerIdentityReady:M,onLoadStateChange:R,placeholderBorderRadius:C,popupCapabilityOwner:v,externalTelemetryContext:q}){let Re=Or(),{emitInstrument:I}=To(or),G=rs(),Y=ns(),re=Et(()=>$i(mn(Re),q),[q,Re]),[ve,Le]=ce("loading");Ct(()=>{R?.(ve)},[ve,R]);let[Ce,$e]=ce(!1),vt=!fn(n?.trim())||!g?.trim(),{request:Ke,collect:Ne,finish:Me}=ho(),wt=de(!1),fe=de(null),ut=de(null),[O,Ae]=ce(0),[yt,Be]=ce(!1),it=de(!1),N=de(new Map),{startAttempt:ue,finishAttempt:ge,invalidateAttempt:K,isAttemptInvalidated:Ge,isAttemptCurrent:Ve,generationRef:L}=na((Q,oe,Fe)=>{f?.(Q,oe,{...Fe,popupBlocked:Fe?.popupBlocked??Dr(oe),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:"popup",terminalReason:"overlay_timeout"}),Be(!0),Ae(Je=>Je+1)},{onHandoffObserved:()=>{v.markAvailable(),re?.log({name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal",attempt:L.current})}});Ct(()=>{yt&&ut.current?.focus()},[yt,O]);let st=tt(()=>{Ae(Q=>Q+1)},[]),Ye=tt((Q,oe,Fe)=>{K(Fe),f?.("paypal",Q,{code:oe,popupBlocked:Dr(Q),provider:"stripe",paymentMethodCategory:"paypal",presentationMode:"popup"}),Be(!0),st()},[K,f,st]),He=tt(()=>{window.setTimeout(()=>{(fe.current?.querySelector("iframe")??fe.current)?.focus()},0)},[]);Ct(()=>{it.current&&(it.current=!1,He())},[He,O]);let Ee=tt(()=>{Be(!1),i?.(null),He()},[He,i]);Ct(()=>{if(!G||wt.current)return;let Q=new URLSearchParams(window.location.search),oe=Q.get("payment_intent"),Fe=Q.get("payment_intent_client_secret"),Je=Q.get("redirect_status");if(!oe||!Fe)return;wt.current=!0;let lt;try{let pt=localStorage.getItem(ca);if(pt){let Xe=JSON.parse(pt);Xe.clientSecret===Fe&&(lt={...Xe.accountPatch?{accountPatch:Xe.accountPatch}:{},...Xe.sessionId?{sessionId:Xe.sessionId}:{},...Xe.nonce?{nonce:Xe.nonce}:{}})}}catch{}try{localStorage.removeItem(ca)}catch{}let z=new URL(window.location.href);z.searchParams.delete("payment_intent"),z.searchParams.delete("payment_intent_client_secret"),z.searchParams.delete("redirect_status"),window.history.replaceState({},"",z.toString()),(async()=>{try{if($e(!0),Je==="failed"){let _="PayPal payment was declined. Please try again.";i?.(_),y?.(dn("paypal",_));return}let{paymentIntent:pt,error:Xe}=await G.retrievePaymentIntent(Fe);if(Xe){i?.(Xe.message??"Failed to retrieve PayPal payment status.");return}if(pt&&(pt.status==="requires_capture"||pt.status==="succeeded")){let _=typeof pt.payment_method=="string"?pt.payment_method:pt.payment_method?.id;o({id:_??pt.id,type:"card",threeDSecureActionResultTokenId:pt.id,isPaypal:!0},lt)}else{let _="PayPal payment was not completed. Please try again.";i?.(_),y?.(dn("paypal",_))}}catch(pt){i?.(pt instanceof Error?pt.message:"Failed to complete PayPal payment.")}finally{$e(!1)}})()},[G,o,i,y]);let le=tt(async Q=>{if(s||Ce){Q.reject();return}let oe=b?await b("paypal"):{proceed:!0};if(!oe.proceed){N.current.delete(O),Q.reject();return}let Fe=ue("paypal");N.current.set(O,{generation:Fe,accountPatch:oe.accountPatch,sessionId:oe.sessionId,nonce:oe.nonce}),Be(!1),re?.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal",attempt:Fe}),l?.("paypal"),Q.resolve()},[s,l,re,b,ue,Ce,O]),mt=tt(async Q=>{if(!G||!Y)return;let oe=N.current.get(O);if(oe&&!Ve(oe.generation)){N.current.delete(O);return}if(!oe&&Ge()||oe&&!ge(oe.generation))return;oe||ge();let Fe=oe??null;if(N.current.delete(O),!Fe&&b){let _=await b("paypal");if(!_.proceed){Q.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}Fe={accountPatch:_.accountPatch,sessionId:_.sessionId,nonce:_.nonce}}let Je=Fe?.sessionId??e,lt=Fe?.nonce??t,z=await uu({event:Q,prepared:Fe,email:n,billingName:g,methodLabel:"PayPal",collect:Ne});if(!z){Q.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let pt=z.email,Xe={...Fe?.accountPatch,...On(z,!0)};try{if($e(!0),i?.(null),!Je||!fn(pt))throw new Error("Missing sessionId or email for PayPal payment");await M?.(z);let _=G.createPaymentMethod,{error:ct,paymentMethod:Jt}=await _({type:"paypal"});if(ct){Ye(ct,"stripe_paypal_create_payment_method_failed",oe?.generation),Q.paymentFailed({reason:"fail"});return}let xe=await Ja(r,I,Je,lt??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:Jt?.id??null,intentKind:"payment"});if(xe.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let un=xe.clientSecret,c={return_url:window.location.href};if(Jt?.id&&(c.payment_method=Jt.id),typeof window<"u")try{localStorage.setItem(ca,JSON.stringify({clientSecret:un,sessionId:Je,nonce:lt,accountPatch:Xe}))}catch{}let{error:w,paymentIntent:ne}=await G.confirmPayment({clientSecret:un,confirmParams:c,redirect:"if_required"});if(w){if(typeof window<"u")try{localStorage.removeItem(ca)}catch{}if(Zo(w)){let $=w.message??"Your payment was declined.";i?.($),y?.(dn("paypal",$,{code:Sr(w),declineCode:bo(w)})),await Xa({billingApiUrl:r,sessionId:Je,nonce:lt,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:Sr(w)??"provider_declined"}})}else Ye(w,"stripe_paypal_confirm_failed",oe?.generation);return}if(typeof window<"u")try{localStorage.removeItem(ca)}catch{}let k=typeof ne?.payment_method=="string"?ne.payment_method:ne?.payment_method?.id;o({id:k??ne?.id,type:"card",threeDSecureActionResultTokenId:ne?.id,isPaypal:!0},{accountPatch:Xe,paymentMethodCategory:"paypal",sessionId:Je,nonce:lt});return}catch(_){Ye(_,"stripe_paypal_failed",oe?.generation)}finally{$e(!1)}},[G,Y,e,t,n,g,Ne,M,r,I,o,i,y,b,Ye,ge,Ve,Ge,O]);return Oe(Qr,{children:[d(Ql,{state:ve,placeholderTestId:"flopay-paypal-placeholder",borderRadius:C,children:Oe("div",{ref:fe,tabIndex:-1,"data-testid":"flopay-paypal-focus-target",role:"group","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[yt&&d("button",{ref:ut,type:"button","data-testid":"flopay-paypal-retry-button",onClick:Ee,style:Qi,children:"Try PayPal again"}),Ke&&d(vo,{identity:Ke.identity,methodLabel:Ke.methodLabel,onComplete:Me,onCancel:()=>Me(null)},Ke.id),d("div",{style:{display:Ke?"none":void 0},children:d(Wl,{onReady:Q=>Le(Zl(Q,["paypal"])),onLoadError:()=>{Le("load_error"),as(re,"paypal","paypal","provider_error")},onClick:le,onConfirm:mt,onCancel:()=>{let Q=N.current.get(O);N.current.delete(O),re?.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"cancelled",...Q?{attempt:Q.generation}:{}}),K(Q?.generation),Be(!1),it.current=!0,st()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:vt,emailRequired:vt,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},O)})]})}),Ce&&d(wr,{status:"processing"})]})}function Vl({sessionId:e,nonce:t,email:n,billingApiUrl:r,intentKind:o,expressMethods:i,onTokenizedBody:s,onErrorChange:l,onButtonClick:y,onDecline:f,onTechnicalFailure:b,runBeforeButtonClick:g,billingName:M,onBuyerIdentityReady:R,onLoadStateChange:C,placeholderBorderRadius:v,popupCapabilityOwner:q,externalTelemetryContext:Re}){let I=Or(),{emitInstrument:G}=To(or),Y=rs(),re=ns(),ve=Et(()=>$i(mn(I),Re),[Re,I]),[Le,Ce]=ce("loading");Ct(()=>{C?.(Le)},[Le,C]);let[$e,vt]=ce(!1),Ke=de(!fn(n?.trim())||!M?.trim()).current,{request:Ne,collect:Me,finish:wt}=ho(),fe=de(null),ut=de(null),[O,Ae]=ce(0),[yt,Be]=ce(!1),[it,N]=ce(()=>Ga(e,t)?"blocked":"idle"),[ue,ge]=ce("google_pay"),K=de(null),Ge=de(!0),Ve=de(!1),L=de("google_pay"),st=de("google_pay"),Ye=de(null),He=de(null),Ee=de(new Set);Ct(()=>(Ge.current=!0,()=>{Ge.current=!1;for(let c of Ee.current)window.clearTimeout(c);Ee.current.clear()}),[]);let le=de(new Map),{startAttempt:mt,finishAttempt:Q,invalidateAttempt:oe,isAttemptInvalidated:Fe,isAttemptCurrent:Je,generationRef:lt}=na((c,w,ne)=>{b?.(c,w,{...ne,popupBlocked:ne?.popupBlocked??Dr(w),provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup",terminalReason:"overlay_timeout"}),ge(c),Be(!0),Ae(k=>k+1)},{onHandoffObserved:c=>{q.markAvailable(),ve?.log({name:"provider.popup.opened",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:lt.current,...c==="apple_pay"||c==="google_pay"?{walletType:c}:{}})}});Ct(()=>{yt&&ut.current?.focus()},[yt,O]);let z=tt(()=>{Ae(c=>c+1)},[]),pt=tt((c,w,ne,k,$=!1)=>{oe(k),b?.(c,w,{code:ne,popupBlocked:Dr(w),telemetryReported:$,provider:"stripe",paymentMethodCategory:"wallet",presentationMode:"popup"}),ge(c),Be(!0),z()},[oe,b,z]),Xe=tt(()=>{window.setTimeout(()=>{(fe.current?.querySelector("iframe")??fe.current)?.focus()},0)},[]);Ct(()=>{Ve.current&&(Ve.current=!1,Xe())},[Xe,O]);let _=tt(()=>{Be(!1),l?.(null),Xe()},[Xe,l]),ct=tt(()=>{K.current?.()},[]);Ct(()=>{let c=Ga(e,t);if(!c)return;let w=!1,ne=!1,k=async()=>{if(!ne){ne=!0,w||N("checking");try{let $=await Nl(Y,c.clientSecret,Ee.current);if(w)return;let ft=Yi($,c.providerObjectId,Hi(c.clientSecret));if(ft.kind==="confirmed"){if(!Ol(e,t,c.clientSecret))return;K.current=null,N("idle"),s({id:ft.paymentMethodId,type:"card",threeDSecureActionResultTokenId:ft.intentId},{...c.accountPatch?{accountPatch:c.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t});return}if(ft.kind==="terminal"){Gi(e,t,c.clientSecret),K.current=null,N("idle"),ge(c.paymentMethodType),Be(!0),z();return}N("blocked")}catch{w||N("blocked")}finally{ne=!1}}};return K.current=k,N("blocked"),()=>{w=!0,K.current===k&&(K.current=null)}},[t,s,z,e,Y]);let Jt=tt(async c=>{let w=!1,ne=De=>{w||(w=!0,c.paymentFailed({reason:"fail",...De?{message:De}:{}}))};if(!Y||!re){ne();return}let k=le.current.get(O);if(k&&!Je(k.generation)){le.current.delete(O),ne();return}if(!k&&Fe()){ne();return}if(k&&!Q(k.generation)){ne();return}k||Q();let $=c.expressPaymentType??k?.method??L.current,ft=k??null,ze=ql($),Ue;$==="apple_pay"?Ue="apple_pay":$==="google_pay"&&(Ue="google_pay");let xt=k?.generation??lt.current,ee=ve,pn=ee?.now()??globalThis.performance?.now()??Date.now(),We=new AbortController,Dt=!1,Rn=!1,Kt=null,Te=e,Ut="processing",gn="other",hn="provider_runtime",kn,Nn=new Promise((De,we)=>{kn=we}),vn=window.setTimeout(()=>{Dt=!0,We.abort(),kn(Ha)},nu),Vt=async(De,we,Ln)=>{Ut=De,gn=we,hn=we==="intent_create"||we==="session_claim"?"transport_error":"provider_runtime";let St=ee?.now()??globalThis.performance?.now()??Date.now();try{return await Promise.race([Ln,Nn])}finally{let bn=ee?.now()??globalThis.performance?.now()??Date.now();ee?.performance({stage:De,durationMs:Math.max(0,bn-St),durationMode:"machine",requestCategory:we,paymentMethodCategory:"wallet",provider:"stripe",...Dt?{statusClass:"timeout"}:{}})}};try{if(vt(!0),l?.(null),!ft&&g){let A=await Vt("processing","other",g(ze));if(!A.proceed){ne();return}ft={accountPatch:A.accountPatch,sessionId:A.sessionId,nonce:A.nonce}}let De=ft?.sessionId??e;Te=De;let we=ft?.nonce??t,Ln=Ye.current??ft?.accountPatch,St=Xl({event:c,fallbackEmail:Ln?.email??n,fallbackName:[Ln?.firstName,Ln?.lastName].join(" ").trim()||M});if(!fn(St.email)){ne("Buyer details are required."),Me(es($),St).then(A=>{A&&(Ye.current=A)});return}Ye.current=null;let bn={...ft?.accountPatch,...On(St,!0)};await Vt("processing","session_claim",Promise.resolve(R?.(St)));let{error:En}=await Vt("tokenization","provider_sdk",re.submit());if(En){ne(),pt($,En,"stripe_wallet_submit_failed",k?.generation);return}if(!De)throw new Error("Missing sessionId or email for payment.");let Hn={provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:$,paymentMethodId:null,intentKind:o},Ht=JSON.stringify({sessionId:De,nonce:we??"",request:Hn}),Xt=He.current,ln=Xt?.retryIdentity===Ht?Xt.authorizationAttemptId:Wd();He.current={authorizationAttemptId:ln,retryIdentity:Ht};let kt=await Vt("processing","intent_create",Ja(r,G,De,we??"",{...Hn,authorizationAttemptId:ln},{signal:We.signal}));if(kt.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Mt=kt.clientSecret,yn=au({createdAt:Date.now(),sessionId:De,...we?{nonce:we}:{},clientSecret:Mt,providerObjectId:kt.providerObjectId,paymentMethodType:$,accountPatch:bn});window.clearTimeout(vn),Rn=!0,ee?.performance({stage:"callback",durationMs:Math.max(0,(ee?.now()??globalThis.performance?.now()??Date.now())-pn),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe"});let Zt=ee?.now()??globalThis.performance?.now()??Date.now(),qt={stage:"provider_confirmation",provider:"stripe",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",...Ue?{walletType:Ue}:{},attempt:xt},Wt=!1,Tt=null;ee?.log({name:"payment.provider_confirmation.started",...qt}),Kt=window.setTimeout(()=>{Kt!==null&&Ee.current.delete(Kt),Wt=!0;let A=ee?.now()??globalThis.performance?.now()??Date.now();ee?.error({errorCode:"PROVIDER_RUNTIME_FAILED",...qt,operationOutcome:"watchdog_expired",durationMs:Math.max(0,A-Zt),statusClass:"timeout",failureCategory:"provider_runtime",terminalReason:"provider_error"}),ee?.flush?.().catch(()=>{}),Tt?.()},ru),Ee.current.add(Kt);let X=(A,gt)=>{Kt!==null&&(window.clearTimeout(Kt),Ee.current.delete(Kt),Kt=null);let Ze=ee?.now()??globalThis.performance?.now()??Date.now(),x=Math.max(0,Ze-Zt),qe=A;Wt&&(A==="resolved"?qe="resolved_late":A==="returned_error"?qe="returned_error_late":qe="rejected_late");let te=gt??(A==="resolved"?"approved":"provider_error");return ee?.log({name:"payment.provider_confirmation.returned",...qt,operationOutcome:qe,terminalReason:te}),ee?.performance({...qt,durationMs:x,durationMode:"buyer",operationOutcome:qe,terminalReason:te}),{durationMs:x,operationOutcome:qe,terminalReason:te}},Qt=!1,en=!1,ir=A=>{if(!A||typeof A!="object")return null;let gt=A;if(gt.error)return null;let Ze=gt.setupIntent??gt.paymentIntent,x=Yi(Ze??null,void 0,!!gt.setupIntent);return x.kind==="confirmed"?x:null},mr=A=>{if(Qt||k&<.current!==k.generation)return;let gt=ir(A);if(!gt)return;if(yn&&!Ol(De,we,Mt)){Qt=!0;return}let{intentId:Ze,paymentMethodId:x}=gt;Qt=!0,en=!0,He.current=null,K.current=null,Ge.current&&(N("idle"),vt(!1));let qe=`${Gl}:${De}`;if(typeof window<"u")try{localStorage.setItem(qe,JSON.stringify({createdAt:Date.now(),sessionId:De,nonce:we,accountPatch:bn,paymentMethodId:x,providerIntentId:Ze,paymentMethodType:$}))}catch{}try{s({id:x,type:"card",threeDSecureActionResultTokenId:Ze},{accountPatch:bn,paymentMethodCategory:"wallet",sessionId:De,nonce:we})}finally{if(typeof window<"u")try{localStorage.removeItem(qe)}catch{}}},Wn=!1;Tt=async()=>{if(!(Wn||Qt||en)){Wn=!0,Ge.current&&N("checking");try{let A=await Nl(Y,Mt,Ee.current);if(Qt||en)return;let gt=Hi(Mt),Ze=Yi(A,kt.providerObjectId,gt);if(Ze.kind==="confirmed"){mr(gt?{setupIntent:A}:{paymentIntent:A});return}if(Ze.kind==="terminal"){if(en=!0,Gi(De,we,Mt),He.current=null,K.current=null,!Ge.current)return;N("idle"),ne(),pt($,new Error("Wallet confirmation did not complete."),"stripe_wallet_confirmation_terminal",k?.generation,!0);return}Ge.current&&!en&&(N("blocked"),vt(!1))}catch{Ge.current&&!en&&(N("blocked"),vt(!1))}finally{Wn=!1}}},K.current=Tt;let Gt,sr;try{let A=await(Hi(Mt)?Y.confirmSetup({elements:re,clientSecret:Mt,redirect:"if_required"}):Y.confirmPayment({elements:re,clientSecret:Mt,redirect:"if_required"}));if(!A||typeof A!="object"||(Gt=A,!Gt.error&&!ir(Gt)))throw Wi;sr=X(Gt.error?"returned_error":"resolved",Gt.error&&Zo(Gt.error)?"provider_declined":void 0)}catch(A){let gt=A===Wi,Ze=X(gt?"returned_error":"rejected");if(ee?.error({...gt?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response"}:ki(A),...qt,operationOutcome:Ze.operationOutcome,durationMs:Ze.durationMs,statusClass:"unknown",terminalReason:Ze.terminalReason}),!Ge.current||Qt)return;await Tt?.();return}let jt=Gt.error;if(jt){if(!Ge.current||Qt)return;if(Zo(jt)){en=!0,Gi(De,we,Mt),He.current=null,K.current=null,N("idle");let A=jt.message??"Your payment was declined.";ne(A),l?.(A),f?.(dn(ze,A,{code:Sr(jt),declineCode:bo(jt)})),Xa({billingApiUrl:r,sessionId:De,nonce:we,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:$,providerDeclineReason:Sr(jt)??"provider_declined",...kt.intentKind==="payment"&&kt.providerObjectId.startsWith("pi_")?{providerIntentId:kt.providerObjectId}:{}}})}else ee?.error({...ki(jt),...qt,operationOutcome:sr.operationOutcome,durationMs:sr.durationMs,statusClass:"unknown",terminalReason:sr.terminalReason}),await Tt?.();return}if(mr(Gt),!Qt)throw new Error("Invalid provider returned for APM intent")}catch(De){if(De===Ha){let we=ee?.now()??globalThis.performance?.now()??Date.now();ee?.error({errorCode:su(gn),stage:Ut,requestCategory:gn,paymentMethodCategory:"wallet",provider:"stripe",...Ue?{walletType:Ue}:{},operationOutcome:"watchdog_expired",checkoutSessionId:Te,durationMs:Math.max(0,we-pn),statusClass:"timeout",failureCategory:hn,attempt:xt,terminalReason:"provider_error"}),ee?.flush?.().catch(()=>{})}ne(),pt($,De,De===Ha?"stripe_wallet_authorization_timeout":"stripe_wallet_failed",k?.generation,De===Ha)}finally{if(window.clearTimeout(vn),Kt!==null&&(window.clearTimeout(Kt),Ee.current.delete(Kt)),!Rn){let De=ee?.now()??globalThis.performance?.now()??Date.now();ee?.performance({stage:"callback",durationMs:Math.max(0,De-pn),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe",...Dt?{statusClass:"timeout"}:{}})}Ge.current&&vt(!1)}},[Y,re,e,t,n,M,Me,R,r,G,o,s,l,f,g,pt,Q,Je,Fe,lt,ve,O]),xe=Et(()=>{let c=["applePay","googlePay","paypal","link","amazonPay","klarna"],w=new Set(["applePay","googlePay"]),ne=new Set(i.map(Fl)),k={};for(let $ of c)ne.has($)?k[$]=w.has($)?"always":"auto":k[$]="never";return k},[i]),un=Et(()=>i.map(Fl),[i]);return Oe(Qr,{children:[d(Ql,{state:Le,placeholderTestId:"flopay-wallet-placeholder",borderRadius:v,children:Oe("div",{ref:fe,tabIndex:-1,"data-testid":"flopay-wallet-focus-target",role:"group","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[yt&&Oe("button",{ref:ut,type:"button","data-testid":"flopay-wallet-retry-button",onClick:_,style:Qi,children:["Try ",es(ue)," again"]}),it!=="idle"&&Oe("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:ct,disabled:it==="checking",style:Qi,children:it==="checking"?"Checking payment status\u2026":"Check payment status"})]}),Ne&&d(vo,{identity:Ne.identity,methodLabel:Ne.methodLabel,onComplete:wt,onCancel:()=>wt(null)},Ne.id),it==="idle"&&d("div",{style:{display:Ne?"none":void 0},children:d(Wl,{onReady:c=>{Ce(Zl(c,un))},onLoadError:c=>{Ce("load_error"),as(ve,"stripe","wallet","provider_error")},onClick:async c=>{L.current=c.expressPaymentType,st.current=ql(c.expressPaymentType);let w=!0,ne=window.setTimeout(()=>{w=!1,c.reject()},tu),k=g?await g(st.current):{proceed:!0};if(window.clearTimeout(ne),!w)return;if(!k.proceed){le.current.delete(O),c.reject();return}let $=mt(c.expressPaymentType);le.current.set(O,{generation:$,method:c.expressPaymentType,accountPatch:k.accountPatch,sessionId:k.sessionId,nonce:k.nonce}),Be(!1),ve?.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"stripe",paymentMethodCategory:"wallet",attempt:$,...c.expressPaymentType==="apple_pay"||c.expressPaymentType==="google_pay"?{walletType:c.expressPaymentType}:{}}),y?.(st.current),c.resolve()},onConfirm:Jt,onCancel:()=>{let c=le.current.get(O);le.current.delete(O),ve?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet",terminalReason:"cancelled",...c?{attempt:c.generation}:{}}),oe(c?.generation),He.current=null,Be(!1),Ve.current=!0,z()},options:{buttonType:{applePay:"plain",googlePay:"plain"},paymentMethods:xe,emailRequired:Ke,billingAddressRequired:Ke,layout:{maxColumns:1,overflow:"never"}}},O)})]})}),$e&&d(wr,{status:"processing"})]})}function ec(e,t){return{...e,paymentMethodTypes:[t],...t==="revolut_pay"||t==="sepa_debit"||t==="us_bank_account"?{setupFutureUsage:"off_session"}:null}}function Su({method:e,themeId:t,submitting:n=!1,disabled:r=!1,highlighted:o=!1,hasNextStep:i=!1,onClick:s,backgroundColor:l,borderColor:y,textColor:f,borderRadius:b,fontFamily:g}){let M=Jd(e,t),R=xl[e],[C,v]=ce(!1),q=!!R&&!C,Re=M?.backgroundColor??l??"#ffffff",I=M?.borderColor??y??"#d1d5db",G=M?.textColor??f??"#262833";return d("button",{type:"button","data-testid":`flopay-stripe-method-button-${e}`,"data-method":e,onClick:()=>{!n&&!r&&s()},disabled:n||r,"aria-busy":n||void 0,style:{position:"relative",width:"100%",boxSizing:"border-box",height:Ya,padding:"0 1rem",backgroundColor:Re,color:G,border:`1px solid ${I}`,borderRadius:b??8,fontSize:"0.95rem",fontWeight:600,fontFamily:g,cursor:n||r?"not-allowed":"pointer",opacity:r&&!n?.55:1,animation:n?"flopay-pulse 1.5s ease-in-out infinite":void 0,display:"flex",alignItems:"center",justifyContent:"center",gap:8,transition:"transform 0.1s, opacity 140ms ease-out, border-color 140ms ease-out",boxShadow:o?"0 0 0 2px rgba(74, 73, 255, 0.15)":void 0},children:n?d("span",{style:{margin:"0 auto"},children:`Connecting to ${eo(e)}\u2026`}):Oe(Qr,{children:[Oe("span",{style:{display:"inline-flex",alignItems:"center",gap:jd(e)?8:0},children:[q?d("img",{src:R,alt:"","aria-hidden":"true",onError:()=>v(!0),loading:"lazy",decoding:"async",width:30,height:20,style:{width:30,height:20,flexShrink:0,borderRadius:3,objectFit:"contain",display:"inline-flex"}}):null,!q&&M?.logoSvg?d("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:M.logoSvg}}):null,d("span",{children:eo(e)})]}),i&&d("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:G,strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{position:"absolute",right:"1rem",top:"50%",transform:"translateY(-50%)",flexShrink:0,opacity:.7},"aria-hidden":"true",children:d("path",{d:"M9 18l6-6-6-6"})})]})})}function ts({method:e,sessionId:t,nonce:n,email:r,billingName:o,onBuyerIdentityReady:i,billingApiUrl:s,onTokenizedBody:l,onErrorChange:y,onDecline:f,onCancel:b,runBeforeButtonClick:g,onButtonClick:M,isProcessing:R,submitButtonColor:C,submitButtonBorderRadius:v,submitButtonStyle:q,errorText:Re}){let I=Or(),{emitInstrument:G}=To(or),Y=rs(),re=ns(),[ve,Le]=ce(!1),Ce=de(!1),[$e,vt]=ce(!1),[Ke,Ne]=ce("loading"),[Me,wt]=ce(""),fe=!fn(r?.trim()),ut=!fe||fn(Me.trim()),O=tt(async()=>{if(!Y||!re||R||Ce.current||!$e)return;Ce.current=!0,Le(!0);let Ae=g?await g("card"):{proceed:!0};if(!Ae.proceed){Ce.current=!1,Le(!1);return}M?.("card");let yt=Ae.sessionId??t,Be=Ae.nonce??n,it=Yr(o?.trim()),N=On({email:Ae.accountPatch?.email?.trim()||r?.trim()||Me.trim(),firstName:Ae.accountPatch?.firstName?.trim()||it.firstName,lastName:Ae.accountPatch?.lastName?.trim()||it.lastName}),ue=N.email,ge=On({...Ae.accountPatch,...N});try{if(y?.(null),!fn(ue))throw new Error("A valid email address is required for payment.");await i?.(N);let K=await re.submit();if(K.error){y?.(K.error.message??"Payment failed.");return}let Ge=[N.firstName,N.lastName].filter(Boolean).join(" "),Ve=await Y.createPaymentMethod({elements:re,params:{billing_details:{email:ue,...Ge?{name:Ge}:{}}}});if(Ve.error||!Ve.paymentMethod){y?.(Ve.error?.message??"Failed to create payment method.");return}let L=Ve.paymentMethod;if(!yt||!ue)throw new Error("Missing sessionId or email for payment.");let st=L.type||e,Ye=await Ja(s,G,yt,Be??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:st,paymentMethodId:null,intentKind:"payment"});if(Ye.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let He=Ye.clientSecret;if(typeof window<"u")try{localStorage.setItem(_r,JSON.stringify({clientSecret:He,sessionId:yt,nonce:Be,accountPatch:ge,paymentMethodId:L.id,paymentMethodType:L.type??e,gateway:"stripe"}))}catch{}let{error:Ee,paymentIntent:le}=await Y.confirmPayment({clientSecret:He,confirmParams:{return_url:window.location.href,payment_method:L.id},redirect:"if_required"});if(Ee){if(typeof window<"u")try{localStorage.removeItem(_r)}catch{}let oe=Ee.message??"Payment failed.";y?.(oe),f?.(dn("card",oe,{code:Ee.code})),await Xa({billingApiUrl:s,sessionId:yt,nonce:Be,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:Ee.code??"provider_declined"}});return}let mt=le?.status;if(!Yo(mt)){if(typeof window<"u")try{localStorage.removeItem(_r)}catch{}let oe=mt==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";y?.(oe),f?.(dn("card",oe,{code:mt??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(_r)}catch{}let Q=typeof le?.payment_method=="string"?le.payment_method:le?.payment_method?.id;l({id:Q??L.id,type:"card",threeDSecureActionResultTokenId:le?.id,gateway:"stripe",paymentMethodType:L.type??e},{accountPatch:ge,paymentMethodCategory:"apm",sessionId:yt,nonce:Be})}catch(K){y?.(K instanceof Error?K.message:"Payment failed. Please try again.")}finally{Ce.current=!1,Le(!1)}},[Y,re,R,$e,g,M,t,n,r,o,Me,i,s,G,e,l,y,f]);return Oe("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[fe&&d("div",{"data-testid":"flopay-apm-identity-fields",style:{display:"flex",flexDirection:"column",gap:"0.75rem",marginBottom:"0.75rem"},children:fe&&Oe("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",d("input",{type:"email",autoComplete:"email",required:!0,value:Me,onChange:Ae=>wt(Ae.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]})}),d(Zd,{onReady:()=>Ne("ready"),onLoadError:()=>{Ne("load_error"),as(mn(I),"stripe","apm")},onChange:Ae=>{vt(!!Ae.complete)},options:{layout:{type:"accordion",defaultCollapsed:!1,radios:"never"},fields:{billingDetails:{email:"never"}},defaultValues:{billingDetails:{...o?.trim()?{name:o.trim()}:{},...fn(r?.trim())?{email:r?.trim()}:{}}}}}),d("button",{type:"button","data-testid":`flopay-stripe-method-pay-${e}`,onClick:()=>{O()},disabled:!$e||!ut||ve||R||Ke!=="ready",style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:C,color:"white",border:"none",borderRadius:v,fontSize:"1rem",fontWeight:600,cursor:!$e||!ut||ve||R||Ke!=="ready"?"not-allowed":"pointer",opacity:!$e||!ut||ve||R||Ke!=="ready"?.5:1,transition:"opacity 120ms ease-out",...q??{}},children:ve?"Processing\u2026":`Pay with ${eo(e)}`}),Re&&d(Co,{margin:"0.75rem 0 0",children:Re})]})}function Hl({sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:i,paymentElementMethods:s,stripeInstance:l,paymentElementBaseOptions:y,onTokenizedBody:f,onErrorChange:b,onButtonClick:g,onDecline:M,runBeforeButtonClick:R,onLoadStateChange:C,isProcessing:v=!1,submitButtonColor:q="#4A49FF",submitButtonBorderRadius:Re=8,submitButtonStyle:I,buttonAppearance:G,themeId:Y,onExpandApm:re,expandedApmMethod:ve}){let{emitInstrument:Le}=To(or),[Ce,$e]=ce(null),[vt,Ke]=ce(null),Ne=de(!1),{request:Me,collect:wt,finish:fe}=ho();Ct(()=>{s.length>0&&l?C?.("ready"):l||C?.("loading")},[s.length,l,C]);let ut=tt(async N=>{if(!l||Ne.current||v)return;Ne.current=!0,Ke(N);let ue=R?await R("card"):{proceed:!0};if(!ue.proceed){Ne.current=!1,Ke(null);return}g?.("card");let ge=ue.sessionId??e,K=ue.nonce??t,Ge=Yr([ue.accountPatch?.firstName,ue.accountPatch?.lastName].filter(Boolean).join(" ")||r),Ve=On({email:ue.accountPatch?.email?.trim()||n?.trim(),firstName:ue.accountPatch?.firstName?.trim()||Ge.firstName,lastName:ue.accountPatch?.lastName?.trim()||Ge.lastName});if(!fn(Ve.email)){Ke(null);let Ye=await wt(eo(N),Ve);if(!Ye){Ne.current=!1;return}Ve=Ye,Ke(N)}let L=Ve.email,st=On({...ue.accountPatch,...Ve});try{if(b?.(null),!ge||!fn(L))throw new Error("Missing sessionId or email for payment.");await o?.(Ve);let Ye=await Ja(i,Le,ge,K??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:N,paymentMethodId:null,intentKind:"payment"});if(Ye.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let He=Ye.clientSecret;if(typeof window<"u")try{localStorage.setItem(_r,JSON.stringify({clientSecret:He,sessionId:ge,nonce:K,accountPatch:st,paymentMethodType:N,gateway:"stripe"}))}catch{}let{error:Ee,paymentIntent:le}=await l.confirmPayment({clientSecret:He,confirmParams:{return_url:window.location.href,payment_method_data:{type:N,billing_details:{name:[Ve.firstName,Ve.lastName].filter(Boolean).join(" "),...L?{email:L}:{}}}},redirect:"if_required"});if(Ee){if(typeof window<"u")try{localStorage.removeItem(_r)}catch{}let oe=Ee.message??"Payment failed.";b?.(oe),M?.(dn("card",oe,{code:Ee.code})),await Xa({billingApiUrl:i,sessionId:ge,nonce:K,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:N,providerDeclineReason:Ee.code??"provider_declined"}});return}let mt=le?.status;if(!Yo(mt)){if(typeof window<"u")try{localStorage.removeItem(_r)}catch{}let oe=mt==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";b?.(oe),M?.(dn("card",oe,{code:mt??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(_r)}catch{}let Q=typeof le?.payment_method=="string"?le.payment_method:le?.payment_method?.id;f({id:Q??le?.id,type:"card",threeDSecureActionResultTokenId:le?.id,gateway:"stripe",paymentMethodType:N},{accountPatch:st,paymentMethodCategory:"apm",sessionId:ge,nonce:K})}catch(Ye){b?.(Ye instanceof Error?Ye.message:"Payment failed. Please try again.")}finally{Ne.current=!1,Ke(null)}},[l,v,R,g,e,t,n,wt,i,Le,r,o,f,b,M]),[O,Ae]=ce(null),yt=re?ve??null:O,Be=tt(N=>{Ne.current||v||yt&&yt!==N||(Bl(N)?re?re(N):Ae(N):ut(N))},[yt,v,ut,re]),it=Et(()=>O?ec(y,O):null,[O,y]);return d("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:Me?d(vo,{identity:Me.identity,methodLabel:Me.methodLabel,onComplete:fe,onCancel:()=>fe(null)},Me.id):s.map(N=>{let ue=ve===N,ge=vt===N,K=vt!==null&&vt!==N||ve!=null&&ve!==N;return Oe(Qd.Fragment,{children:[d(Su,{method:N,themeId:Y,submitting:ge,disabled:K,highlighted:ue,hasNextStep:Bl(N),onClick:()=>Be(N),backgroundColor:G?.backgroundColor,borderColor:G?.borderColor,textColor:G?.textColor,borderRadius:G?.borderRadius,fontFamily:G?.fontFamily}),!re&&O===N&&it&&l&&d(Zr,{stripe:l,options:it,children:d(ts,{method:N,sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:i,onTokenizedBody:f,onErrorChange:b,onDecline:M,onCancel:()=>Ae(null),runBeforeButtonClick:R,onButtonClick:g,isProcessing:v,submitButtonColor:q,submitButtonBorderRadius:Re,submitButtonStyle:I})},N)]},N)})})}function ku({sessionId:e,nonce:t,billingApiUrl:n,telemetry:r,email:o,userId:i,onComplete:s,onError:l,onDecline:y,onTokenizedBody:f,firstName:b,lastName:g,chv:M,className:R,submitLabel:C,isProcessing:v,error:q,onErrorChange:Re,showPayPal:I=!0,showStripe:G=!0,enabledPaymentMethods:Y,enabledPaymentMethodCountries:re,showApplePay:ve=!0,showGooglePay:Le=!0,layout:Ce="default",theme:$e,buttonsTheme:vt,buttonsStyles:Ke,appearance:Ne,cardButtonContent:Me,cardBackButtonContent:wt,cardTitleContent:fe,showSecurityFooter:ut,onButtonClick:O,onBeforeButtonClick:Ae,onBuyerIdentityReady:yt,enableAVS:Be,cardFieldOrder:it,cardPreFormSlot:N,avsLayout:ue="row",country:ge,zip:K,addressLine1:Ge,addressLine2:Ve,city:L,state:st,onCountryChange:Ye,onZipChange:He,avsCheck:Ee,checkoutType:le,checkoutLayout:mt,totalAmount:Q=0,currency:oe="usd",initialCardOpen:Fe=!1,directPaypal:Je,isSubscription:lt=!1,session:z,dataAttachmentPending:pt=!1,dataAttachmentRequiresIdentity:Xe=!1,debug:_=!1}){let ct=Or(),Jt=_i(),xe=To(ur),{emitInstrument:un}=To(or),c=de(null);c.current||(c.current=Ba());let w=c.current,ne=de(null);ne.current||(ne.current=Qo());let k=ne.current,$=Et(()=>({browser:k,capability:w,presentationMode:"popup"}),[k,w]),ft=z??xe.session,ze=ft?.gateways?.paypal?.providerObjectType??Je?.providerObjectType,Ue=pt||xe.claimPending===!0,xt=Xe||xe.claimRequiresIdentity===!0,ee=Ue&&!xt,pn=fl(),We=n||pn,[Dt,Rn]=ce(!1),[Kt,Te]=ce(null),[Ut,gn]=ce(ge??"US"),[hn,kn]=ce(K??""),[Nn,vn]=ce(Ge??""),[Vt,De]=ce(Ve??""),[we,Ln]=ce(L??""),[St,bn]=ce(st??""),[En,Hn]=ce(""),[Ht,Xt]=ce({}),ln=de(K??""),kt=de(ge??"US"),Mt=de(Ge??""),yn=de(Ve??""),Zt=de(L??""),qt=de(st??""),Wt=de(""),Tt=de({});Ct(()=>{let a=(h,D,Pe,J,dt)=>{if(Tt.current[h])return;let Qe=D?.trim();!Qe||Qe===Pe.current||(Pe.current=Qe,J(Qe),dt?.(Qe))};a("country",ge,kt,gn,Ye),a("zip",K,ln,kn,He),a("addressLine1",Ge,Mt,vn),a("addressLine2",Ve,yn,De),a("city",L,Zt,Ln),a("state",st,qt,bn)},[ge,K,Ge,Ve,L,st,Ye,He]);let X=Et(()=>Gd(Be),[Be]),Qt=X!==null,en=Et(()=>Vi(z),[z]),ir=!!z?.vault?.html,mr=!!z?.gateways?.pcivault,Wn=Ci(z),sr=!!(z?.gateways?.stripe?.enabledPaymentMethods??Y)?.includes("card")||Mr(z),jt=ir||sr||mr,A=!!(G&&jt&&e),[gt,Ze]=ce(()=>Ce!=="buttons"||Fe?e??null:null),[x,qe]=ce(0),te=Ce!=="buttons"||Fe||!!e&>===e,tn=z?.captureMethod,Pn=de(ct);Ct(()=>{Pn.current=ct},[ct]);let[nn,fr]=ce(null);Ct(()=>{if(!A||!e||!te){fr(null);return}let a=Pn.current?Pn.current.cardCapture({sessionId:e,captureMethod:tn}):new Dd({sessionId:e,captureMethod:tn,billingApiUrl:We,telemetry:r});return fr({sessionId:e,captureMethod:tn,billingApiUrl:We,telemetry:r,capture:a}),()=>{a.unmount()}},[A,e,te,tn,We,r]);let he=A&&e&&te&&nn?.sessionId===e&&nn.captureMethod===tn&&nn.billingApiUrl===We&&nn.telemetry===r?nn.capture:null,zn=Et(()=>{let a=Ut,h=X?at(X.postal_code,a):!1;return Pu(a,hn,h)},[X,Ut,hn]),{avsInvalid:Gn,invalidAvsFields:jr}=Et(()=>{let a={line1:!1,city:!1,state:!1,zip:!1};if(!A||!X)return{avsInvalid:!1,invalidAvsFields:a};let h=Ut,D=(dt,Qe)=>at(dt,h)&&!Qe.trim(),Pe={line1:D(X.address_line_1,Nn),city:D(X.city,we),state:D(X.state,St),zip:zn.empty||zn.malformed};return{avsInvalid:Pe.line1||Pe.city||Pe.state||Pe.zip,invalidAvsFields:Pe}},[A,X,Ut,Nn,we,St,zn]),[Yn,Jn]=ce(!1),[Yt,Er]=ce(!1),[gr,Tn]=ce(!1),[hr,Xn]=ce({line1:!1,city:!1,state:!1}),Zn=de(!1),vr=de({email:!1,line1:!1,city:!1,state:!1,zip:!1}),Qn=de(!1),It=tt(a=>{vr.current[a]=!0,Qn.current=!0},[]),Un=tt(a=>!Zn.current&&vr.current[a],[]),lr=tt(a=>{Un(a)&&Xn(h=>h[a]?h:{...h,[a]:!0})},[Un]),[qn,Cn]=ce(()=>Ji(z?.vault)),[nt,In]=ce(Fe&&jt?"card":"buttons"),[cn,jn]=ce(null),$r=nt==="expanding"||nt==="card",$n=z?.gateways?.stripe&&!Wn?"stripe":void 0,br=tt(()=>{un?.({class:"card_surface",provider:$n})},[$n,un]),An=de(null),xn=tt(a=>{An.current&&clearTimeout(An.current),An.current=setTimeout(()=>{An.current=null,a()},da)},[]);Ct(()=>()=>{An.current&&clearTimeout(An.current)},[]);let Kr=tt(()=>{br(),Ze(e??null),qe(a=>a+1),In("expanding"),xn(()=>In("card"))},[xn,br,e]),Kn=tt(()=>{In("collapsing"),xn(()=>In("buttons"))},[xn]),Vr=tt(a=>{jn(a),In("apm-expanding"),xn(()=>In("apm-form"))},[xn]),rn=tt(()=>{In("apm-collapsing"),xn(()=>{In("buttons"),jn(null)})},[xn]);Ct(()=>{Ce==="buttons"&&Fe&&jt&&(Ze(e??null),In("card"))},[Ce,Fe,jt,e]);let[S,m]=ce(null),W=de(!1),F=de(null),be=de("idle"),[Nt,ye]=ce(!1),pe=de(Nt);pe.current=Nt;let[E,V]=ce(()=>Je?.existingOrderId?{orderId:Je.existingOrderId,attempts:1}:null),p=de(E);Ct(()=>{p.current=E},[E]);let u=de(null),P=Et(()=>{if(yt||xe.claimBuyerIdentity||z?.buyerIdentified!==!1||!e||!t)return;let a=`${We}|${e}|${t}`;u.current?.key!==a&&(u.current={key:a,claim:fo(new Eo(We,{telemetry:!1}),e,t,{...i?{userId:i}:{},...b?{firstName:b}:{},...g?{lastName:g}:{}})});let h=u.current.claim;return async D=>{await h(D)}},[yt,xe.claimBuyerIdentity,z?.buyerIdentified,e,t,We,i,b,g]),B=yt??xe.claimBuyerIdentity??P,ie=q??Kt,Z=Et(()=>Xd($e),[$e]),j=Et(()=>{let a=Z?.buttonsLayout??Yd(vt);return Ke?{...a,...Ke,cardButton:{...a.cardButton,...Ke.cardButton},cardFormContainer:{...a.cardFormContainer,...Ke.cardFormContainer},backButton:{...a.backButton,...Ke.backButton},backButtonIcon:{...a.backButtonIcon,...Ke.backButtonIcon},submitButton:{...a.submitButton,...Ke.submitButton},title:{...a.title,...Ke.title}}:a},[Z,vt,Ke]),ae=Ne??Z?.appearance,Se=Et(()=>Xs({appearance:ae,buttonsStyles:j,layout:Ce}),[ae,j,Ce]),bt=xe.inlineSessionPatchProcessing??!1,_e=(v??Dt)||bt,H=We.replace(/\/+$/,""),T=Et(()=>Si({userId:i,email:o,firstName:b,lastName:g,country:ge,zip:K},Ht),[i,o,b,g,ge,K,Ht]),U=[T.firstName,T.lastName].filter(a=>!!a?.trim()).join(" "),ke=!fn(T.email?.trim()),Ie=de(null);A&&Ie.current===null&&(Ie.current=ke);let ht=A&&(Ie.current??ke),je=Et(()=>Cu(En,ht),[En,ht]),Mn=je.empty||je.malformed,on=Et(()=>ct?ct.getRawProvider():null,[ct]),to=Et(()=>Jt?Jt.getRawProvider():null,[Jt]),Fo=Q||100,no=oe.toLowerCase(),ni=Et(()=>ae?Od(ae):null,[ae]),ro=ni,vs=Et(()=>{let a=ni??{},h=a.rules??{};return{...a,rules:{...h,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...h[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...h[".AccordionItemContents"]??{}}}}},[ni]),bs=Et(()=>({...ll(Q,z?.captureMethod),currency:no,...ro?{appearance:ro}:null}),[Q,no,z?.captureMethod,ro]),Ps=Et(()=>({mode:"payment",amount:Fo,currency:no,captureMethod:"manual",setupFutureUsage:"off_session",...ro?{appearance:ro}:null}),[Fo,no,ro]),me=tt(a=>{Te(a),Re?.(a)},[Re]),ri=de(""),[Cs,yc]=ce(!1),oi=tt(()=>{yc(!0)},[]);Ct(()=>{if(!A||!ht||!B||!Cs||Mn||ri.current)return;let a=On({email:fn(T.email?.trim())?T.email?.trim():Wt.current.trim(),firstName:T.firstName?.trim(),lastName:T.lastName?.trim()});ri.current=JSON.stringify(a),Xt(h=>({...h,...a})),Promise.resolve(B(a)).catch(h=>{ri.current="",me(h instanceof Error?h.message:"Failed to attach buyer details.")})},[A,ht,B,Cs,Mn,T.email,T.firstName,T.lastName,me]),Ct(()=>{!A||!he||he.setCardFieldOrder?.(it??null,X==null&&!ht)},[A,he,it,X,ht]),Ct(()=>{(nt==="expanding"||nt==="collapsing"||nt==="apm-expanding"||nt==="apm-collapsing")&&me(null)},[nt,me]);let Pr=tt((a,h,D)=>{y?.(dn(a,h,D))},[y]),oo=tt((a,h,D)=>{let Pe=D?.popupBlocked??Dr(h);Pe&&w.markBlocked();let J=Ea(es(a),Pe,k.inAppBrowser),dt=Sr(h),Qe=(dt?.toLowerCase()==="error"?void 0:dt)??Jr(D?.code)??"external_payment_method_failed",tr=new pr(J,"api_error",{code:"external_payment_method_failed",param:a,details:{providerCode:Qe,popupBlocked:Pe,inAppBrowser:k.inAppBrowser,appFamily:k.appFamily,popupCapability:w.current(),presentationMode:D?.presentationMode??"popup"}});D?.telemetryReported||mn(ct)?.error(Ro({...$,presentationMode:D?.presentationMode??"popup"},{errorCode:Pe?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:D?.provider??(a==="paypal"?"paypal":"stripe"),paymentMethodCategory:D?.paymentMethodCategory??(a==="paypal"?"paypal":"wallet"),requestCategory:"provider_sdk",terminalReason:D?.terminalReason??(Pe?"popup_blocked":"provider_error")})),m(null),Ce==="buttons"&&(In("buttons"),jn(null)),me(J),l?.(tr),console.error("[FloPay] External payment method failed:",{method:a,code:Qe,popupBlocked:Pe})},[k,$,ct,Ce,l,w,me]);Ct(()=>{if(!A||!e){Cn(null);return}let a=Ji(z?.vault);if(a){Cn(a);return}if(!te){Cn(null);return}Cn(null);let h=!0;return new Eo(H).getVaultCapture(e,t).then(D=>{if(!h)return;let Pe=Ji(D);Pe?Cn(Pe):me("Failed to load the secure card form.")}).catch(D=>{h&&me(D instanceof Error?D.message:"Failed to load the secure card form.")}),()=>{h=!1}},[A,te,x,e,z?.vault,H,t,me]);let cr=de({onComplete:s,onError:l,updateError:me,emitDecline:Pr,resolvedAccount:T,avsConfig:X,avsCheckProp:Ee,sessionId:e,nonce:t,baseUrl:H,captureMethod:z?.captureMethod,paymentId:z?.paymentId,authorizationExpiresAt:z?.authorizationExpiresAt,serverSideCardGateway:Wn});cr.current={onComplete:s,onError:l,updateError:me,emitDecline:Pr,resolvedAccount:T,avsConfig:X,avsCheckProp:Ee,sessionId:e,nonce:t,baseUrl:H,captureMethod:z?.captureMethod,paymentId:z?.paymentId,authorizationExpiresAt:z?.authorizationExpiresAt,serverSideCardGateway:Wn};let ai=de(!1),ws=tt(()=>{let a=cr.current,h=a.resolvedAccount.email?.trim(),D=fn(h)?h:Wt.current.trim();if(!fn(D))return null;let Pe=a.resolvedAccount.firstName?.trim(),J=a.resolvedAccount.lastName?.trim(),dt=kt.current||a.resolvedAccount.country||"US",Qe=a.avsConfig?at(a.avsConfig.state,dt):!1,tr=a.avsConfig?at(a.avsConfig.address_line_1,dt):!1,et=a.avsConfig?at(a.avsConfig.postal_code,dt):!1,Bt=a.avsConfig?at(a.avsConfig.city,dt):!1,Pt=a.avsConfig?at(a.avsConfig.address_line_2,dt):!1,rt=tr&&!Qe&&et?Ml(dt,(ln.current??"").trim()):null,Dn=Qe?qt.current:rt;return{accountData:{userId:a.resolvedAccount.userId??"",email:D,...Pe?{firstName:Pe}:{},...J?{lastName:J}:{},...et&&ln.current?{zip:ln.current}:{},...Bt&&Zt.current?{city:Zt.current}:{},...Dn?{state:Dn}:{},...tr&&Mt.current?{addressLine1:Mt.current}:{},...Pt&&yn.current?{addressLine2:yn.current}:{},country:dt},...a.avsCheckProp===void 0?{}:{avsCheck:a.avsCheckProp},...a.avsConfig?{avsConfig:{country:at(a.avsConfig.country,dt),postal_code:et,address_line_1:tr,address_line_2:Pt,city:Bt,state:Qe}}:{}}},[]),Ss=de(Ue);Ss.current=Ue,Ct(()=>{Ue||ie!==Ll||cr.current.updateError(null)},[Ue,ie]),Ct(()=>{!A||!he||he.setSubmitGate?.(Gn||Ue||Mn||Nt)},[A,he,Gn,Ue,Mn,Nt]),Ct(()=>{if(!A||!he)return;ai.current=!1;let a=null,h=()=>{a&&clearTimeout(a),a=setTimeout(()=>{a=null,be.current="idle",m(null)},400)},D=he.on("submitting",()=>{Jn(!0),F.current&&clearTimeout(F.current),be.current="validation-window",F.current=setTimeout(()=>{F.current=null,be.current==="validation-window"&&(be.current="processing")},lu),m("processing");let et=cr.current;if(!et.sessionId||!et.nonce)return;let Bt=ws();if(!Bt){et.updateError("Enter a valid email address."),be.current="idle",m(null);return}new Eo(et.baseUrl).patchAccountSnapshot(et.sessionId,et.nonce,Bt,{telemetryMode:"best_effort"}).catch(Pt=>{if(!du(Pt))return;let rt=Pt instanceof Error?Pt.message:"Please check your billing address and try again.";et.updateError(rt),be.current="idle",m(null),et.onError?.(Pt instanceof pr?Pt:new pr(rt,"api_error"))})}),Pe=he.on("complete",async et=>{if(ko(et.sessionId??cr.current.sessionId),be.current="terminal",ye(!1),m("success"),await new Promise(Dn=>setTimeout(Dn,600)),ai.current)return;ai.current=!0;let Bt=cr.current,Pt=Vi(Bt)||et.outcome==="authorized",rt=Bt.serverSideCardGateway?{}:{paymentIntentId:et.intentId};cr.current.onComplete?.(Pt?{status:"authorized",...rt,paymentId:et.paymentId??Bt.paymentId,sessionId:et.sessionId??Bt.sessionId,authorizationExpiresAt:et.authorizationExpiresAt??Bt.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",...rt,checkoutMethod:"card"})}),J=he.on("decline",et=>{let Bt=cr.current,Pt=et.message??"Your payment was declined. Please try another card or contact your bank.";be.current="terminal",ye(!1),Bt.updateError(Pt),m("error");let rt=et.failureOutcome??Vd(et.declineReason)??"authorization_declined";Bt.emitDecline("card",Pt,{code:rt,declineCode:rt}),h()}),dt=he.on("error",et=>{let Bt=cr.current,Pt=et.message??"There was a problem processing your payment. Please try again.";be.current="terminal",ye(!1),Bt.updateError(Pt),m("error"),Bt.onError?.(new pr(Pt,"api_error",{code:et.failureOutcome??"capture_failed"})),h()}),Qe=he.on("challenge_dismissed",()=>{F.current&&(clearTimeout(F.current),F.current=null),be.current="processing",ye(!0),m(null)}),tr=he.on("blocked",()=>{if(pe.current){cr.current.updateError(cu);return}if(!Ss.current){Jn(!0);return}oi(),cr.current.updateError(Ll)});return()=>{a&&(clearTimeout(a),a=null),F.current&&(clearTimeout(F.current),F.current=null),be.current="idle",ye(!1),m(null),D(),Pe(),J(),dt(),Qe(),tr()}},[A,he,oi,ws]);let Cr=!!Je?.clientId,Do=Array.isArray(Y),ga=Do&&Y.length>0,mc=Do&&Y.includes("paypal"),{expressMethods:ha,paymentElementMethods:Oo}=Et(()=>Hd(Y,{excludePaypal:Cr}),[Y,Cr]),ks=Cr||!!Jt,fc=Et(()=>ks?ha.filter(a=>a!=="paypal"):ha,[ha,ks]),gc=Et(()=>{let a=[];return ve&&a.push("apple_pay"),Le&&a.push("google_pay"),a},[ve,Le]),ao=Do?fc:gc,hc=G&&ao.length>0,ii=Qt?Ut:ge,va=Et(()=>{let a=ii?.trim().toUpperCase();return a?re?Oo.filter(h=>{let D=re[h];return!D||D.length===0||D.includes(a)}):zd(Oo,ii):Oo},[Oo,ii,re]),si=Et(()=>({mode:"payment",amount:Fo,currency:no,paymentMethodCreation:"manual",appearance:vs}),[Fo,no,vs]),[Is,_s]=ce("loading"),[Rs,Es]=ce("loading"),[Ts,As]=ce("loading"),[vc,li]=ce(!1),[xs,ci]=ce("loading"),[di,bc]=ce();Ct(()=>{bc(Qo())},[]);let ba=di?.inAppBrowser,Pa=di?xa(di,Je?.approvalPresentation,ze??(lt?"subscription":"order")):"popup",Ms=I&&(Cr||(Do?mc:ba===!1)),Bs=G&&hc,No=(!ee||!!xe.waitForDataAttachment)&&Ms&&Cr,Fs=xs==="retrying"||xs==="exhausted",Lo=!ee&&Ms&&!!to&&(!Cr||Fs),io=!ee&&Bs&&!!on,zo=!ee&&G&&ga&&va.length>0&&!!on,Pc=No&&!Fs?vc:Lo&&$l(Is),Cc=io&&$l(Rs),wc=zo&&Ts!=="load_error",Ds=a=>a==="loading"||a==="ready",Os=No||Lo&&Ds(Is)||io&&Ds(Rs)||zo&&Ts!=="load_error",Ca=de(!1);Ct(()=>{if(!Ca.current){if(!G&&!I){Ca.current=!0;let a=new pr("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");l?.(a),me(a.message)}else if(!G&&I&&!Cr&&!to){Ca.current=!0;let a=new pr("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");l?.(a),me(a.message)}else if(ba!==void 0&&!ee&&!jt&&!Os){Ca.current=!0;let a=new pr("FloPay: this checkout session has no vault card capability and no usable supported non-card payment methods. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});l?.(a),me(a.message)}}},[G,I,Cr,to,ba,ee,jt,Os,l,me]);let Ns=de(!1);Ct(()=>{if(Ns.current||!ga)return;let a=[];ve!==!0&&a.push("showApplePay"),Le!==!0&&a.push("showGooglePay"),a.length!==0&&(Ns.current=!0,console.warn(`[FloPay] ${a.join(" / ")} ${a.length===1?"is":"are"} deprecated: the Apple Pay / Google Pay surface is now driven by \`gateways.stripe.enabledPaymentMethods\` on the session response. Remove the legacy prop(s) to silence this warning.`))},[ga,ve,Le]);let Ls=tt((a,h)=>xe.applyInlineSessionPatch?xe.applyInlineSessionPatch(a).then(D=>({error:null,sessionId:D.sessionId||e,nonce:D.session?.clientSecret||t})).catch(D=>{let Pe=jl(h,D);return me(Pe.message),l?.(Pe),{error:Pe,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[xe.applyInlineSessionPatch,t,l,e,me]),dr=tt(async a=>{if(a!=="card"&&ee&&await xe.waitForDataAttachment?.(),!Ae)return{proceed:!0};try{let h=await Ae({method:a,sessionId:e||void 0,createSession:xe.inlineSessionDraft});if(h===!1)return{proceed:!1};if(h&&typeof h=="object"){h.account&&Xt(Pe=>({...Pe??{},...h.account}));let D=await Ls(h,a);return D.error?{proceed:!1,accountPatch:h.account}:{proceed:!0,accountPatch:h.account,sessionId:D.sessionId,nonce:D.nonce}}return{proceed:!0}}catch(h){let D=jl(a,h);return me(D.message),l?.(D),{proceed:!1}}},[Ls,xe.inlineSessionDraft,xe.waitForDataAttachment,ee,Ae,l,e,me]),zs=tt(async(a,h)=>{if(W.current)return;W.current=!0,Rn(!0),m("processing"),me(null);let D=h?.sessionId??e,Pe=h?.nonce??t,J=Si(T,h?.accountPatch),dt=h?.completionPaymentMethodId??Jo(a),Qe=a.originalPaymentMethodId?{...a,originalPaymentMethodId:void 0}:a,tr=fu(a),et=()=>{un?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"process_payment",provider:tr})};try{let Pt=await new Eo(H).processPayment(J.userId??"",{sessionId:D,nonce:Pe,paymentMethodCategory:h?.paymentMethodCategory??hu(a),tokenizedData:Qe,accountData:{...h?.accountPatch,userId:J.userId??"",email:J.email??"",firstName:J.firstName||void 0,lastName:J.lastName||void 0,...X?(()=>{let _t=kt.current,nr=at(X.state,_t),_n=at(X.address_line_1,_t),an=at(X.postal_code,_t),Gr=_n&&!nr&&an?Ml(_t,(ln.current??"").trim()):null,Vo=nr?qt.current:Gr;return{country:_t,...an&&ln.current?{zip:ln.current}:{},...at(X.city,_t)&&Zt.current?{city:Zt.current}:{},...Vo?{state:Vo}:{},..._n&&Mt.current?{addressLine1:Mt.current}:{},...at(X.address_line_2,_t)&&yn.current?{addressLine2:yn.current}:{}}})():{}},chv:M,avsCheck:Ee??!1,checkoutType:le,checkoutLayout:mt,avsConfig:X?{country:at(X.country,kt.current),postal_code:at(X.postal_code,kt.current),address_line_1:at(X.address_line_1,kt.current),address_line_2:at(X.address_line_2,kt.current),city:at(X.city,kt.current),state:at(X.state,kt.current)}:void 0});if(Pt.ok){let _t=Pt.status===204?null:await Pt.json().catch(()=>null),nr=Vi(z)||_t?.status==="authorized";ko(D),m("success"),V(null),await new Promise(Gr=>setTimeout(Gr,600));let _n;typeof _t?.paymentId=="string"?_n=_t.paymentId:z?.paymentId&&(_n=z.paymentId);let an;typeof _t?.authorizationExpiresAt=="string"?an=_t.authorizationExpiresAt:z?.authorizationExpiresAt&&(an=z.authorizationExpiresAt),s?.(nr?{status:"authorized",..._n===void 0?{}:{paymentId:_n},sessionId:typeof _t?.sessionId=="string"?_t.sessionId:D,...an===void 0?{}:{authorizationExpiresAt:an},paymentIntentId:a.threeDSecureActionResultTokenId,paymentMethodId:dt,checkoutMethod:a.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:a.threeDSecureActionResultTokenId,paymentMethodId:dt,checkoutMethod:a.isPaypal?"paypal":"card"});return}let rt=await Pt.json().catch(()=>null);if(rt?.type==="paypal_redirect_required"){let _t=rt.threeDSecureToken,nr=rt.paymentMethodId||a.id||"";if(!ct||!_t){m("error"),me("PayPal authorization required but no token provided.");return}try{let _n=Jt?.getRawProvider();if(!_n){me("PayPal is not available.");return}let an={return_url:window.location.href};nr&&(an.payment_method=nr);let{error:Gr}=await _n.confirmPayment({clientSecret:_t,confirmParams:an,redirect:"if_required"});if(Gr){m("error");let Vo=Gr.message??"PayPal payment failed.";me(Vo),Pr("paypal",Vo,{code:Gr.code})}}catch(_n){m("error"),me(_n instanceof Error?_n.message:"PayPal authorization failed.")}return}if(rt?.type==="paypal_direct_required"){let _t=rt.orderId;if(!_t){m("error"),me("PayPal retry required but no order id provided.");return}let nr=p.current?.attempts??0;if(nr>=2){m("error"),me("PayPal payment could not be completed after multiple attempts."),Pr("paypal","paypal_direct_required retry limit exceeded");return}li(!1),ci("loading"),V({orderId:_t,attempts:nr+1}),m(null);return}Ld(Pt.status,rt)||et(),m("error");let Dn=rt?.message??"Payment failed. Please try again.";me(Dn),Pr(a.isPaypal?"paypal":"card",Dn,{code:rt?.code??rt?.gatewayErrorCode,declineCode:rt?.declineCode??rt?.gatewayDeclineReason}),await new Promise(_t=>setTimeout(_t,400))}catch(Bt){Jl(Bt)||et(),m("error"),me(Bt instanceof Error?Bt.message:"An unexpected error occurred"),await new Promise(Pt=>setTimeout(Pt,400))}finally{Rn(!1),m(null),W.current=!1}},[H,e,t,T,X,Ee,le,mt,M,ct,Jt,z,s,me,Pr,un]),Bn=tt((a,h)=>{f?f(a):zs(a,h)},[f,zs]),Uo=`${Gl}:${e}`;Ct(()=>{if(typeof window>"u")return;let a=localStorage.getItem(Uo);if(!a)return;let h;try{h=JSON.parse(a)}catch{localStorage.removeItem(Uo);return}if(!h||typeof h.createdAt!="number"||Date.now()-h.createdAt<0||Date.now()-h.createdAt>Yl||typeof h.paymentMethodId!="string"||typeof h.providerIntentId!="string"||typeof h.paymentMethodType!="string"||h.sessionId!==e||!t||h.nonce!==t||!ao.includes(h.paymentMethodType)){localStorage.removeItem(Uo);return}localStorage.removeItem(Uo),Bn({id:h.paymentMethodId,type:"card",threeDSecureActionResultTokenId:h.providerIntentId,gateway:"stripe",paymentMethodType:h.paymentMethodType},{...h.accountPatch?{accountPatch:h.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t})},[Bn,t,e,Uo,ao]);let Us=de(!1);Ct(()=>{if(typeof window>"u"||Us.current)return;let a=new URLSearchParams(window.location.search),h=a.get("payment_intent"),D=a.get("payment_intent_client_secret"),Pe=a.get("redirect_status");if(!h||!D||!ct)return;let J=ct.getRawProvider();if(!J)return;let dt=rt=>{let Dn=localStorage.getItem(rt);if(!Dn)return null;try{return JSON.parse(Dn)}catch{return localStorage.removeItem(rt),null}},Qe=dt(_r)??dt(Dl),tr;if(Qe?.clientSecret){if(Qe.clientSecret!==D)return;tr={...Qe.accountPatch?{accountPatch:Qe.accountPatch}:{},...Qe.sessionId?{sessionId:Qe.sessionId}:{},...Qe.nonce?{nonce:Qe.nonce}:{}}}else if(Qe?.sessionId&&Qe.sessionId!==e)return;Us.current=!0,localStorage.removeItem(_r),localStorage.removeItem(Dl);let et=new URL(window.location.href);et.searchParams.delete("payment_intent"),et.searchParams.delete("payment_intent_client_secret"),et.searchParams.delete("redirect_status"),window.history.replaceState({},"",et.toString());let Bt=Qe?.paymentMethodType??Qe?.tokenType??"card",Pt="card";(async()=>{if(Pe==="failed"){let an="Payment was declined. Please try again.";me(an),Pr(Pt,an);return}let{paymentIntent:rt,error:Dn}=await J.retrievePaymentIntent(D);if(Dn){let an=Dn.message??"Failed to retrieve payment status.";me(an),Pr(Pt,an,{code:Dn.code});return}let _t=rt?.status,nr=Yo(_t);if(!rt||!nr){let an=_t==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";me(an),Pr(Pt,an,{code:_t??"missing_payment_intent"});return}let _n=typeof rt.payment_method=="string"?rt.payment_method:rt.payment_method?.id;Bn({id:_n??Qe?.paymentMethodId??Qe?.tokenId??rt.id,type:"card",threeDSecureActionResultTokenId:rt.id,gateway:Qe?.gateway??"stripe",paymentMethodType:Bt},tr)})()},[e,Bn,ct,me,Pr]);let ui=tt(a=>{a.preventDefault()},[]);if(!(A||ct!==null))return d("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let qo=Ce==="buttons",Fn=ae?.variables,Sc=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),pi=Fn?.colorBackground,kc=pi&&!Sc.has(pi)?pi:void 0,jo=j.cardInputBorder??(qo?"#e5e7eb":"#A4A4FF"),qs=Fn?.colorDanger??"#dc2626",Lt=a=>jr[a]&&(hr[a]||Yn),wa=Mn&&(gr||Yn),er=a=>a?qs:jo,Sa=(zn.malformed||zn.empty)&&(Yt||Yn),Ic=er(Sa),yi=j.cardFormContainer?.backgroundColor??kc??(qo?"white":"#EDEDFF"),so=j.cardInputBackground??Fn?.colorBackground??"white",mi=uo(wt),js=uo(fe),lo=j.nameInput,$s=j.cardInputFontSize??wu(lo?.fontSize)??Fn?.fontSizeBase??"16px",Ks=typeof lo?.fontFamily=="string"?lo.fontFamily:Fn?.fontFamily??"Poppins, sans-serif",Vs=Js(lo?.fontWeight)??400,_c=j.cardInputColor??(typeof lo?.color=="string"?lo.color:void 0)??Fn?.colorText??"#262833",Rc=j.cardInputPlaceholderColor??"#9ca3af",$t=Fn?.borderRadius??"8px",Hr=Fn?.borderRadius??j.cardButton?.borderRadius??$t,Wr=Fn?.colorPrimary??"#4A49FF",Ec=Fn?.colorPrimaryHover??Wo(Wr,.12),fi=Fn?.colorText??"#262833",gi={fontSize:$s,fontFamily:Ks,fontWeight:Vs,color:_c,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},$o={marginTop:"0.375rem",...gi,fontSize:"0.75rem",lineHeight:1.4,color:qs},Tc={"--flopay-input-placeholder-color":Rc,"--flopay-input-font-size":$s,"--flopay-input-font-family":Ks,"--flopay-input-font-weight":String(Vs)},Ko=j.cardFormContainer??{},hi=Ko.padding??(qo?"0":"1rem"),vi=Ko.borderRadius??$t,Ac=he&&qn?d(bi,{capture:he,html:qn.html,messageToken:qn.messageToken,expectedOrigin:qn.expectedOrigin,theme:Se,submitLabel:C,onReady:()=>{if(!ht&&!X||typeof document>"u")return;let a=()=>{let D=(document.querySelector('[data-testid="flopay-vault-identity-fields"]')??document.querySelector('[data-testid="flopay-avs-fields"]'))?.querySelector("input:not([disabled]), select:not([disabled])");if(D){Zn.current=!0;try{D.focus()}finally{Zn.current=!1}}};Qn.current||a()},onError:a=>me(a),onValidation:a=>{let h=be.current;(h==="idle"||h==="validation-window")&&(me(a),a&&be.current==="validation-window"&&(F.current&&(clearTimeout(F.current),F.current=null),be.current="idle",m(null)))}}):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"}),Hs=Oe("div",{onFocusCapture:a=>{["INPUT","SELECT","TEXTAREA","IFRAME"].includes(a.target.tagName)&&br()},style:{backgroundColor:yi,borderRadius:vi,...Ko,padding:hi,...Tc,display:"flex",flexDirection:"column"},children:[d("style",{children:`
|
|
26
26
|
.flopay-shared-input::placeholder {
|
|
27
27
|
color: var(--flopay-input-placeholder-color);
|
|
28
28
|
opacity: 1;
|
|
@@ -30,13 +30,13 @@ ${pt.join(`
|
|
|
30
30
|
font-family: var(--flopay-input-font-family);
|
|
31
31
|
font-weight: var(--flopay-input-font-weight);
|
|
32
32
|
}
|
|
33
|
-
`}),
|
|
34
|
-
`)}):null,
|
|
35
|
-
`)}):null,Os=We==="apm-expanding"||We==="apm-form"||We==="apm-collapsing",ao;We==="apm-expanding"?ao=kl:We==="apm-collapsing"&&(ao=_l);let ga=ln?Ul(Ya,ln):null;if(ve==="buttons"){let a=We==="buttons"||We==="expanding"||We==="apm-expanding",b=We==="expanding"||We==="card"||We==="collapsing",j=De===void 0?{boxSizing:"border-box",height:La,padding:"0 1rem"}:{padding:"0.9rem 1rem"},Be;We==="expanding"||We==="apm-expanding"?Be=nu:(We==="collapsing"||We==="apm-collapsing")&&(Be=tu);let W;return We==="expanding"?W=kl:We==="collapsing"&&(W=_l),ze("form",{onSubmit:Qa,className:w,noValidate:!0,style:{position:"relative"},children:[c(Ui,{}),Un&&c(fr,{status:Un,errorMessage:P,authorized:Kn}),ze("div",{style:{display:"grid"},children:[ze("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!a&&!Be?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!a&&!Be?ou:{},...Be?{animation:Be,pointerEvents:"none"}:{}},children:[Ns("flopay-direct-paypal-gate-debug"),Ls("flopay-stripe-gate-debug"),xo&&ke&&ze(Yr,{children:[z&&c("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."}),c(ka,{sessionId:e,nonce:t,billingApiUrl:N,email:y.email,billingName:k||void 0,onBuyerIdentityReady:g,clientId:ke.clientId,environment:ke.environment,currency:Me.toUpperCase(),isSubscription:Ee,providerObjectType:B,approvalPresentation:ua==="popup"?void 0:ua,onTokenizedBody:An,onComplete:s,onErrorChange:he,onDecline:p,onTechnicalFailure:eo,onButtonClick:Z,runBeforeButtonClick:lr,isProcessing:Ce,onLoadStateChange:Ja,onInitializationStateChange:Xa,session:u,existingOrderId:z?.orderId,debug:H},z?.orderId??"fresh")]}),Mo&&c(Gr,{stripe:tn,options:cs,children:c(Al,{sessionId:e,nonce:t,email:y.email,billingName:k||void 0,onBuyerIdentityReady:g,billingApiUrl:N,onTokenizedBody:An,onErrorChange:he,isProcessing:Ce,onButtonClick:Z,onDecline:p,onTechnicalFailure:eo,runBeforeButtonClick:lr,onLoadStateChange:fs,placeholderBorderRadius:jr})}),no?c(Gr,{stripe:ht,options:ls,children:c(xl,{sessionId:e,nonce:t,email:y.email,billingName:k||void 0,onBuyerIdentityReady:g,billingApiUrl:N,intentKind:xe>0?"payment":"setup",expressMethods:to,onTokenizedBody:An,onErrorChange:he,onButtonClick:Z,onDecline:p,onTechnicalFailure:eo,runBeforeButtonClick:lr,onLoadStateChange:hs,placeholderBorderRadius:jr})}):null,!no&&Ss?c("div",{style:{height:La,borderRadius:jr,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,Bo&&c(Ml,{sessionId:e,nonce:t,email:y.email,billingName:[y.firstName,y.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:g,billingApiUrl:N,paymentElementMethods:ca,stripeInstance:ht,paymentElementBaseOptions:Ya,onTokenizedBody:An,onErrorChange:he,onButtonClick:Z,onDecline:p,runBeforeButtonClick:lr,onLoadStateChange:Ps,isProcessing:Ce,submitButtonColor:$r,submitButtonBorderRadius:Vt,submitButtonStyle:v.submitButton,onExpandApm:Tr,expandedApmMethod:ln,themeId:Ue,buttonAppearance:{backgroundColor:v.cardButton?.backgroundColor,borderColor:v.cardInputBorder,textColor:v.cardButton?.color,borderRadius:jr}}),Le&&c("button",{type:"button",onClick:async()=>{Ce||!(await lr("card")).proceed||(Z?.("card"),Xr())},disabled:Ce,style:{width:"100%",...j,...v.cardButton,...Yi({themeBundle:I,resolvedPrimaryColor:$r,resolvedBorderRadius:Vt,submitButtonStyle:v.submitButton,explicitPrimaryColor:xn?.colorPrimary}),fontSize:v.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:Ce?"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:Ce?.6:1},onMouseEnter:st=>{!Ce&&(I||xn?.colorPrimary)&&(st.currentTarget.style.backgroundColor=yc)},onMouseLeave:st=>{(I||xn?.colorPrimary)&&(st.currentTarget.style.backgroundColor=$r)},onMouseDown:st=>{st.currentTarget.style.transform="scale(0.985)"},onMouseUp:st=>{st.currentTarget.style.transform="scale(1)"},children:c(so,{content:De})}),P&&We==="buttons"&&c(ho,{margin:"0.25rem 0",styleOverride:v.errorBanner,children:P})]}),Le&&b&&c("div",{style:{gridArea:"1 / 1",...W?{animation:W}:{},...We==="collapsing"?{pointerEvents:"none"}:{}},children:Ds}),G&&Os&&ln&&ga&&ht&&c("div",{style:{gridArea:"1 / 1",...ao?{animation:ao}:{},...We==="apm-collapsing"?{pointerEvents:"none"}:{}},children:ze("div",{style:{backgroundColor:ti,borderRadius:ii,...Oo,padding:ai},children:[ze("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[ze("button",{type:"button","data-testid":"flopay-apm-back-button",onClick:In,style:{display:"inline-flex",alignItems:"center",gap:ni?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:v.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...v.backButton},"aria-label":"Back to payment methods",children:[c("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...v.backButtonIcon},children:c("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:c("path",{d:"M15 18l-6-6 6-6"})})}),c(lo,{content:ye})]}),c("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:v.titleFontSize??"1.05rem",color:ri,paddingRight:80,...v.title},children:`Pay with ${Jr(ln)}`})]}),c(Gr,{stripe:ht,options:ga,children:c(Ki,{method:ln,sessionId:e,nonce:t,email:y.email,billingName:[y.firstName,y.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:g,billingApiUrl:N,onTokenizedBody:An,onErrorChange:he,onDecline:p,onCancel:In,runBeforeButtonClick:lr,onButtonClick:Z,isProcessing:Ce,submitButtonColor:$r,submitButtonBorderRadius:Vt,submitButtonStyle:v.submitButton,errorText:P})},ln)]})})]})]})}return Os&&ln&&ga&&ht&&G?ze("form",{onSubmit:Qa,className:w,noValidate:!0,style:{position:"relative"},children:[c(Ui,{}),Un&&c(fr,{status:Un,errorMessage:P,authorized:Kn}),c("div",{style:{...ao?{animation:ao}:{},...We==="apm-collapsing"?{pointerEvents:"none"}:{}},children:ze("div",{style:{backgroundColor:ti,borderRadius:ii,...Oo,padding:ai},children:[ze("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[ze("button",{type:"button","data-testid":"flopay-apm-back-button-default",onClick:In,style:{display:"inline-flex",alignItems:"center",gap:ni?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:v.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...v.backButton},"aria-label":"Back to payment methods",children:[c("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...v.backButtonIcon},children:c("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:c("path",{d:"M15 18l-6-6 6-6"})})}),c(lo,{content:ye})]}),c("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:v.titleFontSize??"1.05rem",color:ri,paddingRight:80,...v.title},children:`Pay with ${Jr(ln)}`})]}),c(Gr,{stripe:ht,options:ga,children:c(Ki,{method:ln,sessionId:e,nonce:t,email:y.email,billingName:[y.firstName,y.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:g,billingApiUrl:N,onTokenizedBody:An,onErrorChange:he,onDecline:p,onCancel:In,runBeforeButtonClick:lr,onButtonClick:Z,isProcessing:Ce,submitButtonColor:$r,submitButtonBorderRadius:Vt,submitButtonStyle:v.submitButton,errorText:P})},ln)]})})]}):ze("form",{onSubmit:Qa,className:w,noValidate:!0,style:{position:"relative"},children:[c(Ui,{}),Un&&c(fr,{status:Un,errorMessage:P,authorized:Kn}),ze("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Ns("flopay-direct-paypal-gate-debug-default"),Ls("flopay-stripe-gate-debug-default"),xo&&ke&&ze(Yr,{children:[z&&c("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."}),c(ka,{sessionId:e,nonce:t,billingApiUrl:N,email:y.email,billingName:k||void 0,onBuyerIdentityReady:g,clientId:ke.clientId,environment:ke.environment,currency:Me.toUpperCase(),isSubscription:Ee,providerObjectType:B,approvalPresentation:ua==="popup"?void 0:ua,onTokenizedBody:An,onComplete:s,onErrorChange:he,onDecline:p,onTechnicalFailure:eo,onButtonClick:Z,runBeforeButtonClick:lr,isProcessing:Ce,onLoadStateChange:Ja,onInitializationStateChange:Xa,session:u,existingOrderId:z?.orderId,debug:H},z?.orderId??"fresh")]}),Mo&&c(Gr,{stripe:tn,options:cs,children:c(Al,{sessionId:e,nonce:t,email:y.email,billingName:k||void 0,onBuyerIdentityReady:g,billingApiUrl:N,onTokenizedBody:An,onErrorChange:he,isProcessing:Ce,onButtonClick:Z,onDecline:p,onTechnicalFailure:eo,runBeforeButtonClick:lr,onLoadStateChange:fs,placeholderBorderRadius:jr})}),no&&c(Gr,{stripe:ht,options:ls,children:c(xl,{sessionId:e,nonce:t,email:y.email,billingName:k||void 0,onBuyerIdentityReady:g,billingApiUrl:N,intentKind:xe>0?"payment":"setup",expressMethods:to,onTokenizedBody:An,onErrorChange:he,onButtonClick:Z,onDecline:p,onTechnicalFailure:eo,runBeforeButtonClick:lr,onLoadStateChange:hs,placeholderBorderRadius:jr})}),Bo&&c(Ml,{sessionId:e,nonce:t,email:y.email,billingName:[y.firstName,y.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:N,paymentElementMethods:ca,stripeInstance:ht,paymentElementBaseOptions:Ya,onTokenizedBody:An,onErrorChange:he,onButtonClick:Z,onDecline:p,runBeforeButtonClick:lr,onLoadStateChange:Ps,isProcessing:Ce,submitButtonColor:$r,submitButtonBorderRadius:Vt,submitButtonStyle:v.submitButton,themeId:Ue,onExpandApm:Tr,expandedApmMethod:ln,buttonAppearance:{backgroundColor:v.cardButton?.backgroundColor,borderColor:v.cardInputBorder,textColor:v.cardButton?.color,borderRadius:jr}})]}),Le&&(sc||ic||lc)&&ze("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem",margin:"0.5rem 0 0.75rem",color:"#999",fontSize:"0.85rem"},children:[c("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}}),c("span",{children:"or pay with card"}),c("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}})]}),Le&&Ds]})}import{Fragment as vr,jsx as oe,jsxs as en}from"react/jsx-runtime";var ko=44,rs="flopay_checkout_saved_payment_resume",$a=new Map,qa=new Map;function jl(e,t){t.settled&&t.consumers===0&&$a.get(e)===t&&$a.delete(e)}function Cu(e,t,n){let r=qa.get(e);if(r&&(!r.sdkGeneratedIdempotencyKey||!t||r.sdkGeneratedIdempotencyKey===t))return r.attempt;let o=n(),i={attempt:o,sdkGeneratedIdempotencyKey:t};qa.set(e,i);let s=()=>{qa.get(e)===i&&qa.delete(e)};return o.then(s,s),o}function na(e){return new Promise(t=>setTimeout(t,e))}function ja(e,t,n){let r=wa({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:Jl,enabled:t!==!1});return r.beginCheckout(n),r}function ra(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function Zi(e,t,n,r,o,i){let s=ja(e,t,n);s.error({errorCode:r,stage:o,paymentMethodCategory:"unknown",...i,...o==="session_read"?{requestCategory:"session_read"}:{}}),ra(s)}function $l(e,t,n,r){e.log({name:t==="session_claim"?"session.claim.completed":"session.request.completed",stage:t,requestCategory:t,statusClass:"2xx"}),e.performance({stage:t,durationMs:Math.max(0,e.now()-n),durationMode:"machine",requestCategory:t,...r===void 0?{}:{attempt:r},statusClass:"2xx"})}function Kl(e,t,n,r,o){let i=Gl(t,"CHECKOUT_SESSION_CREATE_FAILED","unknown");return e.performance({stage:n,durationMs:Math.max(0,e.now()-r),durationMode:"machine",requestCategory:n,attempt:o,statusClass:i.statusClass}),t instanceof 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 Xl(e,t){let n=e?.data.paypal?.publishableKey;if(n)return{clientId:n,environment:e?.data.paypal?.environment,providerObjectType:e?.data.paypal?.providerObjectType,approvalPresentation:e?.data.paypal?.approvalPresentation,...t?{existingOrderId:t}:{}}}function Qi(e){return!e||e.data.stripe?.publishableKey?!1:!!Xl(e)?.clientId}var Su={name:"provider_unavailable",initialize:()=>Promise.resolve(),getRawProvider:()=>null,destroy:()=>{}};function wu(e){return new yu(Su,{publishableKey:"provider_unavailable",...e})}async function es(e,t){let{publishableKey:n,paypalPublishableKey:r}=Ai(e);return{...await xi({publishableKey:n,paypalPublishableKey:r,...t}),publishableKey:n,paypalPublishableKey:r}}function os(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function Iu(){if(!os())return null;try{let e=window.sessionStorage.getItem(rs);return e?JSON.parse(e):null}catch{return null}}function Vl(e){if(os())try{window.sessionStorage.setItem(rs,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function ts(){if(os())try{window.sessionStorage.removeItem(rs)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}function ku(){if(typeof window>"u")return;let e=new URL(window.location.href),t=["payment_intent","payment_intent_client_secret","redirect_status"],n=!1;for(let r of t)e.searchParams.has(r)&&(e.searchParams.delete(r),n=!0);n&&window.history.replaceState(window.history.state,"",e.toString())}function Hl(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 ns(e,t){return e?"custom_layout":t==="buttons"?"buttons_layout":"default_layout"}function _u(e,t){return e?"unknown":t==="buttons"?"buttons":"embedded"}function Wl(e){return e?.gateways?.stripe?"stripe":e?.gateways?.paypal?"paypal":void 0}function Ru(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 as({sessionId:e,nonce:t,createSession:n,billingApiUrl:r,telemetry:o,appearance:i,locale:s,loading:l,error:p,onComplete:f,onError:C,onInstrument:h,onDecline:m,onCountryChange:w,onZipChange:_,showPayPal:ae=!0,showStripe:Y=!0,enabledPaymentMethods:Pe,showApplePay:S=!0,showGooglePay:G=!0,debug:X=!1,layout:ce,theme:Te,buttonsTheme:Fe,buttonsStyles:ve,cardButtonContent:Ue,cardBackButtonContent:bt,cardTitleContent:ot,showSecurityFooter:$e,onButtonClick:De,onBeforeButtonClick:ye,enableAVS:we,cardFieldOrder:Qe,cardPreFormSlot:Z,avsLayout:Ie,submitLabel:be,className:ct,initialErrorMessage:dt=null,initialPayPalOrderId:U,children:V,checkoutMode:de,confirmLabel:fe,renderConfirmButton:ut,onSessionCompleted:Ne}){let x=vu(r),at=tr(()=>Yl(Te),[Te]),Ye=i??at?.appearance,re=n?"embedded_checkout":"standard_checkout",Q=ns(V,ce),[L,Ae]=jt(null),[xe,Me]=jt(null),qe=Rt(null),ke=Rt(null),Ee=Rt(0),[ee,dn]=jt(null),Yt=Rt(null),[H,Je]=jt(null),$=tr(()=>n?Po(n):"",[n]),K=n?`create:${$}`:`session:${e??""}`,ie=Wl(H),u=Rt(new Set),B=Rt(K),_e=Rt(K);Uo(()=>{_e.current=K,B.current!==K&&(B.current=K,u.current.clear())},[K]);let Ke=Pn(T=>{if(_e.current===K){if(yi.has(T.name)){if(u.current.has(T.name))return;u.current.add(T.name)}Bt(()=>h?.(T))}},[K,h]),Re=go(Ke,K),$t=Rt(!1),N=Pn(T=>{if($t.current)return;let E=T.gateway||!ie?T:{...T,gateway:ie};Ke(E)},[Ke,ie]);ur(()=>{Re({class:"lifecycle",name:"checkout.mount"})},[Re]);let[Ct,Et]=jt(e??""),pt=e??Ct,un=n?"":pt,[O,Ot]=jt(!0),[Cn,pn]=jt(null),[mn,_n]=jt(0),[Fn,Dn]=jt("full"),[Jt,je]=jt(!1),[He,St]=jt(dt),[rn,wt]=jt(null),[$n,mt]=jt(null),[Tt,zt]=jt(!1),[yn,Ut]=jt(void 0),[At,Sn]=jt(""),[wn,It]=jt(!1),[te,on]=jt(!1),[Kn,Ht]=jt(!1),Kt=Rt(null),an=Rt(0),nr=Rt(void 0),[Nn,Wt]=jt("loading"),[Le,fn]=jt(0),se=Rt(!1),M=Rt(!1),Oe=Rt(!1),D=Rt(null),kt=Rt(null),xt=tr(()=>({checkoutMode:de??Fn,layout:_u(V,ce)}),[de,V,Fn,ce]),Gt=Rt(f);Gt.current=f;let Vn=Rt(C);Vn.current=C;let ge=Rt(m);ge.current=m;let sn=Pn(T=>Ma(D,async E=>{try{return await T(E)}catch(F){throw E.aborted?Zo(F):F}}),[]);ur(()=>()=>{D.current?.abort(),D.current=null},[]);let Hn=Pn((T,E)=>{qe.current=T,Me(T),Yt.current=E,dn(E)},[]),Pr=Pn(()=>{let T=ke.current;T&&(ke.current=null,T.destroy())},[]);ur(()=>{Qt(xe)?.setCheckoutContext(xt),ee&&ee!==xe&&Qt(ee)?.setCheckoutContext(xt)},[xe,ee,xt]);let rr=Rt(Ne);rr.current=Ne;let zr=Pn(T=>{Wt(T),!(T!=="exhausted"||Oe.current)&&(Oe.current=!0,Vn.current?.(new bn("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),Ur=Pn(()=>{Wt("retrying"),fn(T=>T+1)},[]);ur(()=>{Wt("loading"),fn(0),Oe.current=!1},[pt]),ur(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:Jl,checkout_type:re,checkout_layout:Q,billing_api_url:x})},[Q,re,x]);let or=tr(()=>n?Po(n,!0):"",[n]),Er=tr(()=>At===or?yn:void 0,[yn,At,or]),Rn=tr(()=>n?di(n,Er):void 0,[n,Er]),ar=de??Rn?.checkoutMode??"full",Dt=tr(()=>Rn?{...Rn,checkoutMode:ar}:void 0,[Rn,ar]);ur(()=>{Ut(void 0),Sn(or),nr.current=void 0,Kt.current=null,Ht(!1)},[or]),ur(()=>{St(dt)},[dt]);let Ln=Pn((T,E,F)=>{Bt(()=>{ge.current?.(nn(T,E,F))})},[]),Wn=Pn(async(T,E)=>{St(null),mt(null),zt(!1),wt("processing");let F=E?.sessionId??T.id,z=T.clientSecret||t,it=Wl(T),R=qe.current??Yt.current,d=Qt(R),A=R?null:ja(x,o,xt),g={log:y=>{d?d.log(y):A?.log(y)},error:y=>{d?d.error(y):A?.error(y)},terminal:y=>{d?d.terminal(y):A?.terminal(y)},performance:y=>{d?d.performance(y):A?.performance(y)},now:()=>d?.now()??A?.now()??0,elapsed:y=>d?.elapsed(y)??Math.max(0,(A?.now()??y)-y)},P=g.now(),I=!!(E?.initialAutoProcessingError||E?.initialAutoProcessingPending),v=!1,q,Ve=()=>{v||(v=!0,I=!0,q=g.now(),g.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),g.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},Nt=!1,Ce=()=>{Nt||(Nt=!0,g.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),g.performance({stage:"processing",durationMs:g.elapsed(P),durationMode:"machine",paymentMethodCategory:"saved",requestCategory:"process_payment"}),q!==void 0&&g.performance({stage:"recovery",durationMs:g.elapsed(q),durationMode:"machine",paymentMethodCategory:"saved"}))};g.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),$t.current=!0;try{g.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"})}finally{$t.current=!1}Re({class:"lifecycle",name:"payment.processing.started",provider:it}),I&&Ve();let ne;try{let y=fl(E?.initialAutoProcessingError),k=E?.initialAutoProcessingError?.type==="3ds_required"&&!E.initialAutoProcessingError.threeDSecureToken&&E.initialAutoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:E.initialAutoProcessingError.nextActionRedirectUrl}:null,J,ue=Se=>(Ve(),sn(pe=>Co(Se,{billingApiUrl:x,sessionId:F,nonce:z,session:T,signal:pe})));if(k)J=await ue(k);else if(y)Ve(),y.type==="paypal_redirect_required"&&kt.current?.publishableKey&&Vl({sessionId:F,publishableKey:kt.current.publishableKey,paypalPublishableKey:kt.current.paypalPublishableKey}),J=await sn(Se=>Fa(y,{flopay:qe.current,paypalFlopay:Yt.current,attempt3DS:E?.attempt3DS,billingApiUrl:x,sessionId:F,session:T,telemetry:!1,signal:Se})),y.type==="paypal_redirect_required"&&ts();else if(E?.initialAutoProcessingPending){let Se=E.initialAutoProcessingPending,pe=new Ua(x,{telemetry:!1}),Ge=await sn(qn=>pe.waitForCheckoutSessionCompletion(Se.sessionId,{initialDelayMs:Se.retryAfterMs,nonce:z,statusUrl:Se.statusUrl,signal:qn})),ht=Ge.data.session,tn=Ge.autoProcessingError?.type==="3ds_required"&&Ge.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:Ge.autoProcessingError.nextActionRedirectUrl}:null;if(tn)J=await ue(tn);else{if(!Mr(ht))throw po(ht);J=Sr(ht,F)}}else{if(E?.initialAutoProcessingError)throw gr(E.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:E.initialAutoProcessingError.checkoutMethod});if(E?.fromCreateSession)return E?.fallbackToFull&&(Dn("full"),Hl("full")),!1;{let Se=await So({billingApiUrl:x,sessionId:F,session:T,nonce:z,telemetry:!1});Se.type==="success"?J=Se.result:Se.type==="next_action_required"?J=await ue(Se):(Ve(),Se.type==="paypal_redirect_required"&&kt.current?.publishableKey&&Vl({sessionId:F,publishableKey:kt.current.publishableKey,paypalPublishableKey:kt.current.paypalPublishableKey}),J=await sn(pe=>Fa(Se,{flopay:qe.current,paypalFlopay:Yt.current,attempt3DS:E?.attempt3DS,billingApiUrl:x,sessionId:F,session:T,telemetry:!1,signal:pe})),Se.type==="paypal_redirect_required"&&ts())}}F&&bo(F),Ce(),I&&(g.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),g.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),g.terminal({outcome:J.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),zt(J.status==="authorized"),wt("success"),await na(600),ne=()=>Gt.current?.(J)}catch(y){let k=Qo(y);if(k.code==="three_ds_aborted")return!1;let J=k.checkoutMethod??Xo;St(k.message),mt(k.message),zt(!1),E?.fallbackToFull&&(g.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),Dn("full"),Hl("full")),Ce();let ue=k.statusCode===void 0?void 0:bu(k.statusCode,"unknown"),Se=ue==="4xx"?{requestCategory:"process_payment",statusClass:ue}:{},pe=ue===void 0||ue==="4xx";if(pe&&(k.telemetryOutcome==="payment_declined"||!!(k.declineCode||k.code?.toLowerCase().includes("declin"))))g.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...Se});else if(pe&&(k.telemetryOutcome==="validation_rejected"||k.type==="validation_error"))g.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...Se});else{let tn=Gl(y,I?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown"),qn=k.telemetryRequestCategory??"process_payment";$t.current=!0;try{g.error({...tn,...k.telemetryFailureCategory?{failureCategory:k.telemetryFailureCategory}:{},stage:I?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:qn})}finally{$t.current=!1}Re({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:qn,provider:it})}return Bt(()=>Vn.current?.(k)),Ln(J,k,{code:k.code,declineCode:k.declineCode}),wt("error"),await Promise.allSettled([na(400),E?.ensureProvidersReady?E.ensureProvidersReady():Promise.resolve()]),I&&(g.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),g.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{Ce(),A&&ra(A),wt(null),mt(null)}return Bt(ne),!0},[Ln,Re,t,x,sn,o,xt]);ur(()=>{if(typeof window>"u"||M.current)return;let T=new URLSearchParams(window.location.search),E=T.get("payment_intent_client_secret");if(!E)return;let F=Iu();F&&(M.current=!0,(async()=>{let z,it=0;St(null),mt(null),wt("processing"),je(!0);try{if(T.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:R,paypalFlopay:d}=await xi({publishableKey:F.publishableKey,paypalPublishableKey:F.paypalPublishableKey,billingApiUrl:x,locale:s,telemetry:o});z=Qt(d??R),z?.setCheckoutContext(xt),it=z?.now()??0,z?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),z?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let A=(d??R)?.getRawProvider();if(!A)throw Object.assign(new bn("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:g,error:P}=await A.retrievePaymentIntent(E);if(P)throw Object.assign(new bn(P.message??"Failed to retrieve PayPal payment status.","api_error",{code:P.code}),{checkoutMethod:"paypal"});let I=Ys(g?.status);if(!g||I==="failed")throw Object.assign(new bn("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let v=typeof g.payment_method=="string"?g.payment_method:g.payment_method?.id,q=I;if(F.sessionId){let Ce=(await new Ua(x,{telemetry:!1}).getUnifiedCheckoutSession(F.sessionId)).data.session;if(Ce&&Ce.status!=="complete"){let ne=await So({billingApiUrl:x,sessionId:F.sessionId,session:Ce,telemetry:!1,tokenizedData:{id:v??g.id,type:"card",threeDSecureActionResultTokenId:g.id,isPaypal:!0}});if(ne.type!=="success")throw Object.assign(new bn("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});q=ne.result.status}}F.sessionId&&bo(F.sessionId),z?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),z?.performance({stage:"redirect_resume",durationMs:z.elapsed(it),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),z?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),wt("success"),await na(600),Bt(()=>Gt.current?.({status:q,paymentIntentId:g.id,paymentMethodId:v,checkoutMethod:"paypal"}))}catch(R){let d=Qo(R),A=d.checkoutMethod??"paypal",g=!!(d.declineCode||d.code?.toLowerCase().includes("declin"));if(z)z.performance({stage:"redirect_resume",durationMs:z.elapsed(it),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),g?z.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):z.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(g){let P=ja(x,o,xt);P.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),ra(P)}else Zi(x,o,xt,"REDIRECT_RESUME_FAILED","redirect_resume");St(d.message),mt(d.message),Bt(()=>Vn.current?.(d)),Ln(A,d,{code:d.code,declineCode:d.declineCode}),wt("error"),await na(400)}finally{ts(),ku(),wt(null),mt(null),je(!1)}})())},[Ln,s,x,o,xt]);let Gn=Rt(null),yt=tr(()=>Dt?Po(Dt):"",[Dt]),En=Rt(Dt);En.current=Dt,ur(()=>{Et(e??"")},[e]),ur(()=>{se.current=!1,St(dt),mt(null),zt(!1),wt(null)},[yt,dt,e]);async function Yn(T,E,F){let z=ja(x,o,xt),it=new Ua(x,{telemetry:!1}),R=!1;try{let d=T.idempotencyKey===void 0?void 0:ql(T.idempotencyKey),A=wi(E,F),g=Ii(E,F);A?.canonicalIdentity===F&&g&&g.canonicalIdentity===void 0&&(Ta(E,F,g.idempotencyKey),g={...g,canonicalIdentity:F});let P=d??(g?.canonicalIdentity===F?g.idempotencyKey:void 0),I,v=!1;z.log({name:A?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let q=A?.sid??null,Ve=null,Nt,Ce,ne=!1;if(q)try{Ve=await it.getUnifiedCheckoutSession(q,A?.nonce),A&&A.canonicalIdentity===void 0&&(ll(Ve.data.session,T)?(Ea(E,F,q,A.nonce??Ve.data.session?.clientSecret),g&&g.canonicalIdentity===void 0&&(Ta(E,F,g.idempotencyKey),P??(P=g.idempotencyKey))):(Ra(E,F),g=null,P=d,q=null,Ve=null));let k=Ve?.data.session?.status,J=Ve?.data.session,ue=J?.clientSecret||A?.nonce;if(q&&J?.buyerIdentified===!1&&ue&&(Ce=uo(it,q,ue,T.account)),q&&Ve&&k==="complete"){if(ki(q))return{sid:q,result:Ve};Ra(E,F),q=null,Ve=null,v=!0}}catch{z.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),A?.canonicalIdentity===void 0?(Ra(E,F),P=d):_a(E,F),q=null}if(!q){!d&&(v||!P)&&(P=ql(),I=P),P&&Ta(E,F,P);let k=z.now(),J=0;z.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let ue={...T,idempotencyKey:P,avsCheck:!!we,avsConfig:typeof we=="object"?we:void 0,checkoutType:"embedded_checkout",checkoutLayout:ns(V,ce)};Object.defineProperty(ue,fu,{configurable:!1,enumerable:!1,value:{onAttempt:Ge=>{J=Math.max(J,Ge)}}});let Se=()=>{$l(z,"session_create",k,J)},pe=Ge=>{Kl(z,Ge,"session_create",k,J)&&Re({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_create"})};try{if(hu(ue)){let Ge=await it.createDetachedSession(ue);Ge.claimed.catch(()=>{}),Ve=Ge.shell,q=Ge.sessionId,Ce=Ge.claim;let ht=z.now();z.log({name:"session.claim.started",stage:"session_claim",requestCategory:"session_claim"}),Nt=Ge.claimed.then(tn=>{let qn=tn.data.session?.id??Ge.sessionId;return qn&&Ea(E,F,qn,tn.data.session?.clientSecret??Ge.nonce),$l(z,"session_claim",ht),Se(),tn},tn=>{throw _a(E,F),Kl(z,tn,"session_claim",ht,0)&&Re({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_claim"}),tn}).finally(()=>ra(z)),Nt.catch(()=>{}),R=!0,z.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),z.performance({stage:"session_shell",durationMs:z.now()-k,durationMode:"machine",requestCategory:"session_create",attempt:J,statusClass:"2xx",paymentMethodCategory:"card"})}else Ve=await it.createAndFetchSession(ue),Se()}catch(Ge){throw pe(Ge),Ge}q=Ve.data.session?.id??q??"",q&&!Nt&&Ea(E,F,q,Ve.data.session?.clientSecret)}let y=Ve?.data.session;return!Ce&&q&&y?.buyerIdentified===!1&&y.clientSecret&&(Ce=uo(it,q,y.clientSecret,T.account)),{sid:q??"",result:Ve,sdkGeneratedIdempotencyKey:I,...Nt?{claimed:Nt}:{},...Ce?{claim:Ce}:{},...ne?{claimRequiresIdentity:!0}:{}}}finally{R||ra(z)}}let ir=Rt(Yn);Uo(()=>{ir.current=Yn},[Yn]);let gn=Pn(async(T,E)=>{let F=En.current;if(!F)throw new bn("createSession is required to bootstrap checkout.","validation_error");let z=di(F,T),it=Po(z),R=sl(z),d=$a.get(it);if(!d){let P={canonicalIdentity:it,promise:ir.current(z,R,it),consumers:0,settled:!1};d=P,$a.set(it,P);let I=()=>{P.settled=!0,jl(it,P)};P.promise.then(I,I)}d.consumers+=1;let A=!1,g=()=>{A||(A=!0,d.consumers-=1,jl(it,d))};E?.(g);try{let P=await d.promise;Gn.current=it,T&&(Sn(or),Ut(y=>Hs(y,T)));let{sid:I,result:v,claimed:q,claim:Ve,claimRequiresIdentity:Nt}=P;if(nr.current=Ve,Ht(Nt===!0),Ae(v),v.data.session&&Je(v.data.session),I&&Et(I),q){an.current+=1;let y=an.current;Kt.current=q,on(!0),q.then(k=>{an.current===y&&(Kt.current===q&&(Kt.current=null),Ae(k),k.data.session&&Je(k.data.session),on(!1),Ht(!1))},k=>{an.current===y&&(Kt.current===q&&(Kt.current=null),on(!1),Ht(!1),pn(k instanceof bn?k:new bn(k instanceof Error?k.message:"Failed to create session","api_error")))})}else an.current+=1,Kt.current=null,on(!1),Ht(!1);let{flopay:Ce,paypalFlopay:ne}=await es(v,{billingApiUrl:x,locale:s,telemetry:o});return Hn(Ce,ne),Ot(!1),P}catch(P){throw Gn.current===it&&(Gn.current=null),P}finally{E||g()}},[or,Hn,s,x,o]),We=Rt(Wn);We.current=Wn;let hn=Rt(gn);hn.current=gn;let ln=Pn(async T=>{if(!Ru(T)||wn)return{sessionId:Ct,session:H};It(!0);try{let E=await gn(T);return{sessionId:E.sid,session:E.result.data.session??null}}finally{It(!1)}},[gn,wn,Ct,H]),On=Pn(async T=>{let E=nr.current;if(!E)return;let F=an.current,z=await E(T);an.current===F&&(Ae(z),z.data.session&&Je(z.data.session))},[]),br=Pn(async()=>{await Kt.current},[]),qr=Pn(async()=>(await br(),{proceed:!0}),[br]);ur(()=>{let T=!1,E,F=++Ee.current;Pr(),pn(null),_n(0);let z=()=>{T=!0,Ee.current===F&&(Ee.current+=1,Pr())},it=En.current;if(yt&&it)return Dn(ar),Ot(!1),Gn.current===yt?z:(Je(Ws(it,de)),(async()=>{let A=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),g=ar==="auto"&&!se.current&&!A;g&&(St(null),mt(null),wt("processing"));try{let P=await hn.current(void 0,Ve=>{E=Ve}),I=P.result.data.session??null;kt.current=Ai(P.result);let v=Qi(P.result),q=ki(P.sid||I?.id);if(!T&&g&&I&&!v&&!q){se.current=!0,await Cu(yt,P.sdkGeneratedIdempotencyKey,()=>We.current(I,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:P.result.autoProcessingError,initialAutoProcessingPending:P.result.autoProcessingPending,autoProcessingAttempted:P.result.autoProcessingAttempted,sessionId:P.sid||I.id}));return}!T&&g&&((v||q)&&(se.current=!0),wt(null),mt(null))}catch(P){if(T)return;let I=va(P);if(g&&I==="session_auto_completed"){se.current=!0,wt("success"),await na(600),T||(Bt(()=>{Gt.current?.({status:"succeeded"})}),wt(null),mt(null));return}g&&(wt(null),mt(null));let v=P instanceof bn?P:new bn(P instanceof Error?P.message:"Failed to create session","api_error");pn(v)}finally{E?.(),E=void 0}})(),()=>{z(),E?.()});Ot(!0);async function R(){let A=!1,g=null;try{let P=new Ua(x,{telemetry:!1}),I=await P.getUnifiedCheckoutSession(pt,t);if(g=I,T)return;Ae(I);let v=I.data.session??null;if(Je(v),!v)throw new bn("No session data returned","api_error");let q=v.checkoutMode;if(q==="setup")throw new bn("This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.","validation_error",{code:"InvalidCardSetupSurface",param:"sessionId"});if(v.status==="authorized"){Ot(!1),Bt(()=>{Gt.current?.(Sr(v,pt)),rr.current?.(v.successUrl??"")});return}if(v.status==="complete"){Ot(!1),Bt(()=>{rr.current?.(v.successUrl??"")});return}if(v.status==="expired")throw ha(v);A=!0;let Ve=de??q??"full";Dn(Ve),an.current+=1;let Nt=v.clientSecret||t;nr.current=v.buyerIdentified===!1&&Nt?uo(P,pt,Nt,{...v.customer?.id?{userId:v.customer.id}:{}}):void 0,on(!1),Ht(!1);let Ce=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),ne=Qi(I);if(Ve==="auto"&&!se.current&&!Ce&&!ne){se.current=!0;let y=d(I);try{if(await We.current(v,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>y,sessionId:pt||v.id}),T)return;await y,T||Ot(!1);return}catch{if(T)return;await y,T||Ot(!1);return}}await d(I),T||Ot(!1)}catch(P){if(T)return;let I=Vs(P,A);if(A&&Re({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"}),I){let{errorCode:q,stage:Ve,...Nt}=I;Zi(x,o,xt,q,Ve,Nt)}if(I?.stage==="provider_load"&&(de??g?.data.session?.checkoutMode??"full")==="full"&&Ks(g,ae,Y)){let q=wu({billingApiUrl:x,locale:s,telemetry:o});ke.current=q,Hn(q,null),_n(1),Ot(!1);return}let v=P instanceof bn&&I?.stage!=="provider_load"?P:$s();v!==P&&Bt(()=>Vn.current?.(v)),pn(v),Ot(!1)}}async function d(A){let{flopay:g,paypalFlopay:P,...I}=await es(A,{billingApiUrl:x,locale:s,telemetry:o});kt.current={publishableKey:I.publishableKey,paypalPublishableKey:I.paypalPublishableKey},Hn(g,P),_n(0)}return R(),z},[de,yt,ar,un,t,ae,Y]);let Cr=Pn(async()=>{if(!L||mn!==1)return;let T=Ee.current;_n(2);try{let{flopay:E,paypalFlopay:F}=await es(L,{billingApiUrl:x,locale:s,telemetry:o});if(Ee.current!==T)return;Pr(),Hn(E,F),_n(0)}catch(E){if(Ee.current!==T)return;let{errorCode:F,stage:z,...it}=li(E);Zi(x,o,xt,F,z,it)}},[Pr,Hn,s,mn,x,o,xt,L]),zn=!!(pt&&(H?.clientSecret||t)),vn=Jt||!zn,Xr=Pn(async()=>{if(!(Jt||!zn||!H)){je(!0),St(null);try{await Wn(H,{attempt3DS:!0,fallbackToFull:!0,sessionId:pt||H.id})}finally{je(!1)}}},[pt,Jt,zn,Wn,H]),Tn=Xl(L,U),Tr=Qi(L),In=tr(()=>{if(!(!L||!H||!L.data.stripe?.publishableKey))return{billingApiUrl:x}},[L,H,x]),Un=!!(n&&!V&&ce==="buttons"&&ye&&ar==="full"),et=!!(pt&&(H?.vault?.html||Ar(H))),Jn=tr(()=>({session:H,loading:O,error:Cn,checkoutMode:Fn,inlineSessionDraft:Dt,applyInlineSessionPatch:Un?ln:void 0,inlineSessionPatchProcessing:wn,claimPending:te,claimRequiresIdentity:Kn,claimBuyerIdentity:On,waitForDataAttachment:br}),[H,O,Cn,Fn,Dt,Un,ln,wn,te,Kn,On,br]),Xt=!!n&&ce==="buttons"&&!Tr&&!et&&(!xe||!In),_t=rn?oe(fr,{status:rn,errorMessage:$n,authorized:Tt}):null;if(O&&!et){if(l)return en(vr,{children:[l,_t]});if(ce==="buttons"){let T=at?.buttonsLayout?.cardButton?.borderRadius??at?.appearance.variables?.borderRadius??8,E=F=>oe("div",{style:{height:F,borderRadius:T,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return en(vr,{children:[en("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[ae&&E(ko),Y&&(S||G)&&E(ko),Y&&E(ko),oe("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),_t]})}return en(vr,{children:[en("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[oe("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),oe("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),_t]})}return Cn?p?oe(cr.Provider,{value:Jn,children:p(Cn)}):oe(cr.Provider,{value:Jn,children:oe("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:Cn.message})}):Xt?en(vr,{children:[oe(cr.Provider,{value:Jn,children:oe(Tu,{onButtonClick:De,showPayPal:ae,showStripe:Y,showApplePay:S,showGooglePay:G,theme:Te,buttonsTheme:Fe,buttonsStyles:ve,cardButtonContent:Ue,cardBackButtonContent:bt,cardTitleContent:ot})}),_t]}):Tr&&H&&Tn?en(vr,{children:[oe(cr.Provider,{value:Jn,children:en("div",{className:ct,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[He&&oe(ho,{icon:!1,children:He}),Nn==="retrying"&&oe("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),Nn==="exhausted"&&en("div",{role:"alert",children:[oe("div",{children:"PayPal is temporarily unavailable. Please try again."}),oe("button",{type:"button",onClick:Ur,children:"Retry PayPal"})]}),Nn!=="exhausted"&&oe("div",{"aria-hidden":Nn==="retrying"?!0:void 0,style:Nn==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:oe(al,{sessionId:pt,nonce:H.clientSecret||void 0,billingApiUrl:x,email:H.customer?.email||Dt?.account?.email,billingName:[H.customer?.firstName,H.customer?.lastName].filter(Boolean).join(" ")||[Dt?.account?.firstName,Dt?.account?.lastName].filter(Boolean).join(" ")||void 0,onBuyerIdentityReady:On,clientId:Tn.clientId,environment:Tn.environment,currency:(H.currency??"usd").toUpperCase(),isSubscription:H.mode==="subscription",providerObjectType:Tn.providerObjectType,approvalPresentation:Tn.approvalPresentation,existingOrderId:Tn.existingOrderId,onComplete:f,onErrorChange:St,onDecline:m,onButtonClick:De,runBeforeButtonClick:qr,onInitializationStateChange:zr,allowAutomaticRetry:Le===0,session:H,telemetry:o,telemetryContext:xt,onInstrument:N,debug:X},`${K}:paypal-init-${Le}`)})]})}),_t]}):Fn==="confirm"?en(vr,{children:[oe(cr.Provider,{value:Jn,children:oe(Aa,{flopay:xe,paypalFlopay:ee,options:In??{billingApiUrl:x},onInstrument:N,children:en("div",{className:ct,children:[He&&oe("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:He}),ut?ut({onConfirm:Xr,isProcessing:vn}):oe("button",{type:"button",onClick:Xr,disabled:vn,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:vn?"not-allowed":"pointer",opacity:vn?.6:1},children:Jt?"Processing...":fe??"Confirm Purchase"})]})},K)}),_t]}):(!xe||!In)&&!(et&&Fn==="full")?oe(vr,{children:_t}):en(vr,{children:[oe(cr.Provider,{value:Jn,children:en(Aa,{flopay:xe,paypalFlopay:ee,options:In??{billingApiUrl:x},onInstrument:N,children:[mn===1&&oe("button",{type:"button",onClick:Cr,children:"Retry payment methods"}),V?en(vr,{children:[He&&oe("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:He}),oe(Eu,{sessionId:pt,nonce:H?.clientSecret||void 0,billingApiUrl:x,session:H,submitLabel:be,children:V})]}):oe(Ji,{sessionId:pt,nonce:H?.clientSecret||void 0,telemetry:o,email:H?.customer?.email||Dt?.account?.email,userId:H?.customer?.id||Dt?.account?.userId,firstName:H?.customer?.firstName||Dt?.account?.firstName,lastName:H?.customer?.lastName||Dt?.account?.lastName,totalAmount:H?Math.round(gu(H).total*100):0,currency:H?.currency?.toLowerCase()??"usd",onComplete:f,onError:C,onDecline:m,error:He,onErrorChange:St,showPayPal:ae,showStripe:Y,enabledPaymentMethods:mn?[]:Pe??L?.data.stripe?.enabledPaymentMethods??H?.gateways?.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:L?.data.stripe?.enabledPaymentMethodCountries,showApplePay:S,showGooglePay:G,layout:ce,theme:Te,buttonsTheme:Fe,buttonsStyles:ve,appearance:Ye,cardButtonContent:Ue,cardBackButtonContent:bt,cardTitleContent:ot,onButtonClick:De,onBeforeButtonClick:ye,onBuyerIdentityReady:On,enableAVS:we,...Qe?{cardFieldOrder:Qe}:{},...Z?{cardPreFormSlot:Z}:{},avsLayout:Ie,country:H?.customer?.country,city:H?.customer?.city,state:H?.customer?.state,onCountryChange:w,onZipChange:_,avsCheck:!!we,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:ns(V,ce),className:ct,submitLabel:be,directPaypal:Tn,isSubscription:H?.mode==="subscription",session:H,dataAttachmentPending:te,dataAttachmentRequiresIdentity:Kn,debug:X})]},K)}),_t]})}function Eu({sessionId:e,nonce:t,billingApiUrl:n,session:r,submitLabel:o,children:i}){return oe(vr,{children:Xi.Children.map(i,s=>{if(!Xi.isValidElement(s))return s;let l=s.props,p={};return l.sessionId||(p.sessionId=e),!l.nonce&&t&&(p.nonce=t),l.billingApiUrl||(p.billingApiUrl=n),l.submitLabel===void 0&&o!==void 0&&(p.submitLabel=o),r?.customer&&(l.email||(p.email=r.customer.email),l.userId||(p.userId=r.customer.id),l.firstName||(p.firstName=r.customer.firstName),l.lastName||(p.lastName=r.customer.lastName)),Object.keys(p).length===0?s:Xi.cloneElement(s,p)})})}function Tu({onButtonClick:e,showPayPal:t,showStripe:n=!0,showApplePay:r,showGooglePay:o,theme:i,buttonsTheme:s,buttonsStyles:l,cardButtonContent:p,cardBackButtonContent:f,cardTitleContent:C}){let[h,m]=jt(!1),w=tr(()=>Yl(i),[i]),_=tr(()=>{let S=w?.buttonsLayout??Pu(s);return l?{...S,...l,cardButton:{...S.cardButton,...l.cardButton},cardFormContainer:{...S.cardFormContainer,...l.cardFormContainer},backButton:{...S.backButton,...l.backButton},backButtonIcon:{...S.backButtonIcon,...l.backButtonIcon},submitButton:{...S.submitButton,...l.submitButton},title:{...S.title,...l.title}}:S},[w,s,l]),ae=w?.buttonsLayout?.cardButton?.borderRadius??w?.appearance.variables?.borderRadius??8,Y=S=>oe("div",{style:{height:S,borderRadius:ae,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),Pe=p===void 0?{boxSizing:"border-box",height:ko,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(h){let S=_.cardInputBorder??"#e5e7eb",G=_.cardInputBackground??"white",X=io(f),ce=io(C);return en("div",{style:{backgroundColor:_.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",..._.cardFormContainer},children:[en("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[en("button",{type:"button",onClick:()=>m(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:X?0:"0.5rem",background:"none",border:"none",color:"#4b5563",fontSize:"0.85rem",fontWeight:500,padding:0,flexShrink:0,opacity:1,cursor:"pointer",..._.backButton},children:[oe("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",..._.backButtonIcon},children:oe("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:oe("path",{d:"M15 18l-6-6 6-6"})})}),oe(lo,{content:f})]}),ce?oe("div",{style:{flex:1}}):oe("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,..._.title},children:oe(jo,{content:C})})]}),oe("div",{style:{backgroundColor:G,border:`1px solid ${S}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:oe("div",{style:{width:"60%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),en("div",{style:{display:"flex"},children:[oe("div",{style:{flex:1,backgroundColor:G,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${S}`,borderLeft:`1px solid ${S}`,borderBottomLeftRadius:8,padding:12,height:45},children:oe("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),oe("div",{style:{flex:1,backgroundColor:G,borderTop:"none",borderRight:`1px solid ${S}`,borderBottom:`1px solid ${S}`,borderLeft:`1px solid ${S}`,borderBottomRightRadius:8,padding:12,height:45},children:oe("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),oe("div",{style:{backgroundColor:G,border:`1px solid ${S}`,borderRadius:8,marginTop:8,padding:12,height:45},children:oe("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),oe("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",..._.submitButton,opacity:.5}}),oe("style",{children:`
|
|
33
|
+
`}),qo&&$r&&Oe("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:A?-2:0},children:[Oe("button",{type:"button",onClick:Kn,style:{display:"inline-flex",alignItems:"center",gap:mi?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:j.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...j.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",...j.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(yo,{content:wt})]}),js?d("div",{style:{flex:1}}):d("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:j.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...j.title},children:d(Go,{content:fe})})]}),!qo&&!js&&d("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:fi,order:A?-3:0,...j.title},children:d(Go,{content:fe})}),A&&N&&d("div",{style:{order:-2,width:"100%"},children:N}),A&&ht&&Oe("div",{"data-testid":"flopay-vault-identity-fields",style:{order:-1,marginTop:"0.5rem"},children:[d("div",{style:{backgroundColor:so,border:`1px solid ${er(wa)}`,borderRadius:$t,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:En,onChange:a=>{It("email"),Wt.current=a.target.value,Hn(a.target.value)},onPointerDown:()=>It("email"),onKeyDown:()=>It("email"),onBlur:()=>{Un("email")&&Tn(!0),Mn||oi()},disabled:_e,required:!0,"aria-invalid":wa||void 0,"aria-describedby":wa?"flopay-buyer-email-error":void 0,"data-testid":"flopay-email",style:{width:"100%",border:"none",outline:"none",background:"transparent",...gi}})}),wa&&d("div",{id:"flopay-buyer-email-error",role:"alert","data-testid":"flopay-email-error",style:$o,children:je.empty?"Email address is required":"Enter a valid email address"})]}),X&&d("div",{style:{order:A?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let a=Ut,h=(J=!1)=>({backgroundColor:so,border:`1px solid ${er(J)}`,borderRadius:$t,marginTop:"0.5rem",padding:"10px"}),D=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...gi}),Pe=qd(a);return Oe(Qr,{children:[at(X.address_line_1,a)&&Oe(Qr,{children:[d("div",{style:h(Lt("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:Nn,onChange:J=>{It("line1"),Tt.current.addressLine1=!0,Mt.current=J.target.value,vn(J.target.value)},onPointerDown:()=>It("line1"),onKeyDown:()=>It("line1"),onBlur:()=>lr("line1"),disabled:_e,required:!0,"aria-invalid":Lt("line1")||void 0,"aria-describedby":Lt("line1")?"flopay-billing-address-line1-error":void 0,"data-testid":"flopay-address-line1",style:D()})}),Lt("line1")&&d("div",{id:"flopay-billing-address-line1-error",role:"alert","data-testid":"flopay-address-line1-error",style:$o,children:"Street address is required"})]}),at(X.address_line_2,a)&&d("div",{style:h(),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:Vt,onChange:J=>{Tt.current.addressLine2=!0,yn.current=J.target.value,De(J.target.value)},disabled:_e,"data-testid":"flopay-address-line2",style:D()})}),(at(X.city,a)||at(X.state,a))&&Oe("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[at(X.city,a)&&d("div",{style:{flex:1,backgroundColor:so,borderTop:`1px solid ${er(Lt("city"))}`,borderRight:`1px solid ${er(Lt("city"))}`,borderBottom:`1px solid ${er(Lt("city"))}`,borderLeft:`1px solid ${er(Lt("city"))}`,padding:"10px",borderTopLeftRadius:$t,borderBottomLeftRadius:$t,...at(X.state,a)?{borderRight:"none",borderTopRightRadius:0,borderBottomRightRadius:0}:{borderRadius:$t}},children:d("input",{className:"flopay-shared-input",id:"flopay-billing-city",name:"billing-city",placeholder:"City",autoComplete:"billing address-level2",value:we,onChange:J=>{It("city"),Tt.current.city=!0,Zt.current=J.target.value,Ln(J.target.value)},onPointerDown:()=>It("city"),onKeyDown:()=>It("city"),onBlur:()=>lr("city"),disabled:_e,required:!0,"aria-invalid":Lt("city")||void 0,"aria-describedby":Lt("city")?"flopay-billing-city-error":void 0,"data-testid":"flopay-city",style:D()})}),at(X.state,a)&&d("div",{style:{flex:1,backgroundColor:so,borderTop:`1px solid ${er(Lt("state"))}`,borderRight:`1px solid ${er(Lt("state"))}`,borderBottom:`1px solid ${er(Lt("state"))}`,borderLeft:`1px solid ${er(Lt("state"))}`,padding:"10px",borderTopRightRadius:$t,borderBottomRightRadius:$t,...at(X.city,a)?{borderTopLeftRadius:0,borderBottomLeftRadius:0,borderLeft:`1px solid ${er(Lt("state")||Lt("city"))}`}:{borderRadius:$t}},children:Pe?Oe("select",{id:"flopay-billing-state",name:"billing-state",value:St,onChange:J=>{It("state"),Tt.current.state=!0,qt.current=J.target.value,bn(J.target.value)},onPointerDown:()=>It("state"),onKeyDown:()=>It("state"),onBlur:()=>lr("state"),disabled:_e,autoComplete:"billing address-level1",required:!0,"aria-invalid":Lt("state")||void 0,"aria-describedby":Lt("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:{...D(),cursor:"pointer"},children:[d("option",{value:"",children:Ki(a)}),Pe.map(J=>d("option",{value:J.code,children:J.name},J.code))]}):d("input",{className:"flopay-shared-input",id:"flopay-billing-state",name:"billing-state",placeholder:Ki(a),autoComplete:"billing address-level1",value:St,onChange:J=>{It("state"),Tt.current.state=!0,qt.current=J.target.value,bn(J.target.value)},onPointerDown:()=>It("state"),onKeyDown:()=>It("state"),onBlur:()=>lr("state"),disabled:_e,required:!0,"aria-invalid":Lt("state")||void 0,"aria-describedby":Lt("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:D()})})]}),Lt("city")&&d("div",{id:"flopay-billing-city-error",role:"alert","data-testid":"flopay-city-error",style:$o,children:"City is required"}),Lt("state")&&Oe("div",{id:"flopay-billing-state-error",role:"alert","data-testid":"flopay-state-error",style:$o,children:[Ki(a)," is required"]}),(at(X.country,a)||at(X.postal_code,a))&&Oe("div",{style:{display:"flex",flexDirection:ue==="column"?"column":"row",gap:ue==="column"?"0.5rem":"0",marginTop:"0.5rem"},children:[at(X.country,a)&&d("div",{style:{flex:ue==="row"?1:void 0,backgroundColor:so,borderTop:`1px solid ${jo}`,borderRight:`1px solid ${jo}`,borderBottom:`1px solid ${jo}`,borderLeft:`1px solid ${jo}`,padding:"10px",...ue==="row"&&at(X.postal_code,a)?{borderRadius:"0",borderTopLeftRadius:$t,borderBottomLeftRadius:$t,borderRight:"none"}:{borderRadius:$t}},children:d("select",{id:"flopay-billing-country",name:"billing-country",value:Ut,onChange:J=>{Tt.current.country=!0,kt.current=J.target.value,gn(J.target.value),Ye?.(J.target.value),qt.current="",bn("")},disabled:_e,autoComplete:"billing country","data-testid":"flopay-country",style:{...D(),cursor:"pointer"},children:Nd.map(J=>Oe("option",{value:J.code,children:[J.flag," ",J.name]},J.code))})}),at(X.postal_code,a)&&d("div",{style:{flex:ue==="row"?1:void 0,backgroundColor:so,border:`1px solid ${Ic}`,padding:"10px",...ue==="row"&&at(X.country,a)?{borderRadius:"0",borderTopRightRadius:$t,borderBottomRightRadius:$t}:{borderRadius:$t}},children:d("input",{className:"flopay-shared-input",id:"flopay-billing-postal-code",name:"billing-postal-code",placeholder:Zi(Ut),autoComplete:"billing postal-code",value:hn,onChange:J=>{It("zip"),Tt.current.zip=!0,ln.current=J.target.value,kn(J.target.value),He?.(J.target.value)},onPointerDown:()=>It("zip"),onKeyDown:()=>It("zip"),onBlur:()=>{Un("zip")&&Er(!0)},disabled:_e,required:zn.required,"aria-invalid":Sa||void 0,"aria-describedby":Sa?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:D()})})]}),Sa&&d("div",{id:"flopay-billing-postal-code-error",role:"alert","data-testid":"flopay-zip-error",style:$o,children:zn.empty?`${Zi(a)} is required`:bu(a)})]})})()}),A&&Ac,ie&&d(Co,{margin:"0.75rem 0",styleOverride:j.errorBanner,children:ie})]}),ka={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"},Ws=a=>_?!I||!Cr?d("pre",{"data-testid":a,style:ka,children:"FloPay/DirectPayPal-debug - not enabled"}):d("pre",{"data-testid":a,style:ka,children:["FloPay/DirectPayPal-debug (parent gate)",` showPayPal=${I}`,` directPaypalConfigured=${Cr}`,` inAppBrowserDetected=${String(ba)}`,` shouldRenderDirectPayPal=${No}`,` shouldRenderStripePayPal=${Lo}`,` hasPaypalStripeInstance=${!!to}`].join(`
|
|
34
|
+
`)}):null,Gs=a=>_?!G||!on?d("pre",{"data-testid":a,style:ka,children:"FloPay/Stripe-debug - not enabled"}):d("pre",{"data-testid":a,style:ka,children:["FloPay/Stripe-debug (parent gate)",` showStripe=${G}`,` currency=${oe}`,` amountInCents=${Fo}`,` enabledPaymentMethods: ${JSON.stringify(Y??[])}`,` enabledPaymentMethodsProvided=${Do}`,` hasEnabledMethods=${ga}`,` expressMethods: ${JSON.stringify(ha)}`,` walletExpressMethods: ${JSON.stringify(ao)}`,` paymentElementMethods: ${JSON.stringify(Oo)}`,` paymentElementMethodsForCurrency: ${JSON.stringify(va)}`,` hasStripeInstance=${!!on}`,` shouldRenderWallets=${io}`,` shouldRenderPaymentElement=${zo}`].join(`
|
|
35
|
+
`)}):null,Ys=nt==="apm-expanding"||nt==="apm-form"||nt==="apm-collapsing",co;nt==="apm-expanding"?co=zl:nt==="apm-collapsing"&&(co=Ul);let Ia=cn?ec(si,cn):null;if(Ce==="buttons"){let a=nt==="buttons"||nt==="expanding"||nt==="apm-expanding",h=nt==="expanding"||nt==="card"||nt==="collapsing",D=Me===void 0?{boxSizing:"border-box",height:Ya,padding:"0 1rem"}:{padding:"0.9rem 1rem"},Pe;nt==="expanding"||nt==="apm-expanding"?Pe=mu:(nt==="collapsing"||nt==="apm-collapsing")&&(Pe=yu);let J;return nt==="expanding"?J=zl:nt==="collapsing"&&(J=Ul),Oe("form",{onSubmit:ui,className:R,noValidate:!0,style:{position:"relative"},children:[d(Xi,{}),S&&d(wr,{status:S,errorMessage:ie,authorized:en}),Oe("div",{style:{display:"grid"},children:[Oe("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!a&&!Pe?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!a&&!Pe?gu:{},...Pe?{animation:Pe,pointerEvents:"none"}:{}},children:[Ws("flopay-direct-paypal-gate-debug"),Gs("flopay-stripe-gate-debug"),No&&Je&&Oe(Qr,{children:[E&&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(ea.Provider,{value:w,children:d(Oa,{sessionId:e,nonce:t,billingApiUrl:We,email:T.email,billingName:U||void 0,onBuyerIdentityReady:B,clientId:Je.clientId,environment:Je.environment,currency:oe.toUpperCase(),isSubscription:lt,providerObjectType:ze,approvalPresentation:Pa==="popup"?void 0:Pa,onTokenizedBody:Bn,onComplete:s,onErrorChange:me,onDecline:y,onTechnicalFailure:oo,onButtonClick:O,runBeforeButtonClick:dr,isProcessing:_e,onLoadStateChange:li,onInitializationStateChange:ci,session:ft,existingOrderId:E?.orderId,debug:_},E?.orderId??"fresh")})]}),Lo&&d(Zr,{stripe:to,options:Ps,children:d(Kl,{sessionId:e,nonce:t,email:T.email,billingName:U||void 0,onBuyerIdentityReady:B,billingApiUrl:We,onTokenizedBody:Bn,onErrorChange:me,isProcessing:_e,onButtonClick:O,onDecline:y,onTechnicalFailure:oo,runBeforeButtonClick:dr,onLoadStateChange:_s,placeholderBorderRadius:Hr,popupCapabilityOwner:w,externalTelemetryContext:$})}),io?d(Zr,{stripe:on,options:bs,children:d(Vl,{sessionId:e,nonce:t,email:T.email,billingName:U||void 0,onBuyerIdentityReady:B,billingApiUrl:We,intentKind:Q>0?"payment":"setup",expressMethods:ao,onTokenizedBody:Bn,onErrorChange:me,onButtonClick:O,onDecline:y,onTechnicalFailure:oo,runBeforeButtonClick:dr,onLoadStateChange:Es,placeholderBorderRadius:Hr,popupCapabilityOwner:w,externalTelemetryContext:$})}):null,!io&&Bs?d("div",{style:{height:Ya,borderRadius:Hr,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,zo&&d(Hl,{sessionId:e,nonce:t,email:T.email,billingName:[T.firstName,T.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:B,billingApiUrl:We,paymentElementMethods:va,stripeInstance:on,paymentElementBaseOptions:si,onTokenizedBody:Bn,onErrorChange:me,onButtonClick:O,onDecline:y,runBeforeButtonClick:dr,onLoadStateChange:As,isProcessing:_e,submitButtonColor:Wr,submitButtonBorderRadius:$t,submitButtonStyle:j.submitButton,onExpandApm:Vr,expandedApmMethod:cn,themeId:$e,buttonAppearance:{backgroundColor:j.cardButton?.backgroundColor,borderColor:j.cardInputBorder,textColor:j.cardButton?.color,borderRadius:Hr}}),A&&d("button",{type:"button",onClick:async()=>{_e||!(await dr("card")).proceed||(O?.("card"),Kr())},disabled:_e,style:{width:"100%",...D,...j.cardButton,...is({themeBundle:Z,resolvedPrimaryColor:Wr,resolvedBorderRadius:$t,submitButtonStyle:j.submitButton,explicitPrimaryColor:Fn?.colorPrimary}),fontSize:j.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:dt=>{!_e&&(Z||Fn?.colorPrimary)&&(dt.currentTarget.style.backgroundColor=Ec)},onMouseLeave:dt=>{(Z||Fn?.colorPrimary)&&(dt.currentTarget.style.backgroundColor=Wr)},onMouseDown:dt=>{dt.currentTarget.style.transform="scale(0.985)"},onMouseUp:dt=>{dt.currentTarget.style.transform="scale(1)"},children:d(po,{content:Me})}),ie&&nt==="buttons"&&d(Co,{margin:"0.25rem 0",styleOverride:j.errorBanner,children:ie})]}),A&&h&&d("div",{style:{gridArea:"1 / 1",...J?{animation:J}:{},...nt==="collapsing"?{pointerEvents:"none"}:{}},children:Hs}),G&&Ys&&cn&&Ia&&on&&d("div",{style:{gridArea:"1 / 1",...co?{animation:co}:{},...nt==="apm-collapsing"?{pointerEvents:"none"}:{}},children:Oe("div",{style:{backgroundColor:yi,borderRadius:vi,...Ko,padding:hi},children:[Oe("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[Oe("button",{type:"button","data-testid":"flopay-apm-back-button",onClick:rn,style:{display:"inline-flex",alignItems:"center",gap:mi?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:j.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...j.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",...j.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(yo,{content:wt})]}),d("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:j.titleFontSize??"1.05rem",color:fi,paddingRight:80,...j.title},children:`Pay with ${eo(cn)}`})]}),d(Zr,{stripe:on,options:Ia,children:d(ts,{method:cn,sessionId:e,nonce:t,email:T.email,billingName:[T.firstName,T.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:B,billingApiUrl:We,onTokenizedBody:Bn,onErrorChange:me,onDecline:y,onCancel:rn,runBeforeButtonClick:dr,onButtonClick:O,isProcessing:_e,submitButtonColor:Wr,submitButtonBorderRadius:$t,submitButtonStyle:j.submitButton,errorText:ie})},cn)]})})]})]})}return Ys&&cn&&Ia&&on&&G?Oe("form",{onSubmit:ui,className:R,noValidate:!0,style:{position:"relative"},children:[d(Xi,{}),S&&d(wr,{status:S,errorMessage:ie,authorized:en}),d("div",{style:{...co?{animation:co}:{},...nt==="apm-collapsing"?{pointerEvents:"none"}:{}},children:Oe("div",{style:{backgroundColor:yi,borderRadius:vi,...Ko,padding:hi},children:[Oe("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[Oe("button",{type:"button","data-testid":"flopay-apm-back-button-default",onClick:rn,style:{display:"inline-flex",alignItems:"center",gap:mi?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:j.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...j.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",...j.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(yo,{content:wt})]}),d("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:j.titleFontSize??"1.05rem",color:fi,paddingRight:80,...j.title},children:`Pay with ${eo(cn)}`})]}),d(Zr,{stripe:on,options:Ia,children:d(ts,{method:cn,sessionId:e,nonce:t,email:T.email,billingName:[T.firstName,T.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:B,billingApiUrl:We,onTokenizedBody:Bn,onErrorChange:me,onDecline:y,onCancel:rn,runBeforeButtonClick:dr,onButtonClick:O,isProcessing:_e,submitButtonColor:Wr,submitButtonBorderRadius:$t,submitButtonStyle:j.submitButton,errorText:ie})},cn)]})})]}):Oe("form",{onSubmit:ui,className:R,noValidate:!0,style:{position:"relative"},children:[d(Xi,{}),S&&d(wr,{status:S,errorMessage:ie,authorized:en}),Oe("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Ws("flopay-direct-paypal-gate-debug-default"),Gs("flopay-stripe-gate-debug-default"),No&&Je&&Oe(Qr,{children:[E&&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(ea.Provider,{value:w,children:d(Oa,{sessionId:e,nonce:t,billingApiUrl:We,email:T.email,billingName:U||void 0,onBuyerIdentityReady:B,clientId:Je.clientId,environment:Je.environment,currency:oe.toUpperCase(),isSubscription:lt,providerObjectType:ze,approvalPresentation:Pa==="popup"?void 0:Pa,onTokenizedBody:Bn,onComplete:s,onErrorChange:me,onDecline:y,onTechnicalFailure:oo,onButtonClick:O,runBeforeButtonClick:dr,isProcessing:_e,onLoadStateChange:li,onInitializationStateChange:ci,session:ft,existingOrderId:E?.orderId,debug:_},E?.orderId??"fresh")})]}),Lo&&d(Zr,{stripe:to,options:Ps,children:d(Kl,{sessionId:e,nonce:t,email:T.email,billingName:U||void 0,onBuyerIdentityReady:B,billingApiUrl:We,onTokenizedBody:Bn,onErrorChange:me,isProcessing:_e,onButtonClick:O,onDecline:y,onTechnicalFailure:oo,runBeforeButtonClick:dr,onLoadStateChange:_s,placeholderBorderRadius:Hr,popupCapabilityOwner:w,externalTelemetryContext:$})}),io&&d(Zr,{stripe:on,options:bs,children:d(Vl,{sessionId:e,nonce:t,email:T.email,billingName:U||void 0,onBuyerIdentityReady:B,billingApiUrl:We,intentKind:Q>0?"payment":"setup",expressMethods:ao,onTokenizedBody:Bn,onErrorChange:me,onButtonClick:O,onDecline:y,onTechnicalFailure:oo,runBeforeButtonClick:dr,onLoadStateChange:Es,placeholderBorderRadius:Hr,popupCapabilityOwner:w,externalTelemetryContext:$})}),zo&&d(Hl,{sessionId:e,nonce:t,email:T.email,billingName:[T.firstName,T.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:We,paymentElementMethods:va,stripeInstance:on,paymentElementBaseOptions:si,onTokenizedBody:Bn,onErrorChange:me,onButtonClick:O,onDecline:y,runBeforeButtonClick:dr,onLoadStateChange:As,isProcessing:_e,submitButtonColor:Wr,submitButtonBorderRadius:$t,submitButtonStyle:j.submitButton,themeId:$e,onExpandApm:Vr,expandedApmMethod:cn,buttonAppearance:{backgroundColor:j.cardButton?.backgroundColor,borderColor:j.cardInputBorder,textColor:j.cardButton?.color,borderRadius:Hr}})]}),A&&(Cc||Pc||wc)&&Oe("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem",margin:"0.5rem 0 0.75rem",color:"#999",fontSize:"0.85rem"},children:[d("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}}),d("span",{children:"or pay with card"}),d("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}})]}),A&&Hs]})}import{Fragment as Rr,jsx as se,jsxs as sn}from"react/jsx-runtime";var Ao=44,ms="flopay_checkout_saved_payment_resume",ti=new Map,Qa=new Map;function nc(e,t){t.settled&&t.consumers===0&&ti.get(e)===t&&ti.delete(e)}function Mu(e,t,n){let r=Qa.get(e);if(r&&(!r.sdkGeneratedIdempotencyKey||!t||r.sdkGeneratedIdempotencyKey===t))return r.attempt;let o=n(),i={attempt:o,sdkGeneratedIdempotencyKey:t};Qa.set(e,i);let s=()=>{Qa.get(e)===i&&Qa.delete(e)};return o.then(s,s),o}function ua(e){return new Promise(t=>setTimeout(t,e))}function ei(e,t,n){let r=Fa({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:dc,enabled:t!==!1});return r.beginCheckout(n),r}function pa(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function cs(e,t,n,r,o,i){let s=ei(e,t,n);s.error({errorCode:r,stage:o,paymentMethodCategory:"unknown",...i,...o==="session_read"?{requestCategory:"session_read"}:{}}),pa(s)}function rc(e,t,n,r){e.log({name:t==="session_claim"?"session.claim.completed":"session.request.completed",stage:t,requestCategory:t,statusClass:"2xx"}),e.performance({stage:t,durationMs:Math.max(0,e.now()-n),durationMode:"machine",requestCategory:t,...r===void 0?{}:{attempt:r},statusClass:"2xx"})}function oc(e,t,n,r,o){let i=lc(t,"CHECKOUT_SESSION_CREATE_FAILED","unknown");return e.performance({stage:n,durationMs:Math.max(0,e.now()-r),durationMode:"machine",requestCategory:n,attempt:o,statusClass:i.statusClass}),t instanceof 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 uc(e,t){let n=e?.data.paypal?.publishableKey;if(n)return{clientId:n,environment:e?.data.paypal?.environment,providerObjectType:e?.data.paypal?.providerObjectType,approvalPresentation:e?.data.paypal?.approvalPresentation,...t?{existingOrderId:t}:{}}}function ds(e){return!e||e.data.stripe?.publishableKey?!1:!!uc(e)?.clientId}var Bu={name:"provider_unavailable",initialize:()=>Promise.resolve(),getRawProvider:()=>null,destroy:()=>{}};function Fu(e){return new Iu(Bu,{publishableKey:"provider_unavailable",...e})}async function us(e,t){let{publishableKey:n,paypalPublishableKey:r}=qi(e);return{...await ji({publishableKey:n,paypalPublishableKey:r,...t}),publishableKey:n,paypalPublishableKey:r}}function fs(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function Du(){if(!fs())return null;try{let e=window.sessionStorage.getItem(ms);return e?JSON.parse(e):null}catch{return null}}function ac(e){if(fs())try{window.sessionStorage.setItem(ms,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function ps(){if(fs())try{window.sessionStorage.removeItem(ms)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}function Ou(){if(typeof window>"u")return;let e=new URL(window.location.href),t=["payment_intent","payment_intent_client_secret","redirect_status"],n=!1;for(let r of t)e.searchParams.has(r)&&(e.searchParams.delete(r),n=!0);n&&window.history.replaceState(window.history.state,"",e.toString())}function ic(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 ys(e,t){return e?"custom_layout":t==="buttons"?"buttons_layout":"default_layout"}function Nu(e,t){return e?"unknown":t==="buttons"?"buttons":"embedded"}function sc(e){return e?.gateways?.stripe?"stripe":e?.gateways?.paypal?"paypal":void 0}function Lu(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 gs({sessionId:e,nonce:t,createSession:n,billingApiUrl:r,telemetry:o,appearance:i,locale:s,loading:l,error:y,onComplete:f,onError:b,onInstrument:g,onDecline:M,onCountryChange:R,onZipChange:C,showPayPal:v=!0,showStripe:q=!0,enabledPaymentMethods:Re,showApplePay:I=!0,showGooglePay:G=!0,debug:Y=!1,layout:re,theme:ve,buttonsTheme:Le,buttonsStyles:Ce,cardButtonContent:$e,cardBackButtonContent:vt,cardTitleContent:Ke,showSecurityFooter:Ne,onButtonClick:Me,onBeforeButtonClick:wt,enableAVS:fe,cardFieldOrder:ut,cardPreFormSlot:O,avsLayout:Ae,submitLabel:yt,className:Be,initialErrorMessage:it=null,initialPayPalOrderId:N,children:ue,checkoutMode:ge,confirmLabel:K,renderConfirmButton:Ge,onSessionCompleted:Ve}){let L=Tu(r),st=ar(()=>cc(ve),[ve]),Ye=i??st?.appearance,He=n?"embedded_checkout":"standard_checkout",Ee=ys(ue,re),[le,mt]=zt(null),[Q,oe]=zt(null),Fe=At(null),Je=At(null),lt=At(0),[z,pt]=zt(null),Xe=At(null),[_,ct]=zt(null),Jt=ar(()=>n?So(n):"",[n]),xe=n?`create:${Jt}`:`session:${e??""}`,un=sc(_),c=At(new Set),w=At(xe),ne=At(xe);Ho(()=>{ne.current=xe,w.current!==xe&&(w.current=xe,c.current.clear())},[xe]);let k=wn(S=>{if(ne.current===xe){if(Ri.has(S.name)){if(c.current.has(S.name))return;c.current.add(S.name)}Ft(()=>g?.(S))}},[xe,g]),$=Po(k,xe),ft=At(!1),ze=wn(S=>{if(ft.current)return;let m=S.gateway||!un?S:{...S,gateway:un};k(m)},[k,un]);yr(()=>{$({class:"lifecycle",name:"checkout.mount"})},[$]);let[Ue,xt]=zt(e??""),ee=e??Ue,pn=n?"":ee,[We,Dt]=zt(!0),[Rn,Kt]=zt(null),[Te,Ut]=zt(0),[gn,hn]=zt("full"),[kn,Nn]=zt(!1),[vn,Vt]=zt(it),[De,we]=zt(null),[Ln,St]=zt(null),[bn,En]=zt(!1),[Hn,Ht]=zt(void 0),[Xt,ln]=zt(""),[kt,Mt]=zt(!1),[yn,Zt]=zt(!1),[qt,Wt]=zt(!1),Tt=At(null),X=At(0),Qt=At(void 0),[en,ir]=zt("loading"),[mr,Wn]=zt(0),Gt=At(!1),sr=At(!1),jt=At(!1),A=At(null),gt=At(null),Ze=ar(()=>({checkoutMode:ge??gn,layout:Nu(ue,re)}),[ge,ue,gn,re]),x=At(f);x.current=f;let qe=At(b);qe.current=b;let te=At(M);te.current=M;let tn=wn(S=>$a(A,async m=>{try{return await S(m)}catch(W){throw m.aborted?sa(W):W}}),[]);yr(()=>()=>{A.current?.abort(),A.current=null},[]);let Pn=wn((S,m)=>{Fe.current=S,oe(S),Xe.current=m,pt(m)},[]),nn=wn(()=>{let S=Je.current;S&&(Je.current=null,S.destroy())},[]);yr(()=>{mn(Q)?.setCheckoutContext(Ze),z&&z!==Q&&mn(z)?.setCheckoutContext(Ze)},[Q,z,Ze]);let fr=At(Ve);fr.current=Ve;let he=wn(S=>{ir(S),!(S!=="exhausted"||jt.current)&&(jt.current=!0,qe.current?.(new Sn("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),zn=wn(()=>{ir("retrying"),Wn(S=>S+1)},[]);yr(()=>{ir("loading"),Wn(0),jt.current=!1},[ee]),yr(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:dc,checkout_type:He,checkout_layout:Ee,billing_api_url:L})},[Ee,He,L]);let Gn=ar(()=>n?So(n,!0):"",[n]),jr=ar(()=>Xt===Gn?Hn:void 0,[Hn,Xt,Gn]),Yn=ar(()=>n?wi(n,jr):void 0,[n,jr]),Jn=ge??Yn?.checkoutMode??"full",Yt=ar(()=>Yn?{...Yn,checkoutMode:Jn}:void 0,[Yn,Jn]);yr(()=>{Ht(void 0),ln(Gn),Qt.current=void 0,Tt.current=null,Wt(!1)},[Gn]),yr(()=>{Vt(it)},[it]);let Er=wn((S,m,W)=>{Ft(()=>{te.current?.(dn(S,m,W))})},[]),gr=wn(async(S,m)=>{Vt(null),St(null),En(!1),we("processing");let W=m?.sessionId??S.id,F=S.clientSecret||t,be=sc(S),Nt=Fe.current??Xe.current,ye=mn(Nt),pe=Nt?null:ei(L,o,Ze),E={log:ae=>{ye?ye.log(ae):pe?.log(ae)},error:ae=>{ye?ye.error(ae):pe?.error(ae)},terminal:ae=>{ye?ye.terminal(ae):pe?.terminal(ae)},performance:ae=>{ye?ye.performance(ae):pe?.performance(ae)},now:()=>ye?.now()??pe?.now()??0,elapsed:ae=>ye?.elapsed(ae)??Math.max(0,(pe?.now()??ae)-ae)},V=E.now(),p=!!(m?.initialAutoProcessingError||m?.initialAutoProcessingPending),u=!1,P,B=()=>{u||(u=!0,p=!0,P=E.now(),E.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),E.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},ie=!1,Z=()=>{ie||(ie=!0,E.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),E.performance({stage:"processing",durationMs:E.elapsed(V),durationMode:"machine",paymentMethodCategory:"saved",requestCategory:"process_payment"}),P!==void 0&&E.performance({stage:"recovery",durationMs:E.elapsed(P),durationMode:"machine",paymentMethodCategory:"saved"}))};E.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),ft.current=!0;try{E.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"})}finally{ft.current=!1}$({class:"lifecycle",name:"payment.processing.started",provider:be}),p&&B();let j;try{let ae=Tl(m?.initialAutoProcessingError),Se=m?.initialAutoProcessingError?.type==="3ds_required"&&!m.initialAutoProcessingError.threeDSecureToken&&m.initialAutoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:m.initialAutoProcessingError.nextActionRedirectUrl}:null,bt,_e=H=>(B(),tn(T=>Io(H,{billingApiUrl:L,sessionId:W,nonce:F,session:S,signal:T})));if(Se)bt=await _e(Se);else if(ae)B(),ae.type==="paypal_redirect_required"&>.current?.publishableKey&&ac({sessionId:W,publishableKey:gt.current.publishableKey,paypalPublishableKey:gt.current.paypalPublishableKey}),bt=await tn(H=>Va(ae,{flopay:Fe.current,paypalFlopay:Xe.current,attempt3DS:m?.attempt3DS,billingApiUrl:L,sessionId:W,session:S,telemetry:!1,signal:H})),ae.type==="paypal_redirect_required"&&ps();else if(m?.initialAutoProcessingPending){let H=m.initialAutoProcessingPending,T=new Za(L,{telemetry:!1}),U=await tn(ht=>T.waitForCheckoutSessionCompletion(H.sessionId,{initialDelayMs:H.retryAfterMs,nonce:F,statusUrl:H.statusUrl,signal:ht})),ke=U.data.session,Ie=U.autoProcessingError?.type==="3ds_required"&&U.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:U.autoProcessingError.nextActionRedirectUrl}:null;if(Ie)bt=await _e(Ie);else{if(!Fr(ke))throw go(ke);bt=Tr(ke,W)}}else{if(m?.initialAutoProcessingError)throw Ir(m.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:m.initialAutoProcessingError.checkoutMethod});if(m?.fromCreateSession)return m?.fallbackToFull&&(hn("full"),ic("full")),!1;{let H=await _o({billingApiUrl:L,sessionId:W,session:S,nonce:F,telemetry:!1});H.type==="success"?bt=H.result:H.type==="next_action_required"?bt=await _e(H):(B(),H.type==="paypal_redirect_required"&>.current?.publishableKey&&ac({sessionId:W,publishableKey:gt.current.publishableKey,paypalPublishableKey:gt.current.paypalPublishableKey}),bt=await tn(T=>Va(H,{flopay:Fe.current,paypalFlopay:Xe.current,attempt3DS:m?.attempt3DS,billingApiUrl:L,sessionId:W,session:S,telemetry:!1,signal:T})),H.type==="paypal_redirect_required"&&ps())}}W&&ko(W),Z(),p&&(E.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),E.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),E.terminal({outcome:bt.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),En(bt.status==="authorized"),we("success"),await ua(600),j=()=>x.current?.(bt)}catch(ae){let Se=la(ae);if(Se.code==="three_ds_aborted")return!1;let bt=Se.checkoutMethod??ia;Vt(Se.message),St(Se.message),En(!1),m?.fallbackToFull&&(E.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),hn("full"),ic("full")),Z();let _e=Se.statusCode===void 0?void 0:xu(Se.statusCode,"unknown"),H=_e==="4xx"?{requestCategory:"process_payment",statusClass:_e}:{},T=_e===void 0||_e==="4xx";if(T&&(Se.telemetryOutcome==="payment_declined"||!!(Se.declineCode||Se.code?.toLowerCase().includes("declin"))))E.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...H});else if(T&&(Se.telemetryOutcome==="validation_rejected"||Se.type==="validation_error"))E.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...H});else{let Ie=lc(ae,p?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown"),ht=Se.telemetryRequestCategory??"process_payment";ft.current=!0;try{E.error({...Ie,...Se.telemetryFailureCategory?{failureCategory:Se.telemetryFailureCategory}:{},stage:p?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:ht})}finally{ft.current=!1}$({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:ht,provider:be})}return Ft(()=>qe.current?.(Se)),Er(bt,Se,{code:Se.code,declineCode:Se.declineCode}),we("error"),await Promise.allSettled([ua(400),m?.ensureProvidersReady?m.ensureProvidersReady():Promise.resolve()]),p&&(E.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),E.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{Z(),pe&&pa(pe),we(null),St(null)}return Ft(j),!0},[Er,$,t,L,tn,o,Ze]);yr(()=>{if(typeof window>"u"||sr.current)return;let S=new URLSearchParams(window.location.search),m=S.get("payment_intent_client_secret");if(!m)return;let W=Du();W&&(sr.current=!0,(async()=>{let F,be=0;Vt(null),St(null),we("processing"),Nn(!0);try{if(S.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:Nt,paypalFlopay:ye}=await ji({publishableKey:W.publishableKey,paypalPublishableKey:W.paypalPublishableKey,billingApiUrl:L,locale:s,telemetry:o});F=mn(ye??Nt),F?.setCheckoutContext(Ze),be=F?.now()??0,F?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),F?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let pe=(ye??Nt)?.getRawProvider();if(!pe)throw Object.assign(new Sn("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:E,error:V}=await pe.retrievePaymentIntent(m);if(V)throw Object.assign(new Sn(V.message??"Failed to retrieve PayPal payment status.","api_error",{code:V.code}),{checkoutMethod:"paypal"});let p=il(E?.status);if(!E||p==="failed")throw Object.assign(new Sn("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let u=typeof E.payment_method=="string"?E.payment_method:E.payment_method?.id,P=p;if(W.sessionId){let Z=(await new Za(L,{telemetry:!1}).getUnifiedCheckoutSession(W.sessionId)).data.session;if(Z&&Z.status!=="complete"){let j=await _o({billingApiUrl:L,sessionId:W.sessionId,session:Z,telemetry:!1,tokenizedData:{id:u??E.id,type:"card",threeDSecureActionResultTokenId:E.id,isPaypal:!0}});if(j.type!=="success")throw Object.assign(new Sn("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});P=j.result.status}}W.sessionId&&ko(W.sessionId),F?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),F?.performance({stage:"redirect_resume",durationMs:F.elapsed(be),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),F?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),we("success"),await ua(600),Ft(()=>x.current?.({status:P,paymentIntentId:E.id,paymentMethodId:u,checkoutMethod:"paypal"}))}catch(Nt){let ye=la(Nt),pe=ye.checkoutMethod??"paypal",E=!!(ye.declineCode||ye.code?.toLowerCase().includes("declin"));if(F)F.performance({stage:"redirect_resume",durationMs:F.elapsed(be),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),E?F.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):F.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(E){let V=ei(L,o,Ze);V.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),pa(V)}else cs(L,o,Ze,"REDIRECT_RESUME_FAILED","redirect_resume");Vt(ye.message),St(ye.message),Ft(()=>qe.current?.(ye)),Er(pe,ye,{code:ye.code,declineCode:ye.declineCode}),we("error"),await ua(400)}finally{ps(),Ou(),we(null),St(null),Nn(!1)}})())},[Er,s,L,o,Ze]);let Tn=At(null),hr=ar(()=>Yt?So(Yt):"",[Yt]),Xn=At(Yt);Xn.current=Yt,yr(()=>{xt(e??"")},[e]),yr(()=>{Gt.current=!1,Vt(it),St(null),En(!1),we(null)},[hr,it,e]);async function Zn(S,m,W){let F=ei(L,o,Ze),be=new Za(L,{telemetry:!1}),Nt=!1;try{let ye=S.idempotencyKey===void 0?void 0:tc(S.idempotencyKey),pe=Fi(m,W),E=Di(m,W);pe?.canonicalIdentity===W&&E&&E.canonicalIdentity===void 0&&(Ua(m,W,E.idempotencyKey),E={...E,canonicalIdentity:W});let V=ye??(E?.canonicalIdentity===W?E.idempotencyKey:void 0),p,u=!1;F.log({name:pe?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let P=pe?.sid??null,B=null,ie,Z,j=!1;if(P)try{B=await be.getUnifiedCheckoutSession(P,pe?.nonce),pe&&pe.canonicalIdentity===void 0&&(wl(B.data.session,S)?(za(m,W,P,pe.nonce??B.data.session?.clientSecret),E&&E.canonicalIdentity===void 0&&(Ua(m,W,E.idempotencyKey),V??(V=E.idempotencyKey))):(La(m,W),E=null,V=ye,P=null,B=null));let Se=B?.data.session?.status,bt=B?.data.session,_e=bt?.clientSecret||pe?.nonce;if(P&&bt?.buyerIdentified===!1&&_e&&(Z=fo(be,P,_e,S.account)),P&&B&&Se==="complete"){if(Oi(P))return{sid:P,result:B};La(m,W),P=null,B=null,u=!0}}catch{F.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),pe?.canonicalIdentity===void 0?(La(m,W),V=ye):Na(m,W),P=null}if(!P){!ye&&(u||!V)&&(V=tc(),p=V),V&&Ua(m,W,V);let Se=F.now(),bt=0;F.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let _e={...S,idempotencyKey:V,avsCheck:!!fe,avsConfig:typeof fe=="object"?fe:void 0,checkoutType:"embedded_checkout",checkoutLayout:ys(ue,re)};Object.defineProperty(_e,_u,{configurable:!1,enumerable:!1,value:{onAttempt:U=>{bt=Math.max(bt,U)}}});let H=()=>{rc(F,"session_create",Se,bt)},T=U=>{oc(F,U,"session_create",Se,bt)&&$({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_create"})};try{if(Eu(_e)){let U=await be.createDetachedSession(_e);U.claimed.catch(()=>{}),B=U.shell,P=U.sessionId,Z=U.claim;let ke=F.now();F.log({name:"session.claim.started",stage:"session_claim",requestCategory:"session_claim"}),ie=U.claimed.then(Ie=>{let ht=Ie.data.session?.id??U.sessionId;return ht&&za(m,W,ht,Ie.data.session?.clientSecret??U.nonce),rc(F,"session_claim",ke),H(),Ie},Ie=>{throw Na(m,W),oc(F,Ie,"session_claim",ke,0)&&$({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_claim"}),Ie}).finally(()=>pa(F)),ie.catch(()=>{}),Nt=!0,F.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),F.performance({stage:"session_shell",durationMs:F.now()-Se,durationMode:"machine",requestCategory:"session_create",attempt:bt,statusClass:"2xx",paymentMethodCategory:"card"})}else B=await be.createAndFetchSession(_e),H()}catch(U){throw T(U),U}P=B.data.session?.id??P??"",P&&!ie&&za(m,W,P,B.data.session?.clientSecret)}let ae=B?.data.session;return!Z&&P&&ae?.buyerIdentified===!1&&ae.clientSecret&&(Z=fo(be,P,ae.clientSecret,S.account)),{sid:P??"",result:B,sdkGeneratedIdempotencyKey:p,...ie?{claimed:ie}:{},...Z?{claim:Z}:{},...j?{claimRequiresIdentity:!0}:{}}}finally{Nt||pa(F)}}let vr=At(Zn);Ho(()=>{vr.current=Zn},[Zn]);let Qn=wn(async(S,m)=>{let W=Xn.current;if(!W)throw new Sn("createSession is required to bootstrap checkout.","validation_error");let F=wi(W,S),be=So(F),Nt=Cl(F),ye=ti.get(be);if(!ye){let V={canonicalIdentity:be,promise:vr.current(F,Nt,be),consumers:0,settled:!1};ye=V,ti.set(be,V);let p=()=>{V.settled=!0,nc(be,V)};V.promise.then(p,p)}ye.consumers+=1;let pe=!1,E=()=>{pe||(pe=!0,ye.consumers-=1,nc(be,ye))};m?.(E);try{let V=await ye.promise;Tn.current=be,S&&(ln(Gn),Ht(ae=>rl(ae,S)));let{sid:p,result:u,claimed:P,claim:B,claimRequiresIdentity:ie}=V;if(Qt.current=B,Wt(ie===!0),mt(u),u.data.session&&ct(u.data.session),p&&xt(p),P){X.current+=1;let ae=X.current;Tt.current=P,Zt(!0),P.then(Se=>{X.current===ae&&(Tt.current===P&&(Tt.current=null),mt(Se),Se.data.session&&ct(Se.data.session),Zt(!1),Wt(!1))},Se=>{X.current===ae&&(Tt.current===P&&(Tt.current=null),Zt(!1),Wt(!1),Kt(Se instanceof Sn?Se:new Sn(Se instanceof Error?Se.message:"Failed to create session","api_error")))})}else X.current+=1,Tt.current=null,Zt(!1),Wt(!1);let{flopay:Z,paypalFlopay:j}=await us(u,{billingApiUrl:L,locale:s,telemetry:o});return Pn(Z,j),Dt(!1),V}catch(V){throw Tn.current===be&&(Tn.current=null),V}finally{m||E()}},[Gn,Pn,s,L,o]),It=At(gr);It.current=gr;let Un=At(Qn);Un.current=Qn;let lr=wn(async S=>{if(!Lu(S)||kt)return{sessionId:Ue,session:_};Mt(!0);try{let m=await Qn(S);return{sessionId:m.sid,session:m.result.data.session??null}}finally{Mt(!1)}},[Qn,kt,Ue,_]),qn=wn(async S=>{let m=Qt.current;if(!m)return;let W=X.current,F=await m(S);X.current===W&&(mt(F),F.data.session&&ct(F.data.session))},[]),Cn=wn(async()=>{await Tt.current},[]),nt=wn(async()=>(await Cn(),{proceed:!0}),[Cn]);yr(()=>{let S=!1,m,W=++lt.current;nn(),Kt(null),Ut(0);let F=()=>{S=!0,lt.current===W&&(lt.current+=1,nn())},be=Xn.current;if(hr&&be)return hn(Jn),Dt(!1),Tn.current===hr?F:(ct(ol(be,ge)),(async()=>{let pe=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),E=Jn==="auto"&&!Gt.current&&!pe;E&&(Vt(null),St(null),we("processing"));try{let V=await Un.current(void 0,B=>{m=B}),p=V.result.data.session??null;gt.current=qi(V.result);let u=ds(V.result),P=Oi(V.sid||p?.id);if(!S&&E&&p&&!u&&!P){Gt.current=!0,await Mu(hr,V.sdkGeneratedIdempotencyKey,()=>It.current(p,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:V.result.autoProcessingError,initialAutoProcessingPending:V.result.autoProcessingPending,autoProcessingAttempted:V.result.autoProcessingAttempted,sessionId:V.sid||p.id}));return}!S&&E&&((u||P)&&(Gt.current=!0),we(null),St(null))}catch(V){if(S)return;let p=Ra(V);if(E&&p==="session_auto_completed"){Gt.current=!0,we("success"),await ua(600),S||(Ft(()=>{x.current?.({status:"succeeded"})}),we(null),St(null));return}E&&(we(null),St(null));let u=V instanceof Sn?V:new Sn(V instanceof Error?V.message:"Failed to create session","api_error");Kt(u)}finally{m?.(),m=void 0}})(),()=>{F(),m?.()});Dt(!0);async function Nt(){let pe=!1,E=null;try{let V=new Za(L,{telemetry:!1}),p=await V.getUnifiedCheckoutSession(ee,t);if(E=p,S)return;mt(p);let u=p.data.session??null;if(ct(u),!u)throw new Sn("No session data returned","api_error");let P=u.checkoutMode;if(P==="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"){Dt(!1),Ft(()=>{x.current?.(Tr(u,ee)),fr.current?.(u.successUrl??"")});return}if(u.status==="complete"){Dt(!1),Ft(()=>{fr.current?.(u.successUrl??"")});return}if(u.status==="expired")throw _a(u);pe=!0;let B=ge??P??"full";hn(B),X.current+=1;let ie=u.clientSecret||t;Qt.current=u.buyerIdentified===!1&&ie?fo(V,ee,ie,{...u.customer?.id?{userId:u.customer.id}:{}}):void 0,Zt(!1),Wt(!1);let Z=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),j=ds(p);if(B==="auto"&&!Gt.current&&!Z&&!j){Gt.current=!0;let ae=ye(p);try{if(await It.current(u,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>ae,sessionId:ee||u.id}),S)return;await ae,S||Dt(!1);return}catch{if(S)return;await ae,S||Dt(!1);return}}await ye(p),S||Dt(!1)}catch(V){if(S)return;let p=nl(V,pe);if(pe&&$({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"}),p){let{errorCode:P,stage:B,...ie}=p;cs(L,o,Ze,P,B,ie)}if(p?.stage==="provider_load"&&(ge??E?.data.session?.checkoutMode??"full")==="full"&&tl(E,v,q)){let P=Fu({billingApiUrl:L,locale:s,telemetry:o});Je.current=P,Pn(P,null),Ut(1),Dt(!1);return}let u=V instanceof Sn&&p?.stage!=="provider_load"?V:el();u!==V&&Ft(()=>qe.current?.(u)),Kt(u),Dt(!1)}}async function ye(pe){let{flopay:E,paypalFlopay:V,...p}=await us(pe,{billingApiUrl:L,locale:s,telemetry:o});gt.current={publishableKey:p.publishableKey,paypalPublishableKey:p.paypalPublishableKey},Pn(E,V),Ut(0)}return Nt(),F},[ge,hr,Jn,pn,t,v,q]);let In=wn(async()=>{if(!le||Te!==1)return;let S=lt.current;Ut(2);try{let{flopay:m,paypalFlopay:W}=await us(le,{billingApiUrl:L,locale:s,telemetry:o});if(lt.current!==S)return;nn(),Pn(m,W),Ut(0)}catch(m){if(lt.current!==S)return;let{errorCode:W,stage:F,...be}=Pi(m);cs(L,o,Ze,W,F,be)}},[nn,Pn,s,Te,L,o,Ze,le]),cn=!!(ee&&(_?.clientSecret||t)),jn=kn||!cn,$r=wn(async()=>{if(!(kn||!cn||!_)){Nn(!0),Vt(null);try{await gr(_,{attempt3DS:!0,fallbackToFull:!0,sessionId:ee||_.id})}finally{Nn(!1)}}},[ee,kn,cn,gr,_]),$n=uc(le,N),br=ds(le),An=ar(()=>{if(!(!le||!_||!le.data.stripe?.publishableKey))return{billingApiUrl:L}},[le,_,L]),xn=!!(n&&!ue&&re==="buttons"&&wt&&Jn==="full"),Kr=!!(ee&&(_?.vault?.html||Mr(_))),Kn=ar(()=>({session:_,loading:We,error:Rn,checkoutMode:gn,inlineSessionDraft:Yt,applyInlineSessionPatch:xn?lr:void 0,inlineSessionPatchProcessing:kt,claimPending:yn,claimRequiresIdentity:qt,claimBuyerIdentity:qn,waitForDataAttachment:Cn}),[_,We,Rn,gn,Yt,xn,lr,kt,yn,qt,qn,Cn]),Vr=!!n&&re==="buttons"&&!br&&!Kr&&(!Q||!An),rn=De?se(wr,{status:De,errorMessage:Ln,authorized:bn}):null;if(We&&!Kr){if(l)return sn(Rr,{children:[l,rn]});if(re==="buttons"){let S=st?.buttonsLayout?.cardButton?.borderRadius??st?.appearance.variables?.borderRadius??8,m=W=>se("div",{style:{height:W,borderRadius:S,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:[v&&m(Ao),q&&(I||G)&&m(Ao),q&&m(Ao),se("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),rn]})}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); } }"})]}),rn]})}return Rn?y?se(ur.Provider,{value:Kn,children:y(Rn)}):se(ur.Provider,{value:Kn,children:se("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:Rn.message})}):Vr?sn(Rr,{children:[se(ur.Provider,{value:Kn,children:se(Uu,{onButtonClick:Me,showPayPal:v,showStripe:q,showApplePay:I,showGooglePay:G,theme:ve,buttonsTheme:Le,buttonsStyles:Ce,cardButtonContent:$e,cardBackButtonContent:vt,cardTitleContent:Ke})}),rn]}):br&&_&&$n?sn(Rr,{children:[se(ur.Provider,{value:Kn,children:sn("div",{className:Be,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[vn&&se(Co,{icon:!1,children:vn}),en==="retrying"&&se("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),en==="exhausted"&&sn("div",{role:"alert",children:[se("div",{children:"PayPal is temporarily unavailable. Please try again."}),se("button",{type:"button",onClick:zn,children:"Retry PayPal"})]}),en!=="exhausted"&&se("div",{"aria-hidden":en==="retrying"?!0:void 0,style:en==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:se(bl,{sessionId:ee,nonce:_.clientSecret||void 0,billingApiUrl:L,email:_.customer?.email||Yt?.account?.email,billingName:[_.customer?.firstName,_.customer?.lastName].filter(Boolean).join(" ")||[Yt?.account?.firstName,Yt?.account?.lastName].filter(Boolean).join(" ")||void 0,onBuyerIdentityReady:qn,clientId:$n.clientId,environment:$n.environment,currency:(_.currency??"usd").toUpperCase(),isSubscription:_.mode==="subscription",providerObjectType:$n.providerObjectType,approvalPresentation:$n.approvalPresentation,existingOrderId:$n.existingOrderId,onComplete:f,onErrorChange:Vt,onDecline:M,onButtonClick:Me,runBeforeButtonClick:nt,onInitializationStateChange:he,allowAutomaticRetry:mr===0,session:_,telemetry:o,telemetryContext:Ze,onInstrument:ze,debug:Y},`${xe}:paypal-init-${mr}`)})]})}),rn]}):gn==="confirm"?sn(Rr,{children:[se(ur.Provider,{value:Kn,children:se(qa,{flopay:Q,paypalFlopay:z,options:An??{billingApiUrl:L},onInstrument:ze,children:sn("div",{className:Be,children:[vn&&se("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:vn}),Ge?Ge({onConfirm:$r,isProcessing:jn}):se("button",{type:"button",onClick:$r,disabled:jn,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:jn?"not-allowed":"pointer",opacity:jn?.6:1},children:kn?"Processing...":K??"Confirm Purchase"})]})},xe)}),rn]}):(!Q||!An)&&!(Kr&&gn==="full")?se(Rr,{children:rn}):sn(Rr,{children:[se(ur.Provider,{value:Kn,children:sn(qa,{flopay:Q,paypalFlopay:z,options:An??{billingApiUrl:L},onInstrument:ze,children:[Te===1&&se("button",{type:"button",onClick:In,children:"Retry payment methods"}),ue?sn(Rr,{children:[vn&&se("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:vn}),se(zu,{sessionId:ee,nonce:_?.clientSecret||void 0,billingApiUrl:L,session:_,submitLabel:yt,children:ue})]}):se(ss,{sessionId:ee,nonce:_?.clientSecret||void 0,telemetry:o,email:_?.customer?.email||Yt?.account?.email,userId:_?.customer?.id||Yt?.account?.userId,firstName:_?.customer?.firstName||Yt?.account?.firstName,lastName:_?.customer?.lastName||Yt?.account?.lastName,totalAmount:_?Math.round(Ru(_).total*100):0,currency:_?.currency?.toLowerCase()??"usd",onComplete:f,onError:b,onDecline:M,error:vn,onErrorChange:Vt,showPayPal:v,showStripe:q,enabledPaymentMethods:Te?[]:Re??le?.data.stripe?.enabledPaymentMethods??_?.gateways?.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:le?.data.stripe?.enabledPaymentMethodCountries,showApplePay:I,showGooglePay:G,layout:re,theme:ve,buttonsTheme:Le,buttonsStyles:Ce,appearance:Ye,cardButtonContent:$e,cardBackButtonContent:vt,cardTitleContent:Ke,onButtonClick:Me,onBeforeButtonClick:wt,onBuyerIdentityReady:qn,enableAVS:fe,...ut?{cardFieldOrder:ut}:{},...O?{cardPreFormSlot:O}:{},avsLayout:Ae,country:_?.customer?.country,city:_?.customer?.city,state:_?.customer?.state,onCountryChange:R,onZipChange:C,avsCheck:!!fe,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:ys(ue,re),className:Be,submitLabel:yt,directPaypal:$n,isSubscription:_?.mode==="subscription",session:_,dataAttachmentPending:yn,dataAttachmentRequiresIdentity:qt,debug:Y})]},xe)}),rn]})}function zu({sessionId:e,nonce:t,billingApiUrl:n,session:r,submitLabel:o,children:i}){return se(Rr,{children:ls.Children.map(i,s=>{if(!ls.isValidElement(s))return s;let l=s.props,y={};return l.sessionId||(y.sessionId=e),!l.nonce&&t&&(y.nonce=t),l.billingApiUrl||(y.billingApiUrl=n),l.submitLabel===void 0&&o!==void 0&&(y.submitLabel=o),r?.customer&&(l.email||(y.email=r.customer.email),l.userId||(y.userId=r.customer.id),l.firstName||(y.firstName=r.customer.firstName),l.lastName||(y.lastName=r.customer.lastName)),Object.keys(y).length===0?s:ls.cloneElement(s,y)})})}function Uu({onButtonClick:e,showPayPal:t,showStripe:n=!0,showApplePay:r,showGooglePay:o,theme:i,buttonsTheme:s,buttonsStyles:l,cardButtonContent:y,cardBackButtonContent:f,cardTitleContent:b}){let[g,M]=zt(!1),R=ar(()=>cc(i),[i]),C=ar(()=>{let I=R?.buttonsLayout??Au(s);return l?{...I,...l,cardButton:{...I.cardButton,...l.cardButton},cardFormContainer:{...I.cardFormContainer,...l.cardFormContainer},backButton:{...I.backButton,...l.backButton},backButtonIcon:{...I.backButtonIcon,...l.backButtonIcon},submitButton:{...I.submitButton,...l.submitButton},title:{...I.title,...l.title}}:I},[R,s,l]),v=R?.buttonsLayout?.cardButton?.borderRadius??R?.appearance.variables?.borderRadius??8,q=I=>se("div",{style:{height:I,borderRadius:v,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),Re=y===void 0?{boxSizing:"border-box",height:Ao,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(g){let I=C.cardInputBorder??"#e5e7eb",G=C.cardInputBackground??"white",Y=uo(f),re=uo(b);return sn("div",{style:{backgroundColor:C.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",...C.cardFormContainer},children:[sn("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[sn("button",{type:"button",onClick:()=>M(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:Y?0:"0.5rem",background:"none",border:"none",color:"#4b5563",fontSize:"0.85rem",fontWeight:500,padding:0,flexShrink:0,opacity:1,cursor:"pointer",...C.backButton},children:[se("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...C.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(yo,{content:f})]}),re?se("div",{style:{flex:1}}):se("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...C.title},children:se(Go,{content:b})})]}),se("div",{style:{backgroundColor:G,border:`1px solid ${I}`,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:G,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${I}`,borderLeft:`1px solid ${I}`,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:G,borderTop:"none",borderRight:`1px solid ${I}`,borderBottom:`1px solid ${I}`,borderLeft:`1px solid ${I}`,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:G,border:`1px solid ${I}`,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",...C.submitButton,opacity:.5}}),se("style",{children:`
|
|
36
36
|
@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }
|
|
37
37
|
@keyframes flopay-interim-expand {
|
|
38
38
|
0% { opacity: 0; max-height: 0; transform: translateY(-12px); }
|
|
39
39
|
40% { opacity: 1; }
|
|
40
40
|
100% { opacity: 1; max-height: 600px; transform: translateY(0); }
|
|
41
41
|
}
|
|
42
|
-
`})]})}return en("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&Y(ko),n&&(r||o)&&Y(ko),n&&oe("button",{type:"button",onClick:()=>{e?.("card"),m(!0)},style:{width:"100%",...Pe,backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:"8px",fontSize:_.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,..._.cardButton},onMouseDown:S=>{S.currentTarget.style.transform="scale(0.985)"},onMouseUp:S=>{S.currentTarget.style.transform="scale(1)"},children:oe(so,{content:p})}),oe("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}import{Fragment as Ou,jsx as Eo,jsxs as zu}from"react/jsx-runtime";var Bu=44;function Zl(e){return new Promise(t=>setTimeout(t,e))}function Fu(e,t){return e instanceof ia?e:new ia(e instanceof Error?e.message:t,"api_error")}function Du(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function Nu(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 Lu({sessionId:e,nonce:t,createSession:n,paymentMethodId:r,checkoutMethod:o,clientId:i,products:s,items:l,subscriptions:p,account:f,successUrl:C,cancelUrl:h,couponCodes:m,tagsData:w,utmMetadata:_,billingApiUrl:ae,locale:Y,theme:Pe,appearance:S,buttonsTheme:G,buttonsStyles:X,onSuccess:ce,onError:Te,onDecline:Fe,children:ve,disabled:Ue=!1,type:bt="button",style:ot,...$e}){let De=oa(()=>Au(ae),[ae]),ye=oa(()=>Nu({createSession:n,clientId:i,products:s,items:l,subscriptions:p,account:f,successUrl:C,cancelUrl:h,couponCodes:m,tagsData:w,utmMetadata:_}),[f,h,i,m,n,s,l,p,C,w,_]),[we,Qe]=aa(!1),[Z,Ie]=aa(null),[be,ct]=aa(null),[dt,U]=aa(!1),[V,de]=aa(null),fe=Ro(!0),ut=Ro(null),Ne=Ro(V),x=Ro(ce),at=Ro(Te),Ye=Ro(Fe),re=Rr(u=>Ma(ut,async B=>{try{return await u(B)}catch(_e){throw B.aborted?Zo(_e):_e}}),[]);_o(()=>{Ne.current=V},[V]),_o(()=>{x.current=ce},[ce]),_o(()=>{at.current=Te},[Te]),_o(()=>{Ye.current=Fe},[Fe]),_o(()=>(fe.current=!0,()=>{fe.current=!1,ut.current?.abort()}),[]),_o(()=>{if(typeof window>"u")return;let u=B=>{B.key==="Escape"&&de(null)};return window.addEventListener("keydown",u),()=>{window.removeEventListener("keydown",u)}},[]);let Q=Rr((u,B=Xo)=>{Ye.current?.(nn(B,u,{code:u.code,declineCode:u.declineCode}))},[]),L=Rr(async u=>{fe.current&&(ct(null),U(u.result.status==="authorized"),Ie("success"),await Zl(600),fe.current&&Bt(()=>x.current?.(u)))},[]),Ae=Rr(async(u,B)=>{fe.current&&(at.current?.(u),B?.emitDecline&&Q(u,B.method),ct(u.message),U(!1),Ie("error"),await Zl(400))},[Q]),xe=Rr(async(u,B,_e)=>{let Ke=u.data.session??null;if(!Ke)throw new ia("No session data returned","api_error");let Re=Ke.clientSecret||t;if(Mr(Ke)){await L({result:Sr(Ke,B),session:Ke,sessionId:Ke.id||B,autoCompleted:!1});return}if(Ke.status==="expired")throw ha(Ke);try{if(u.autoProcessingPending){let N=u.autoProcessingPending,Ct=new is(De),Et=await re(O=>Ct.waitForCheckoutSessionCompletion(N.sessionId,{initialDelayMs:N.retryAfterMs,nonce:Re,statusUrl:N.statusUrl,signal:O})),pt=Et.data.session,un=Et.autoProcessingError?.type==="3ds_required"&&Et.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:Et.autoProcessingError.nextActionRedirectUrl}:null;if(un&&B&&Re){let O=await re(Ot=>Co(un,{billingApiUrl:De,sessionId:B,nonce:Re,session:Ke,signal:Ot}));await L({result:O,session:Ke,sessionId:Ke.id||B,autoCompleted:!1});return}if(Et.autoProcessingError)throw gr(Et.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:Et.autoProcessingError.checkoutMethod});if(!Mr(pt))throw po(pt);await L({result:Sr(pt,B),session:pt,sessionId:pt.id||B,autoCompleted:!1});return}if(u.autoProcessingError){let N=u.autoProcessingError.nextActionRedirectUrl;if(u.autoProcessingError.type==="3ds_required"&&N&&B&&Re){let Ct=await re(O=>Ti({billingApiUrl:De,sessionId:B,nonce:Re,nextActionRedirectUrl:N,signal:O}));if(Ct.status==="declined")throw gr({type:Ct.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:Ct.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:u.autoProcessingError.checkoutMethod});let un=(await new is(De).waitForCheckoutSessionCompletion(B,{initialDelayMs:0,nonce:Re})).data.session;if(!Mr(un))throw gr({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:u.autoProcessingError.checkoutMethod});await L({result:Sr(un,B),session:un,sessionId:un.id||B,autoCompleted:!1});return}throw gr(u.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:u.autoProcessingError.checkoutMethod})}if(_e?.fromCreateSession&&u.autoProcessingAttempted===!0)throw gr({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let $t=await So({billingApiUrl:De,sessionId:B??Ke.id,session:Ke,nonce:Re});if($t.type==="next_action_required"&&Re){let N=B??Ke.id,Ct=await re(Et=>Co($t,{billingApiUrl:De,sessionId:N,nonce:Re,session:Ke,signal:Et}));await L({result:Ct,session:Ke,sessionId:Ke.id||N,autoCompleted:!1});return}if($t.type!=="success")throw gr({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await L({result:$t.result,session:Ke,sessionId:Ke.id||B,autoCompleted:!1})}catch($t){let N=Qo($t);if(N.code==="three_ds_aborted")return;let Ct=Ke.id||B;await Ae(N,{emitDecline:!0,method:N.checkoutMethod??Xo}),Du(N,Ct)&&Ct&&fe.current&&de({sessionId:Ct,errorMessage:N.message,nonce:Re||void 0,payPalOrderId:N.orderId})}},[t,De,re,Ae,L]),Me=Rr(async u=>{if($e.onClick?.(u),!(u.defaultPrevented||Ue||we)){if(de(null),e&&ye){let B=new ia("Provide either sessionId or create-session props, not both.","validation_error");await Ae(B),fe.current&&(Ie(null),ct(null));return}if(!e&&!ye){let B=new ia("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await Ae(B),fe.current&&(Ie(null),ct(null));return}Qe(!0),ct(null),U(!1),Ie("processing");try{let B=new is(De);if(e){let _e=await B.getUnifiedCheckoutSession(e,t);await xe(_e,e);return}try{let _e=await B.createAndFetchSession({...ye});await xe(_e,_e.data.session?.id??null,{fromCreateSession:!0})}catch(_e){if(va(_e)==="session_auto_completed"){await L({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw _e}}catch(B){await Ae(Fu(B,"Automatic payment failed. Please try again."))}finally{fe.current&&(Ie(null),ct(null),Qe(!1))}}},[$e.onClick,ye,Ue,we,t,xe,De,e,Ae,L]),qe=Rr(u=>{let B=Ne.current;de(null),x.current?.({result:u,session:null,sessionId:B?.sessionId??null,autoCompleted:!1})},[]),ke=Rr(u=>{at.current?.(u)},[]),Ee=Rr(u=>{Ye.current?.(u)},[]),ee=oa(()=>Mu(Pe),[Pe]),dn=oa(()=>{let u=ee?.buttonsLayout??xu(G);return X?{...u,...X,cardButton:{...u.cardButton,...X.cardButton}}:u},[ee,G,X]),Yt=oa(()=>{let u=ee?.appearance;return S?u?{...u,...S,variables:{...u.variables,...S.variables}}:S:u},[S,ee]),H=Yt?.variables,Je=H?.colorPrimary??"#4A49FF",$=H?.colorPrimaryHover??qo(Je,.12),K=H?.borderRadius??"8px";return zu(Ou,{children:[Eo("button",{...$e,type:bt,onClick:Me,disabled:Ue||we,"aria-busy":we,style:{width:"100%",...ve===void 0?{boxSizing:"border-box",height:Bu,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...dn.cardButton,...Yi({themeBundle:ee,resolvedPrimaryColor:Je,resolvedBorderRadius:K,submitButtonStyle:dn.submitButton,explicitPrimaryColor:H?.colorPrimary}),fontSize:dn.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:Ue||we?"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:Ue||we?.6:1,...ot},onMouseEnter:u=>{$e.onMouseEnter?.(u),!u.defaultPrevented&&!Ue&&!we&&(ee||H?.colorPrimary)&&(u.currentTarget.style.backgroundColor=$)},onMouseLeave:u=>{$e.onMouseLeave?.(u),!u.defaultPrevented&&(ee||H?.colorPrimary)&&(u.currentTarget.style.backgroundColor=Je)},onMouseDown:u=>{$e.onMouseDown?.(u),u.defaultPrevented||(u.currentTarget.style.transform="scale(0.985)")},onMouseUp:u=>{$e.onMouseUp?.(u),u.defaultPrevented||(u.currentTarget.style.transform="scale(1)")},children:Eo(so,{content:ve})}),Z&&Eo(fr,{status:Z,errorMessage:be,authorized:dt}),V&&Eo("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:u=>{u.target===u.currentTarget&&de(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:Eo("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:Eo(as,{sessionId:V.sessionId,nonce:V.nonce,checkoutMode:"full",billingApiUrl:De,locale:Y,theme:Pe,...Yt?{appearance:Yt}:{},buttonsTheme:G,buttonsStyles:X,initialErrorMessage:V.errorMessage,initialPayPalOrderId:V.payPalOrderId,cardTitleContent:null,onComplete:qe,onError:ke,onDecline:Ee})})})]})}export{ka as DirectPayPalButton,Lu as FloPayAutomaticPaymentButton,vc as FloPayCardSetup,hc as FloPayCardSetupError,as as FloPayCheckout,Aa as FloPayProvider,Ji as SplitCardForm,si as VaultCardFields,Xm as dropThirdPartyOnlyError,Bc as useCheckout,Br as useFloPay,mi as usePayPalFloPay};
|
|
42
|
+
`})]})}return sn("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&q(Ao),n&&(r||o)&&q(Ao),n&&se("button",{type:"button",onClick:()=>{e?.("card"),M(!0)},style:{width:"100%",...Re,backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:"8px",fontSize:C.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,...C.cardButton},onMouseDown:I=>{I.currentTarget.style.transform="scale(0.985)"},onMouseUp:I=>{I.currentTarget.style.transform="scale(1)"},children:se(po,{content:y})}),se("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}import{Fragment as Yu,jsx as Bo,jsxs as Ju}from"react/jsx-runtime";var Ku=44;function pc(e){return new Promise(t=>setTimeout(t,e))}function Vu(e,t){return e instanceof fa?e:new fa(e instanceof Error?e.message:t,"api_error")}function Hu(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function Wu(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 Gu({sessionId:e,nonce:t,createSession:n,paymentMethodId:r,checkoutMethod:o,clientId:i,products:s,items:l,subscriptions:y,account:f,successUrl:b,cancelUrl:g,couponCodes:M,tagsData:R,utmMetadata:C,billingApiUrl:v,locale:q,theme:Re,appearance:I,buttonsTheme:G,buttonsStyles:Y,onSuccess:re,onError:ve,onDecline:Le,children:Ce,disabled:$e=!1,type:vt="button",style:Ke,...Ne}){let Me=ya(()=>qu(v),[v]),wt=ya(()=>Wu({createSession:n,clientId:i,products:s,items:l,subscriptions:y,account:f,successUrl:b,cancelUrl:g,couponCodes:M,tagsData:R,utmMetadata:C}),[f,g,i,M,n,s,l,y,b,R,C]),[fe,ut]=ma(!1),[O,Ae]=ma(null),[yt,Be]=ma(null),[it,N]=ma(!1),[ue,ge]=ma(null),K=Mo(!0),Ge=Mo(null),Ve=Mo(ue),L=Mo(re),st=Mo(ve),Ye=Mo(Le),He=xr(c=>$a(Ge,async w=>{try{return await c(w)}catch(ne){throw w.aborted?sa(ne):ne}}),[]);xo(()=>{Ve.current=ue},[ue]),xo(()=>{L.current=re},[re]),xo(()=>{st.current=ve},[ve]),xo(()=>{Ye.current=Le},[Le]),xo(()=>(K.current=!0,()=>{K.current=!1,Ge.current?.abort()}),[]),xo(()=>{if(typeof window>"u")return;let c=w=>{w.key==="Escape"&&ge(null)};return window.addEventListener("keydown",c),()=>{window.removeEventListener("keydown",c)}},[]);let Ee=xr((c,w=ia)=>{Ye.current?.(dn(w,c,{code:c.code,declineCode:c.declineCode}))},[]),le=xr(async c=>{K.current&&(Be(null),N(c.result.status==="authorized"),Ae("success"),await pc(600),K.current&&Ft(()=>L.current?.(c)))},[]),mt=xr(async(c,w)=>{K.current&&(st.current?.(c),w?.emitDecline&&Ee(c,w.method),Be(c.message),N(!1),Ae("error"),await pc(400))},[Ee]),Q=xr(async(c,w,ne)=>{let k=c.data.session??null;if(!k)throw new fa("No session data returned","api_error");let $=k.clientSecret||t;if(Fr(k)){await le({result:Tr(k,w),session:k,sessionId:k.id||w,autoCompleted:!1});return}if(k.status==="expired")throw _a(k);try{if(c.autoProcessingPending){let ze=c.autoProcessingPending,Ue=new hs(Me),xt=await He(We=>Ue.waitForCheckoutSessionCompletion(ze.sessionId,{initialDelayMs:ze.retryAfterMs,nonce:$,statusUrl:ze.statusUrl,signal:We})),ee=xt.data.session,pn=xt.autoProcessingError?.type==="3ds_required"&&xt.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:xt.autoProcessingError.nextActionRedirectUrl}:null;if(pn&&w&&$){let We=await He(Dt=>Io(pn,{billingApiUrl:Me,sessionId:w,nonce:$,session:k,signal:Dt}));await le({result:We,session:k,sessionId:k.id||w,autoCompleted:!1});return}if(xt.autoProcessingError)throw Ir(xt.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:xt.autoProcessingError.checkoutMethod});if(!Fr(ee))throw go(ee);await le({result:Tr(ee,w),session:ee,sessionId:ee.id||w,autoCompleted:!1});return}if(c.autoProcessingError){let ze=c.autoProcessingError.nextActionRedirectUrl;if(c.autoProcessingError.type==="3ds_required"&&ze&&w&&$){let Ue=await He(We=>Ui({billingApiUrl:Me,sessionId:w,nonce:$,nextActionRedirectUrl:ze,signal:We}));if(Ue.status==="declined")throw Ir({type:Ue.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:Ue.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:c.autoProcessingError.checkoutMethod});let pn=(await new hs(Me).waitForCheckoutSessionCompletion(w,{initialDelayMs:0,nonce:$})).data.session;if(!Fr(pn))throw Ir({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:c.autoProcessingError.checkoutMethod});await le({result:Tr(pn,w),session:pn,sessionId:pn.id||w,autoCompleted:!1});return}throw Ir(c.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:c.autoProcessingError.checkoutMethod})}if(ne?.fromCreateSession&&c.autoProcessingAttempted===!0)throw Ir({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let ft=await _o({billingApiUrl:Me,sessionId:w??k.id,session:k,nonce:$});if(ft.type==="next_action_required"&&$){let ze=w??k.id,Ue=await He(xt=>Io(ft,{billingApiUrl:Me,sessionId:ze,nonce:$,session:k,signal:xt}));await le({result:Ue,session:k,sessionId:k.id||ze,autoCompleted:!1});return}if(ft.type!=="success")throw Ir({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await le({result:ft.result,session:k,sessionId:k.id||w,autoCompleted:!1})}catch(ft){let ze=la(ft);if(ze.code==="three_ds_aborted")return;let Ue=k.id||w;await mt(ze,{emitDecline:!0,method:ze.checkoutMethod??ia}),Hu(ze,Ue)&&Ue&&K.current&&ge({sessionId:Ue,errorMessage:ze.message,nonce:$||void 0,payPalOrderId:ze.orderId})}},[t,Me,He,mt,le]),oe=xr(async c=>{if(Ne.onClick?.(c),!(c.defaultPrevented||$e||fe)){if(ge(null),e&&wt){let w=new fa("Provide either sessionId or create-session props, not both.","validation_error");await mt(w),K.current&&(Ae(null),Be(null));return}if(!e&&!wt){let w=new fa("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await mt(w),K.current&&(Ae(null),Be(null));return}ut(!0),Be(null),N(!1),Ae("processing");try{let w=new hs(Me);if(e){let ne=await w.getUnifiedCheckoutSession(e,t);await Q(ne,e);return}try{let ne=await w.createAndFetchSession({...wt});await Q(ne,ne.data.session?.id??null,{fromCreateSession:!0})}catch(ne){if(Ra(ne)==="session_auto_completed"){await le({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw ne}}catch(w){await mt(Vu(w,"Automatic payment failed. Please try again."))}finally{K.current&&(Ae(null),Be(null),ut(!1))}}},[Ne.onClick,wt,$e,fe,t,Q,Me,e,mt,le]),Fe=xr(c=>{let w=Ve.current;ge(null),L.current?.({result:c,session:null,sessionId:w?.sessionId??null,autoCompleted:!1})},[]),Je=xr(c=>{st.current?.(c)},[]),lt=xr(c=>{Ye.current?.(c)},[]),z=ya(()=>$u(Re),[Re]),pt=ya(()=>{let c=z?.buttonsLayout??ju(G);return Y?{...c,...Y,cardButton:{...c.cardButton,...Y.cardButton}}:c},[z,G,Y]),Xe=ya(()=>{let c=z?.appearance;return I?c?{...c,...I,variables:{...c.variables,...I.variables}}:I:c},[I,z]),_=Xe?.variables,ct=_?.colorPrimary??"#4A49FF",Jt=_?.colorPrimaryHover??Wo(ct,.12),xe=_?.borderRadius??"8px";return Ju(Yu,{children:[Bo("button",{...Ne,type:vt,onClick:oe,disabled:$e||fe,"aria-busy":fe,style:{width:"100%",...Ce===void 0?{boxSizing:"border-box",height:Ku,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...pt.cardButton,...is({themeBundle:z,resolvedPrimaryColor:ct,resolvedBorderRadius:xe,submitButtonStyle:pt.submitButton,explicitPrimaryColor:_?.colorPrimary}),fontSize:pt.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:$e||fe?"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||fe?.6:1,...Ke},onMouseEnter:c=>{Ne.onMouseEnter?.(c),!c.defaultPrevented&&!$e&&!fe&&(z||_?.colorPrimary)&&(c.currentTarget.style.backgroundColor=Jt)},onMouseLeave:c=>{Ne.onMouseLeave?.(c),!c.defaultPrevented&&(z||_?.colorPrimary)&&(c.currentTarget.style.backgroundColor=ct)},onMouseDown:c=>{Ne.onMouseDown?.(c),c.defaultPrevented||(c.currentTarget.style.transform="scale(0.985)")},onMouseUp:c=>{Ne.onMouseUp?.(c),c.defaultPrevented||(c.currentTarget.style.transform="scale(1)")},children:Bo(po,{content:Ce})}),O&&Bo(wr,{status:O,errorMessage:yt,authorized:it}),ue&&Bo("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:c=>{c.target===c.currentTarget&&ge(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:Bo("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:Bo(gs,{sessionId:ue.sessionId,nonce:ue.nonce,checkoutMode:"full",billingApiUrl:Me,locale:q,theme:Re,...Xe?{appearance:Xe}:{},buttonsTheme:G,buttonsStyles:Y,initialErrorMessage:ue.errorMessage,initialPayPalOrderId:ue.payPalOrderId,cardTitleContent:null,onComplete:Fe,onError:Je,onDecline:lt})})})]})}export{Oa as DirectPayPalButton,Gu as FloPayAutomaticPaymentButton,Mc as FloPayCardSetup,xc as FloPayCardSetupError,gs as FloPayCheckout,qa as FloPayProvider,ss as SplitCardForm,bi as VaultCardFields,mm as dropThirdPartyOnlyError,Yc as useCheckout,Or as useFloPay,_i as usePayPalFloPay};
|