@flopay/react 1.9.22 → 1.9.24

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