@flopay/react 1.9.20 → 1.9.21
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +6 -4
- package/dist/index.cjs +9 -9
- package/dist/index.d.cts +5 -1
- package/dist/index.d.ts +5 -1
- package/dist/index.mjs +8 -8
- package/package.json +3 -3
package/dist/index.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import{a as Rt,b as yr,c as Oo,d as oi,e as zo,f as Ds,g as Ns,h as mc,i as yc}from"./chunk-CSBYK62Y.mjs";import{dropThirdPartyOnlyError as $m}from"@flopay/shared";import{PaymentAPI as ns}from"@flopay/js";import{FloPayError as ra,resolveBillingApiUrl as ku,resolveButtonsLayoutTheme as _u,resolveTheme as Ru}from"@flopay/shared";import{useCallback as xr,useEffect as wo,useMemo as ta,useRef as Io,useState as na}from"react";import{Fragment as so,jsx as Hn,jsxs as Ls}from"react/jsx-runtime";function fc(){return Ls(so,{children:[Ls("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:[Hn("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),Hn("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",Hn("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:Hn("path",{d:"M9 18l6-6-6-6"})})]})}function gc(){return Hn(so,{children:"Go back"})}function hc(){return Hn(so,{children:"Secure card checkout"})}function oo(e){return e!==void 0&&(e===""||e===null||e===!1)}function ao({content:e}){return Hn(so,{children:e===void 0?Hn(fc,{}):e})}function io({content:e}){return Hn(so,{children:e===void 0?Hn(gc,{}):e})}function Uo({content:e}){return Hn(so,{children:e===void 0?Hn(hc,{}):e})}import{classifyTelemetryFailure as vc,FloPayError as qn,isCardHolderNamePlaceholder as Os,isMoneySettledOutcome as Pc,isSetupIntentClientSecret as bc,isValidEmail as Cc}from"@flopay/shared";var Sc="Checkout is temporarily unavailable. Please try again later.";function ai(e){return{errorCode:"PROVIDER_LOAD_FAILED",failureCategory:e instanceof qn&&e.type==="authentication_error"?"invalid_response":"provider_runtime",stage:"provider_load",provider:"stripe",requestCategory:"provider_sdk"}}function wc(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 zs(){return new qn(Sc,"api_error",{code:"CheckoutInitializationFailed"})}function ii(e){return!!e?.gateways?.worldpayCorporateGateway}function Ur(e){return e?.status==="open"&&ii(e)}function Us(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 qs(e,t){if(t&&(!(e instanceof qn)||e.type==="authentication_error"))return ai(e);if(!(e instanceof qn&&wc(e))){if(!t&&!(e instanceof qn)&&(e instanceof TypeError||e instanceof SyntaxError))return{...vc(e,"NETWORK_REQUEST_FAILED"),stage:"session_read",requestCategory:"session_read"};if(!t&&e instanceof qn)return{errorCode:"NETWORK_REQUEST_FAILED",stage:"session_read",requestCategory:"session_read"};if(!(e instanceof qn))return{errorCode:"INTERNAL_SDK_ERROR",stage:"checkout_mount"}}}function lo(e,t,n,r={}){let o;return(i={})=>{if(o)return o;let s={...r,...i,email:i.email?.trim()||r.email?.trim()},l=Os(s.firstName,s.lastName);if(!Cc(s.email))return Promise.reject(new qn("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}));let p={};for(let[v,g]of Object.entries(s)){if(l&&v.endsWith("Name")||typeof g!="string")continue;let h=g.trim();h&&(p[v]=h)}return o=e.claimCheckoutSession(t,n,{accountData:p}),o.catch(()=>{}),o}}function js(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 si(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 $s(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(Os(e))return{};let[t,...n]=e?.trim().split(/\s+/)??[];return t?{firstName:t,lastName:n.join(" ")||void 0}:{}}function li(e,t){return t?{...e,...t}:e}function nn(e,t,n){let r=typeof t=="string"?t:t.message,o=typeof t=="string"?n?.code:n?.code??t.code,i=typeof t=="string"?n?.declineCode:n?.declineCode??t.declineCode;return{method:e,message:r,...o?{code:o}:{},...i?{declineCode:i}:{}}}var Ic=[{match:/^paypal authorization required\.?$/i,replacement:"For your additional security, please re-authenticate this payment via PayPal."}];function Ir(e){if(typeof e!="string")return e??void 0;let t=e.trim();if(!t)return e;for(let{match:n,replacement:r}of Ic)if(n.test(t))return r;return e}function jr(e,t){return e.status!=="authorized"?{status:"succeeded"}:{status:"authorized",paymentId:e.paymentId,sessionId:e.id||t||void 0,authorizationExpiresAt:e.authorizationExpiresAt}}function co(e){return e?.status==="authorized"||e?.status==="complete"}function Ks(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function ya(e){let t=Ks(e);return new qn(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function fa(e){return e instanceof qn||typeof e=="object"&&e!==null&&"code"in e?e.code:void 0}function ga(e){let t=Ks(e),n="checkout_processing_timeout";return t?n="authorization_expired":e?.status==="expired"&&(n="checkout_session_expired"),new qn(t?"Authorization has expired.":"Automatic payment failed. Please try again.","api_error",{code:n})}function qo(e,t){return e==="processing"||Pc(e,t)}function Vs(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}async function Ws(e,t){let n=e;if(bc(t)){if(!n?.retrieveSetupIntent)return null;let{setupIntent:i,error:s}=await n.retrieveSetupIntent(t);if(s)throw new qn(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 qn(o.message??"Failed to retrieve payment intent.","api_error",{...o.code?{code:o.code}:{}});return r??null}function Hs(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 ci(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 cu,PaymentAPI as La,SESSION_CREATE_TELEMETRY as du}from"@flopay/js";import{buildCheckoutDisplayData as uu,classifyTelemetryFailure as Vl,FloPayError as mn,isDetachedSessionEligible as pu,resolveBillingApiUrl as mu,resolveButtonsLayoutTheme as yu,resolveIdempotencyKey as Ol,resolveTheme as Wl,SDK_VERSION as Hl,telemetryStatusClass as fu}from"@flopay/shared";import Wi,{useCallback as wn,useEffect as gr,useMemo as Yn,useRef as Tt,useState as Ot}from"react";import{createContext as Gs}from"react";var Gn=Gs({flopay:null,paypalFlopay:null,billingApiUrl:""}),ar=Gs({session:null,loading:!1,error:null});import{PaymentAPI as mi}from"@flopay/js";import{classifyTelemetryFailure as Uc,FloPayError as yi,generateIdempotencyKey as qc,isValidEmail as Wo,normalizeGatewayEnvironment as jc,PAYPAL_VAULTED_PAYMENT_METHOD_TYPE as fi,SDK_VERSION as $c}from"@flopay/shared";import{loadScript as Kc}from"@paypal/paypal-js";import{useCallback as Cr,useEffect as At,useMemo as Ho,useRef as it,useState as Rr}from"react";import{isValidEmail as kc}from"@flopay/shared";import{useCallback as Ys,useEffect as _c,useRef as Js,useState as Zs}from"react";import{jsx as Xs,jsxs as $o}from"react/jsx-runtime";function Dn(e,t=!1){let{firstName:n,lastName:r,...o}=e,i=n?.trim(),s=r?.trim();return{...o,...i||t?{firstName:i??""}:{},...s||t?{lastName:s??""}:{}}}function uo(){let[e,t]=Zs(null),n=Js(null),r=Js(0),o=Ys((s,l)=>(n.current?.(null),r.current+=1,t({id:r.current,methodLabel:s,identity:l}),new Promise(p=>{n.current=p})),[]),i=Ys(s=>{let l=n.current;n.current=null,t(null),l?.(s)},[]);return _c(()=>()=>{n.current?.(null),n.current=null},[]),{request:e,collect:o,finish:i}}function po({identity:e,methodLabel:t,onComplete:n,onCancel:r,submitting:o=!1,testId:i="flopay-buyer-identity-pane"}){let[s,l]=Zs(e.email?.trim()??""),p=kc(s.trim());return $o("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:[$o("div",{style:{fontWeight:700},children:["Continue with ",t]}),$o("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",Xs("input",{type:"email",autoComplete:"email","data-testid":"flopay-email",required:!0,value:s,onChange:v=>l(v.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]}),$o("div",{style:{display:"flex",gap:"0.5rem"},children:[r&&Xs("button",{type:"button",onClick:r,style:{flex:1,minHeight:42},children:"Cancel"}),$o("button",{type:"button",disabled:!p||o,onClick:()=>{n(Dn({...e,email:s.trim()}))},style:{flex:2,minHeight:42},children:["Continue with ",t]})]})]})}function Rc(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 $r(e){if(typeof e!="string")return;let t=e.trim();return/^[a-z0-9_.-]{1,64}$/i.test(t)?t:void 0}function Pr(e){if(typeof e!="object"||e===null)return;let t=e;return $r(t.code)??$r(t.type)??$r(t.name)}function mo(e){if(!(typeof e!="object"||e===null))return $r(e.decline_code)}function Ko(e){return typeof e!="object"||e===null?!1:$r(e.type)?.toLowerCase()==="card_error"||mo(e)!==void 0}function br(e){let t=Rc(e)?.toLowerCase()??"",r=`${Pr(e)?.toLowerCase()??""} ${t}`;return r.includes("popup")&&r.includes("block")}import{resolveBillingApiUrl as Ec}from"@flopay/shared";import{useContext as ha}from"react";function kr(){return ha(Gn).flopay}function di(){return ha(Gn).paypalFlopay??null}function Tc(){return ha(ar)}function Qs(){return ha(Gn).billingApiUrl||Ec()}function va(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 Pa(e,t,n){return!e.inAppBrowser||n!=="order"?"popup":t==="app_switch"||t==="redirect"?t:"popup"}import{FLO_INSTRUMENT_SCHEMA_VERSION as Ac}from"@flopay/shared";import{useCallback as Mc,useRef as ba}from"react";var xc={"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 Bc(e){return e==="stripe"||e==="paypal"?e:void 0}function Fc(e){let t=Bc(e.provider),n={schemaVersion:Ac,...t?{gateway:t}:{}};if(e.class==="lifecycle"){let r=xc[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 ui=new Set(["checkout_mount","sdk_loaded","form_rendered","card_expanded"]);function yo(e,t){let n=ba(e);n.current=e;let r=ba(new Set),o=ba(t),i=ba(t);return Oo(()=>{i.current=t,o.current!==t&&(o.current=t,r.current.clear())},[t]),Mc(s=>{if(i.current!==t)return;let l=Fc(s);if(l){if(ui.has(l.name)){if(r.current.has(l.name))return;r.current.add(l.name)}Rt(()=>n.current?.(l))}},[t])}var Dc=Symbol.for("@flopay/js.telemetry.bridge.v1"),Nc=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function Lc(){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 Oc(e){let t=Lc(),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 Ca(e){let t=globalThis[Nc];return Oc(t?.(e)??{})}function Qt(e){if(e)return e[Dc]}import{useCallback as _r,useEffect as zc,useRef as pi}from"react";function Vo(e){let t=pi(0),n=pi(null),r=pi(null),o=_r((y=r.current)=>{y?.timer&&(clearTimeout(y.timer),y.timer=null)},[]),i=_r(y=>{o();let _=t.current+1;return t.current=_,n.current=null,r.current={generation:_,method:y,timer:null,yieldedControl:!1},_},[o]),s=_r(y=>{let _=r.current;return y!==void 0&&_?.generation!==y?!1:(o(_),r.current=null,(y===void 0||n.current===y)&&(n.current=null),!0)},[o]),l=_r(y=>{let _=r.current,M=y??_?.generation??t.current;(y===void 0||_?.generation===y)&&(o(_),r.current=null),n.current=M},[o]),p=_r(y=>n.current===(y??t.current),[]),v=_r(y=>r.current?.generation===y&&n.current!==y,[]),g=_r(()=>{let y=r.current;y&&(y.yieldedControl=!0,o(y))},[o]),h=_r(()=>{let y=r.current;!y?.yieldedControl||document.visibilityState!=="visible"||(o(y),y.timer=setTimeout(()=>{y.timer=null,r.current?.generation===y.generation&&(r.current=null,n.current=y.generation,e(y.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}))},600))},[o,e]);return zc(()=>{let y=()=>{document.visibilityState==="visible"?h():g()};return document.addEventListener("visibilitychange",y),window.addEventListener("blur",g),window.addEventListener("focus",h),()=>{document.removeEventListener("visibilitychange",y),window.removeEventListener("blur",g),window.removeEventListener("focus",h),o()}},[o,g,h]),{startAttempt:i,finishAttempt:s,invalidateAttempt:l,isAttemptInvalidated:p,isAttemptCurrent:v,generationRef:t}}import{jsx as Kr,jsxs as hi}from"react/jsx-runtime";var Sa=45,Vc=1e3,Wc=11e3,Hc=["https://www.paypal.com","https://www.sandbox.paypal.com"],gi="We couldn't open PayPal. Try again or choose another payment method.",Gc={width:"100%",minHeight:Sa,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 Yc(e){return e.includes("No ack for postMessage init()")&&Hc.some(t=>e.includes(t))&&e.includes("10000ms")}var Jc={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 Xc(e){return!e.generationActive||e.kind==="teardown"?{action:"ignore"}:e.kind==="ineligible"?{action:"unavailable"}:e.automaticRetryAllowed&&!e.automaticRetryUsed?{action:"retry"}:{action:"exhaust",report:Jc[e.kind]??null}}function Zc(e,t){return e==="watchdog_expired"?"paypal_render_timeout":Yc(t)?"paypal_init_timeout":"paypal_init_failure"}function Qc(e,t=!1){return e?t?`${gi} Open this page in your system browser, then try again.`:`${gi} Allow pop-ups for this site, then try again.`:gi}function ed(e){let t=Ko(e),n=br(e);return t?{errorCode:"PROVIDER_RUNTIME_FAILED",popupBlocked:n,providerDeclined:t,terminalReason:"provider_declined"}:{errorCode:n?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",popupBlocked:n,providerDeclined:t,terminalReason:n?"popup_blocked":"provider_error"}}function td(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 nd(e){return e>=500?"5xx":e>=400?"4xx":e>=300?"3xx":"unknown"}function el({sessionId:e,nonce:t,billingApiUrl:n,email:r,billingName:o,onBuyerIdentityReady:i,clientId:s,environment:l,currency:p,isSubscription:v,providerObjectType:g,approvalPresentation:h,onTokenizedBody:y,onComplete:_,onErrorChange:M,onDecline:U,onTechnicalFailure:qe,isProcessing:ge=!1,onLoadStateChange:S,onInitializationStateChange:W,allowAutomaticRetry:Y=!0,onButtonClick:de,runBeforeButtonClick:Le,session:Se,existingOrderId:Re,telemetry:Ge,telemetryContext:St,onInstrument:tt,debug:je=!1}){let $e=kr(),ue=yo(tt,e),we=Ho(()=>{if($e)return null;let E=Ca({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:$c,enabled:Ge!==!1});return E.setCheckoutContext(St??{}),E.beginCheckout(St??{}),E},[n,$e,Ge,St?.checkoutMode,St?.layout]),Xe=Ho(()=>Qt($e),[$e]);At(()=>()=>{we&&we.flush().catch(()=>{}).finally(()=>we.destroy())},[we]);let ee=Ho(()=>({error:E=>{Xe?Xe.error(E):we?.error(E),ue({class:"technical_error",errorCode:E.requestCategory==="intent_create"?"PAYMENT_PROCESSING_FAILED":E.errorCode,requestCategory:E.requestCategory,provider:E.provider})},log:E=>{Xe?Xe.log(E):we?.log(E),ue({class:"lifecycle",name:E.name,provider:E.provider})},performance:E=>{Xe?Xe.performance(E):we?.performance(E)},terminal:E=>{Xe?Xe.terminal(E):we?.terminal(E)},startTiming:()=>Xe?.now()??we?.now()??0,elapsed:E=>Xe?.elapsed(E)??Math.max(0,(we?.now()??E)-E)}),[ue,Xe,we]),Ie=it(null),he=it(0),st=it(null),lt=it(null),T=it(null),$=it(!1),[Ee,ie]=Rr(!1),[rt,A]=Rr(!1),[Te,dt]=Rr(0),We=it(0),[se,x]=Rr(!1),Q=it(!1),Me=it(!1),[ot,ke]=Rr(!1),[Ke,_e]=Rr(!1),{request:le,collect:ve,finish:Vt}=uo(),H=it({sessionId:e,required:!Wo(r?.trim()||Se?.customer?.email?.trim())});H.current.sessionId!==e&&(H.current={sessionId:e,required:!Wo(r?.trim()||Se?.customer?.email?.trim())});let Mt=H.current.required,mt=Ho(()=>n.replace(/\/+$/,""),[n]),ne=Se?.gateways?.paypal?.providerObjectType??g,u=ne??(v?"subscription":"order"),[w]=Rr(va),xe=Se?.gateways?.paypal?.approvalPresentation??h,me=Pa(w,xe==="app_switch"?"app_switch":void 0,u),Ct=ne==="order"||ne==="setup_token",nt=Ho(()=>JSON.stringify([mt,s,p,l??"",u,Ct,me,e,Re??""]),[mt,s,p,l,Re,u,Ct,me,e]),xt=it(nt),K=xt.current!==nt,Wt=it(je),wt=it(null),[yn,sr]=Rr([]),N=Cr(E=>{Wt.current&&sr(be=>[...be,`${new Date().toISOString().slice(11,23)} ${E}`])},[]);At(()=>{Wt.current=je,je&&N("debug:enabled"),wt.current?.setEnabled(je)},[N,je]);let fn=it(y),In=it(_),cn=it(M),rn=it(U),gn=it(qe),Jn=it(de),dn=it(S),Ht=it(W),Ae=it(i),Oe=it(Le),on=it(Se),ut=it(r),jn=it(o),Bt=it(t),Gt=it(null),gt=it(new Map),$t=it(new Map),un=it(!1);At(()=>(un.current=!0,()=>{un.current=!1}),[]),At(()=>{fn.current=y},[y]),At(()=>{Ae.current=i},[i]),At(()=>{In.current=_},[_]),At(()=>{cn.current=M},[M]),At(()=>{rn.current=U},[U]),At(()=>{gn.current=qe},[qe]),At(()=>{Jn.current=de},[de]),At(()=>{dn.current=S},[S]),At(()=>{Ht.current=W},[W]),At(()=>{Oe.current=Le},[Le]),At(()=>{on.current=Se},[Se]),At(()=>{ut.current=r},[r]),At(()=>{jn.current=o},[o]),At(()=>{Bt.current=t},[t]),At(()=>{We.current=Te},[Te]),At(()=>{se&&T.current?.focus()},[se,Te]);let Ft=Cr(()=>{window.setTimeout(()=>{T.current?.focus()},0)},[]),It=Cr(()=>{ie(!1),dt(E=>E+1)},[]),an=Cr(()=>{x(!1),(Ie.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??Ie.current)?.focus?.()},[]);At(()=>{!Ee||!$.current||($.current=!1,an())},[an,Ee,Te]);let Nn=Cr((E,be)=>{let I=be?.popupBlocked??br(E),Nt=Qc(I,w.inAppBrowser),Pn=gn.current;if(Pn){let sn=I&&w.inAppBrowser?new yi(Nt,"api_error",{code:be?.code??"paypal_popup_blocked"}):E;Pn("paypal",sn,be);return}cn.current?.(Nt)},[w.inAppBrowser]),vt=Cr(E=>{let be=st.current,I=lt.current;be===null||!I||(ee.log({...I,name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:E}),ee.performance({...I,stage:"overlay_return",durationMs:ee.elapsed(be),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:E}),st.current=null)},[ee]),J=Cr((E,be,I)=>{let Nt=lt.current;vt("overlay_timeout"),Nt&&ee.error({...Nt,errorCode:"REQUEST_TIMEOUT",failureCategory:"provider_runtime",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",statusClass:"timeout",terminalReason:"overlay_timeout"}),Nn(be,I),x(!0),It(),Ft()},[vt,Ft,Nn,It,ee]),{finishAttempt:hn,generationRef:vn,invalidateAttempt:Dt,isAttemptCurrent:zt,isAttemptInvalidated:Ln,startAttempt:$n}=Vo(J),Xn=Cr(()=>(x(!1),$n("paypal")),[$n]),Yt=Cr(E=>{Dt(E?.generation),E?.showRetry&&x(!0),E?.remount&&It(),E?.focus!==!1&&Ft()},[Ft,Dt,It]),ze=E=>{let be=Gt.current;return be&&$t.current.set(E,be),E};At(()=>{xt.current!==nt&&(xt.current=nt,Q.current=!1,Me.current=!1,ie(!1),A(!1),ke(!1),Ht.current?.("loading"))},[nt]),At(()=>{Rt(()=>dn.current?.(Ee&&!ot))},[Ee,ot]);let Ut=jc(l);At(()=>{let E={attempt:vn.current+1,...w,presentationMode:me},be=()=>lt.current??E,I={error:m=>ee.error({...m,...be()}),log:m=>ee.log({...m,...be()}),performance:m=>ee.performance({...m,...be()}),terminal:m=>ee.terminal({...m,...be()}),startTiming:ee.startTiming,elapsed:ee.elapsed},Nt=s?`${s.slice(0,6)}\u2026(len ${s.length})`:"(empty)",Pn=typeof navigator>"u"?"(no navigator)":navigator.userAgent;if(N(`mount clientId=${Nt} env=${l??"(unset)"}\u2192${Ut??"live"} ccy=${p} sub=${v}`),N(`ua=${Pn.slice(0,80)}${Pn.length>80?"\u2026":""}`),!s){N("FAIL: clientId empty \u2014 gateway misconfigured"),ke(!0),I.error({errorCode:"CONFIGURATION_INVALID",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),console.error("[FloPay] DirectPayPal: clientId empty \u2014 gateway misconfigured");return}if(!Ie.current){N("FAIL: containerRef not attached");return}he.current=I.startTiming(),I.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let sn=!1,On=!1,ae=()=>sn||On,bn,Br=!1,Gr=()=>{bn=qc(),bn||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),Br=!0},kn=null,wr=!1,lr=null,Zn=!1,Kt=()=>{!lr||Zn||(Zn=!0,lr.close().catch(()=>{}))},_n=!1,vr=!1,zn=Ie.current,Rn=null,Qn=null,er=[],Pt=null,Cn=!1,Kn=!1,tr=null,En=m=>{if(!m||typeof m.getBoundingClientRect!="function")return"(no rect)";let d=m.getBoundingClientRect();return`${Math.round(d.width)}\xD7${Math.round(d.height)}`},Ve=m=>{if(!m)return"(empty)";try{let d=new URL(m,typeof window>"u"?"https://localhost":window.location.href),C=d.pathname.toLowerCase();return C.includes("checkcaptcha")||C.includes("captcha")?`CAPTCHA(${d.host}${C})`:C.includes("risk")||C.includes("challenge")?`RISK(${d.host}${C})`:C.includes("smart/buttons")?`smart-buttons(${d.host})`:`${d.host}${C}`.slice(0,100)}catch{return m.slice(0,80)}},tn=m=>{let d=m.getAttribute("src"),C=m.getAttribute("srcdoc"),L=m.getAttribute("name"),te=m.getAttribute("sandbox"),V=[];return d&&V.push(`src=${Ve(d)}`),C&&V.push(`srcdoc[${C.length}ch]`),!d&&!C&&V.push("src=(empty) srcdoc=(empty)"),L&&V.push(`name=${L.slice(0,40)}`),te!==null&&V.push(`sandbox="${te.slice(0,40)}"`),V.join(" ")},pn=m=>{if(!(m instanceof HTMLIFrameElement))return"";try{let d=m.contentDocument;if(!d)return"cd=null";let C=d.body?.children.length??0,L=d.body?.innerHTML.length??0,te=d.head?.innerHTML.length??0;return`cd=same-origin readyState=${d.readyState} body[${C}children,${L}ch] head[${te}ch]`}catch(d){return`cd=cross-origin(${d.message.slice(0,30)})`}},cr=[],Fr=m=>{if(ae())return;let d=m.message??String(m.error??"(no message)");d&&(d.toLowerCase().includes("paypal")||d.toLowerCase().includes("zoid")||d.toLowerCase().includes("postrobot")||d.toLowerCase().includes("storage"))&&(N(`window:error ${d.slice(0,140)}`),cr.push(d))},nr=m=>{if(ae())return;let d=m.reason instanceof Error?m.reason.message:String(m.reason??"(no reason)");d&&(d.toLowerCase().includes("paypal")||d.toLowerCase().includes("zoid")||d.toLowerCase().includes("postrobot")||d.toLowerCase().includes("storage"))&&(N(`window:rejection ${d.slice(0,140)}`),cr.push(d))},dr={value:0},Tn=()=>{Rn?.disconnect(),Rn=null,Qn?.disconnect(),Qn=null;for(let m of er.splice(0))clearTimeout(m);Kn=!1,Cn&&typeof window<"u"&&(window.removeEventListener("error",Fr),window.removeEventListener("unhandledrejection",nr)),Cn=!1},An=()=>{if(!(Cn||ae()||_n)){if(Cn=!0,cr.length=0,dr.value=0,typeof window<"u"&&(window.addEventListener("error",Fr),window.addEventListener("unhandledrejection",nr)),typeof PerformanceObserver<"u")try{Qn=new PerformanceObserver(m=>{if(!ae())for(let d of m.getEntries()){if(!d.name.toLowerCase().includes("paypal"))continue;dr.value+=1;let C=Math.round(d.duration);N(`net ${C}ms ${d.name.slice(0,90)}`)}}),Qn.observe({type:"resource",buffered:!0})}catch{}tr?.()}},Dr=()=>{Pt&&(clearTimeout(Pt),Pt=null)},Un=()=>{Tn(),Dr()},Nr={setEnabled:m=>{m?An():Tn()}};wt.current=Nr,Wt.current&&An();let Jt=m=>{if(!m)return!1;let d=m.toLowerCase();return d.includes("zoid destroyed")||d.includes("destroyed all components")||d.includes("window closed")||d.includes("detected container element removed")},k=m=>{if(ae()||Jt(m))return;let d=Ir(m)??m;Rt(()=>cn.current?.(d))},f=(m,d)=>{if(sn||wr)return;wr=!0,On=!0,Un(),Kt();let C=Xc({kind:m,generationActive:!0,automaticRetryAllowed:Y,automaticRetryUsed:Q.current});if(C.action==="retry"){Q.current=!0,ie(!1),_e(!1),A(!0),Ht.current?.("retrying"),kn=setTimeout(()=>{sn||dt(L=>L+1)},Vc);return}if(ie(!1),_e(!1),A(!1),ke(!0),C.action!=="ignore"){if(Ht.current?.("exhausted"),C.action==="unavailable"){console.error("[FloPay] DirectPayPal load/render failure:",d);return}C.report&&I.error({errorCode:C.report.errorCode,stage:C.report.stage,operationOutcome:C.report.operationOutcome,provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime"}),Me.current||(Me.current=!0,console.error("[FloPay] Direct PayPal initialization failed:",Zc(m,d)))}};ke(!1);let G=async(m,d=Gt.current)=>{if(ae())return;let C=d?.sessionId??e;if(fn.current){await fn.current(m,{sessionId:C,accountPatch:d?.accountPatch,nonce:d?.nonce});return}let L=I.startTiming();I.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let te=()=>{I.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),I.performance({stage:"processing",durationMs:I.elapsed(L),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment"})};try{let V=on.current,b=d?.accountPatch?.email??ut.current,Z=d?.accountPatch?.userId??V?.customer?.id??V?.accountData?.userId??"",pt=d?.accountPatch?.firstName??V?.customer?.firstName??V?.accountData?.firstName,qt=d?.accountPatch?.lastName??V?.customer?.lastName??V?.accountData?.lastName,fe=await new mi(mt,{telemetry:!1}).processPayment(Z,{sessionId:C,nonce:d?.nonce??Bt.current,paymentMethodCategory:"paypal",tokenizedData:m,accountData:{userId:Z,email:b??V?.customer?.email??"",...pt?{firstName:pt}:{},...qt?{lastName:qt}:{},country:d?.accountPatch?.country??V?.customer?.country??V?.accountData?.country??void 0,zip:d?.accountPatch?.zip??V?.customer?.zip??V?.accountData?.zip??void 0}});if(fe.ok){if(On||sn&&un.current)return;te(),I.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),Rt(()=>In.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(ae())return;let D=await fe.json().catch(()=>null),q=D?.message??"PayPal payment failed.",Fe=Ir(q)??q;te(),fe.status===400&&(typeof D?.declineCode=="string"||!Array.isArray(D?.fields))?I.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}):fe.status===400||fe.status===422?I.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx",terminalReason:"approved"}):I.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:nd(fe.status),failureCategory:fe.status>=500?"server_error":void 0}),k(Fe),Rt(()=>rn.current?.(nn("paypal",Fe,{code:D?.code,declineCode:D?.declineCode})));return}catch(V){if(ae())return;te(),I.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let b=V instanceof Error?V.message:"PayPal payment failed.",Z=Ir(b)??b;k(Z),Rt(()=>rn.current?.(nn("paypal",Z)));return}},B=()=>new yi("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),Ce=m=>ae()?Promise.reject(B()):Promise.resolve(m),ct=async m=>{if(ae())throw B();Br||Gr();let d=Gt.current,C=d?.sessionId??e,L=d?.nonce??Bt.current;I.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let te;try{te=await new mi(mt,{telemetry:!1}).createSessionIntent(C,L??"",Ct?{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:fi,paymentMethodId:null,intentKind:u==="setup_token"?"setup":"payment"}:{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"},{idempotencyKey:bn})}catch(V){throw I.error({...Uc(V,"PAYMENT_PROCESSING_FAILED","unknown"),stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"}),V}if(ae())throw B();if(te.provider!=="paypal"||te.providerObjectType!==u)throw new Error(m);return I.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),te.providerObjectId},ye=(m,d)=>{let C=d?.nonce??Bt.current;if(!C)return;let L=d?.sessionId??e,te=mo(m)??Pr(m)??"provider_declined";new mi(mt,{telemetry:!1}).reportSessionIntentDecline(L,C,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:te}).catch(()=>{})},z=Te;N("loadScript:scheduled (deferred 1 tick)");let X=null,F=setTimeout(()=>{if(sn){N("loadScript:skipped (cancelled before defer ran)");return}N("loadScript:start");let m=Ut==="live"?"production":Ut,d={};u==="subscription"?d={intent:"subscription",vault:!0}:u==="order"&&(d={intent:"capture"}),X=Kc({clientId:s,currency:p,...d,...m?{environment:m}:{},...m==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}});let C=!1;X.then(L=>{if(C=!0,N(`loadScript:resolved inactive=${ae()} ns=${!!L} buttons=${!!L?.Buttons}`),ae())return;if(!L?.Buttons){N("FAIL: namespace missing Buttons factory"),f("namespace_unusable","PayPal SDK did not expose the Buttons factory.");return}I.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),I.performance({stage:"provider_ready",durationMs:I.elapsed(he.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),I.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let te=async(fe,D)=>{if(ae()||We.current!==z)return;let q=fe.vaultSetupToken??fe.subscriptionID??fe.orderID??"",Fe=q?$t.current.get(q):gt.current.get(z);if(!(!Fe||!zt(Fe.generation))&&hn(Fe.generation)){$t.current.delete(q),gt.current.delete(Fe.surfaceKey),vt("approved");try{if(_e(!0),Rt(()=>cn.current?.(null)),!q)throw new yi("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});let De=on.current,kt=qr(jn.current??[De?.customer?.firstName,De?.customer?.lastName].filter(Boolean).join(" ")),He=Dn({email:Fe.accountPatch?.email?.trim()||ut.current?.trim()||De?.customer?.email?.trim(),firstName:Fe.accountPatch?.firstName?.trim()||kt.firstName,lastName:Fe.accountPatch?.lastName?.trim()||kt.lastName});if(!Wo(He.email)||!(He.firstName||He.lastName))try{let Xt=td(await D?.order?.get?.());He=Dn({email:Xt.email||He.email,firstName:Xt.firstName||He.firstName,lastName:Xt.lastName||He.lastName})}catch{}if((Ae.current||Mt)&&!Wo(He.email)){let Xt=await ve("PayPal",He);if(!Xt)return;He=Xt}Wo(He.email)&&(Fe.accountPatch=Dn({...Fe.accountPatch,...He}),await Ae.current?.(He));let Mn;u==="setup_token"?Mn={id:q,type:"paypal_setup_token",isPaypal:!0,gateway:"paypal",paymentMethodType:fi}:Ct?Mn={id:q,isPaypal:!0,gateway:"paypal",paymentMethodType:fi}:Mn={id:q,isPaypal:!0},await G(Mn,Fe)}catch(De){k(De instanceof Error?De.message:"PayPal capture failed.")}finally{ae()||_e(!1)}}},V=fe=>{let D=Re?()=>Ce(Re):()=>ct(fe);return async()=>ze(await D())},b=L.Buttons({style:{layout:"horizontal",height:Sa,tagline:!1},...me==="app_switch"?{appSwitchWhenAvailable:!0}:{},onClick:async(fe,D)=>{if(ae()){await D.reject();return}Gr();let q=Oe.current,Fe={};if(q)try{let He=await q("paypal");if(ae()){await D.reject();return}if(!He.proceed){Gt.current=null,gt.current.delete(z),await D.reject();return}Fe={sessionId:He.sessionId,accountPatch:He.accountPatch,nonce:He.nonce}}catch(He){N(`onClick:runBeforeButtonClick rejected msg=${(He instanceof Error?He.message:String(He)).slice(0,120)}`),Gt.current=null,gt.current.delete(z),await D.reject();return}Rt(()=>Jn.current?.("paypal"));let De=Xn(),kt={generation:De,surfaceKey:z,...Fe};Gt.current=kt,gt.current.set(z,kt),lt.current={...E,attempt:De},await D.resolve(),I.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),I.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),st.current=I.startTiming()},createOrder:u==="order"?V("Failed to create PayPal order."):void 0,createSubscription:u==="subscription"?V("Failed to create PayPal subscription."):void 0,createVaultSetupToken:u==="setup_token"?async()=>ze(await ct("Failed to create PayPal setup token.")):void 0,onApprove:te,onCancel:()=>{if(ae())return;let fe=gt.current.get(z)??Gt.current;fe&>.current.delete(fe.surfaceKey),Gt.current=null,vt("cancelled"),I.terminal({outcome:"payment_cancelled",terminalReason:"cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),$.current=!0,Yt({generation:fe?.generation,remount:!0,focus:!1})},onError:fe=>{if(ae()||We.current!==z)return;let D=fe instanceof Error?fe.message:"PayPal failed to render.";if(N(`onError rendered=${_n} msg=${D.slice(0,120)}`),_n){let q=gt.current.get(z)??Gt.current;if(q&&!zt(q.generation)||!q&&Ln())return;if(Jt(D)){hn(q?.generation);return}let{errorCode:Fe,popupBlocked:De,providerDeclined:kt,terminalReason:He}=ed(fe);if(vt(He),kt){I.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:He}),ye(fe,q),Rt(()=>rn.current?.(nn("paypal",D))),q&>.current.delete(q.surfaceKey),Gt.current=null,hn(q?.generation);return}I.error({errorCode:Fe,failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",terminalReason:He}),q&>.current.delete(q.surfaceKey),Gt.current=null,Yt({generation:q?.generation,remount:!0,showRetry:!0,focus:!0}),Nn(fe,{code:"paypal_runtime_failed",popupBlocked:De});return}f(Jt(D)?"teardown":"pre_ready_callback",D)}}),Z=b.isEligible();if(N(`isEligible=${Z}`),I.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!Z){ie(!1),f("ineligible","PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}vr=!0,lr=b,tr=()=>{if(!Cn||Kn||ae()||_n)return;Kn=!0,N(`container:dims ${En(zn)} visibility=${typeof document>"u"?"(no document)":document.visibilityState}`),typeof MutationObserver<"u"&&(Rn=new MutationObserver(D=>{if(!ae()){for(let q of D)if(q.type==="childList")q.addedNodes.forEach(Fe=>{if(!(Fe instanceof Element))return;let De=Fe.tagName.toLowerCase(),kt=(Fe.getAttribute("title")??"").slice(0,40),He=De==="iframe"?` ${tn(Fe)}`:"";N(`child+ ${De}${kt?` title="${kt}"`:""}${He} dims=${En(Fe)}`)});else if(q.type==="attributes"&&q.target instanceof Element){let Fe=q.target;if(Fe.tagName.toLowerCase()!=="iframe")continue;let De=q.attributeName;(De==="src"||De==="srcdoc")&&N(`attr~ iframe ${De}=${De==="srcdoc"?`[${(Fe.getAttribute("srcdoc")??"").length}ch]`:Ve(Fe.getAttribute("src"))} dims=${En(Fe)}`)}}}),Rn.observe(zn,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let fe=D=>{if(ae()||_n)return;let q=zn.querySelectorAll("iframe"),Fe=typeof document<"u"&&"hasStorageAccess"in document;N(`watchdog:${D} container=${En(zn)} children=${zn.childElementCount} iframes=${q.length} visibility=${typeof document>"u"?"(no document)":document.visibilityState} cookies=${typeof navigator>"u"?"?":navigator.cookieEnabled} hasStorageAccessApi=${Fe} paypalNetRequests=${dr.value}`),q.forEach((De,kt)=>{let He=(De.getAttribute("title")??"").slice(0,40);N(` iframe[${kt}] ${En(De)}${He?` title="${He}"`:""} ${tn(De)}`);let Mn=pn(De);Mn&&N(` ${Mn}`)}),cr.length===0&&N(" (no PayPal/zoid window errors captured)")};er.push(setTimeout(()=>fe("3s"),3e3)),er.push(setTimeout(()=>fe("8s"),8e3)),er.push(setTimeout(()=>fe("15s"),15e3))},tr(),N("render:start");let qt=I.startTiming();Pt=setTimeout(()=>{ae()||_n||(N("watchdog:11s retryable render timeout"),f("watchdog_expired","PayPal Buttons render did not settle within 11000ms."))},Wc);let Be=b.render(zn);(async()=>{try{if(await Be,N(`render:resolved inactive=${ae()}`),Un(),ae()){Kt();return}_n=!0,ie(!0),A(!1),Ht.current?.("ready"),I.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),I.performance({stage:"checkout_render",durationMs:I.elapsed(qt),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}catch(fe){let D=fe instanceof Error?fe.message:"PayPal failed to render.";N(`render:rejected msg=${D.slice(0,120)}`),Un(),f(Jt(D)?"teardown":"render_rejected",D)}})()}).catch(L=>{let te=L instanceof Error?L.message:"PayPal operation failed.";N(`provider:failed msg=${te.slice(0,120)}`);let V="script_rejected";C&&Jt(te)?V="teardown":C&&vr&&(V="render_rejected"),f(V,te)})},0);return()=>{sn=!0,clearTimeout(F),kn&&clearTimeout(kn),Un(),wt.current===Nr&&(wt.current=null),Kt(),st.current=null,lt.current=null}},[Y,mt,s,p,l,u,me,Ct,e,Re,Te,ee,ve,Mt,N,vt]);let Pe=je?hi("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:ot?"#fef2f2":"#f3f4f6",border:`1px solid ${ot?"#fca5a5":"#d1d5db"}`,borderRadius:6,color:"#111827",font:"11px/1.35 ui-monospace, SFMono-Regular, Menlo, monospace",whiteSpace:"pre-wrap",wordBreak:"break-word",maxHeight:220,overflowY:"auto"},children:[`FloPay/DirectPayPal-debug (ready=${Ee} failed=${ot})`,yn.length===0?`
|
|
1
|
+
import{a as Bt,b as fr,c as Uo,d as si,e as qo,f as zs,g as Us,h as hc,i as vc}from"./chunk-CSBYK62Y.mjs";import{dropThirdPartyOnlyError as Xm}from"@flopay/shared";import{PaymentAPI as is}from"@flopay/js";import{FloPayError as ia,resolveBillingApiUrl as Au,resolveButtonsLayoutTheme as xu,resolveTheme as Mu}from"@flopay/shared";import{useCallback as Rr,useEffect as _o,useMemo as oa,useRef as Ro,useState as aa}from"react";import{Fragment as co,jsx as Qn,jsxs as qs}from"react/jsx-runtime";function Pc(){return qs(co,{children:[qs("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[Qn("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),Qn("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",Qn("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"#9ca3af",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{position:"absolute",right:"1rem"},"aria-hidden":"true",children:Qn("path",{d:"M9 18l6-6-6-6"})})]})}function bc(){return Qn(co,{children:"Go back"})}function Cc(){return Qn(co,{children:"Secure card checkout"})}function io(e){return e!==void 0&&(e===""||e===null||e===!1)}function so({content:e}){return Qn(co,{children:e===void 0?Qn(Pc,{}):e})}function lo({content:e}){return Qn(co,{children:e===void 0?Qn(bc,{}):e})}function jo({content:e}){return Qn(co,{children:e===void 0?Qn(Cc,{}):e})}import{classifyTelemetryFailure as Sc,FloPayError as jn,isCardHolderNamePlaceholder as js,isMoneySettledOutcome as wc,isSetupIntentClientSecret as Ic,isValidEmail as kc}from"@flopay/shared";var _c="Checkout is temporarily unavailable. Please try again later.";function li(e){return{errorCode:"PROVIDER_LOAD_FAILED",failureCategory:e instanceof jn&&e.type==="authentication_error"?"invalid_response":"provider_runtime",stage:"provider_load",provider:"stripe",requestCategory:"provider_sdk"}}function Rc(e){return e.type==="validation_error"||e.code==="checkout_session_not_found"||e.code==="checkout_session_expired"||e.code==="checkout_session_completed"||e.code==="session_auto_completed"}function $s(){return new jn(_c,"api_error",{code:"CheckoutInitializationFailed"})}function ci(e){return!!e?.gateways?.worldpayCorporateGateway}function Ar(e){return e?.status==="open"&&ci(e)}function Ks(e,t,n){let r=e?.data.session,o=r?.gateways?.stripe?.enabledPaymentMethods??e?.data.stripe?.enabledPaymentMethods;return!!(n&&(r?.vault?.html||r?.gateways?.pcivault||o?.includes("card")||Ar(r))||t&&e?.data.paypal?.publishableKey)}function Vs(e,t){if(t&&(!(e instanceof jn)||e.type==="authentication_error"))return li(e);if(!(e instanceof jn&&Rc(e))){if(!t&&!(e instanceof jn)&&(e instanceof TypeError||e instanceof SyntaxError))return{...Sc(e,"NETWORK_REQUEST_FAILED"),stage:"session_read",requestCategory:"session_read"};if(!t&&e instanceof jn)return{errorCode:"NETWORK_REQUEST_FAILED",stage:"session_read",requestCategory:"session_read"};if(!(e instanceof jn))return{errorCode:"INTERNAL_SDK_ERROR",stage:"checkout_mount"}}}function uo(e,t,n,r={}){let o;return(i={})=>{if(o)return o;let s={...r,...i,email:i.email?.trim()||r.email?.trim()},l=js(s.firstName,s.lastName);if(!kc(s.email))return Promise.reject(new jn("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}));let p={};for(let[f,C]of Object.entries(s)){if(l&&f.endsWith("Name")||typeof C!="string")continue;let h=C.trim();h&&(p[f]=h)}return o=e.claimCheckoutSession(t,n,{accountData:p}),o.catch(()=>{}),o}}function Hs(e,t){if(!t)return e;if(!e)return t;let n;return"checkoutMetadata"in t?n=t:"checkoutMetadata"in e&&(n=e),{account:{...e.account??{},...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,...n?{checkoutMetadata:n.checkoutMetadata}:{},tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}}function di(e,t){return t?{...e,account:{...e.account,...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,..."checkoutMetadata"in t?{checkoutMetadata:t.checkoutMetadata}:{},tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}:e}function Ws(e,t){let n=e.products??[...(e.subscriptions??[]).map(i=>({type:"subscription",code:i.code??i.providerPlanId,name:i.subscriptionName??i.providerPlanName??i.code??i.providerPlanId??null,quantity:i.quantity??1,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount,currency:i.currency,metadata:i.metadata})),...(e.items??[]).map(i=>({type:"item",code:i.code??i.providerItemId,name:i.itemName??i.providerItemName??i.code??i.providerItemId??null,quantity:i.quantity??1,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount,currency:i.currency,metadata:i.metadata}))],r=n.reduce((i,s)=>i+(s.overrideAmount??s.totalAmount??0),0),o=e.currency??n.find(i=>i.currency)?.currency??"USD";return{id:"",clientSecret:"",mode:n.some(i=>i.type==="subscription")?"subscription":"payment",amount:Math.round(r*100),currency:o,status:"open",captureMethod:e.captureMethod,customer:{id:e.account.userId,email:e.account.email??"",firstName:e.account.firstName,lastName:e.account.lastName,gender:e.account.gender??void 0,city:e.account.city??void 0,state:e.account.state??void 0,country:e.account.country??void 0,zip:e.account.zip??void 0},successUrl:e.successUrl,cancelUrl:e.cancelUrl,checkoutMode:t??e.checkoutMode??"full",products:n.map((i,s)=>({uuid:`synthetic-${i.type??"item"}-${s}`,checkoutSessionId:"",type:i.type??"item",code:i.code,name:i.name??null,quantity:i.quantity??1,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount??null,currency:i.currency??o,metadata:i.metadata??null}))}}function Vr(e){if(js(e))return{};let[t,...n]=e?.trim().split(/\s+/)??[];return t?{firstName:t,lastName:n.join(" ")||void 0}:{}}function ui(e,t){return t?{...e,...t}:e}function nn(e,t,n){let r=typeof t=="string"?t:t.message,o=typeof t=="string"?n?.code:n?.code??t.code,i=typeof t=="string"?n?.declineCode:n?.declineCode??t.declineCode;return{method:e,message:r,...o?{code:o}:{},...i?{declineCode:i}:{}}}var Ec=[{match:/^paypal authorization required\.?$/i,replacement:"For your additional security, please re-authenticate this payment via PayPal."}];function xr(e){if(typeof e!="string")return e??void 0;let t=e.trim();if(!t)return e;for(let{match:n,replacement:r}of Ec)if(n.test(t))return r;return e}function Sr(e,t){return e.status!=="authorized"?{status:"succeeded"}:{status:"authorized",paymentId:e.paymentId,sessionId:e.id||t||void 0,authorizationExpiresAt:e.authorizationExpiresAt}}function Mr(e){return e?.status==="authorized"||e?.status==="complete"}function Gs(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function ha(e){let t=Gs(e);return new jn(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function va(e){return e instanceof jn||typeof e=="object"&&e!==null&&"code"in e?e.code:void 0}function po(e){let t=Gs(e),n="checkout_processing_timeout";return t?n="authorization_expired":e?.status==="expired"&&(n="checkout_session_expired"),new jn(t?"Authorization has expired.":"Automatic payment failed. Please try again.","api_error",{code:n})}function $o(e,t){return e==="processing"||wc(e,t)}function Ys(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}async function Js(e,t){let n=e;if(Ic(t)){if(!n?.retrieveSetupIntent)return null;let{setupIntent:i,error:s}=await n.retrieveSetupIntent(t);if(s)throw new jn(s.message??"Failed to retrieve setup intent.","api_error",{...s.code?{code:s.code}:{}});return i??null}if(!n?.retrievePaymentIntent)return null;let{paymentIntent:r,error:o}=await n.retrievePaymentIntent(t);if(o)throw new jn(o.message??"Failed to retrieve payment intent.","api_error",{...o.code?{code:o.code}:{}});return r??null}function Xs(e,t="automatic"){return{...typeof e=="number"&&Number.isFinite(e)&&e>0?{mode:"payment",amount:e,captureMethod:t==="manual"?"manual":"automatic_async"}:{mode:"setup"},paymentMethodTypes:["card"],setupFutureUsage:"off_session"}}function pi(e){let t=e&&typeof e=="object"?e:null;return t?.name==="IntegrationError"||t?.code==="elements_intent_mismatch"||t?.type==="invalid_request_error"?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response"}:{errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime"}}function Ko(e){let t=[e?.id,e?.originalPaymentMethodId];for(let n of t)if(typeof n=="string"&&n.startsWith("pm_"))return n}import{FloPay as yu,PaymentAPI as Ua,SESSION_CREATE_TELEMETRY as fu}from"@flopay/js";import{buildCheckoutDisplayData as gu,classifyTelemetryFailure as Gl,FloPayError as bn,isDetachedSessionEligible as hu,resolveBillingApiUrl as vu,resolveButtonsLayoutTheme as Pu,resolveIdempotencyKey as ql,resolveTheme as Yl,SDK_VERSION as Jl,telemetryStatusClass as bu}from"@flopay/shared";import Xi,{useCallback as Pn,useEffect as ur,useMemo as tr,useRef as Rt,useState as jt}from"react";import{createContext as Zs}from"react";var er=Zs({flopay:null,paypalFlopay:null,billingApiUrl:""}),cr=Zs({session:null,loading:!1,error:null});import{PaymentAPI as gi}from"@flopay/js";import{classifyTelemetryFailure as Kc,FloPayError as hi,generateIdempotencyKey as Vc,isValidEmail as Go,normalizeGatewayEnvironment as Hc,PAYPAL_VAULTED_PAYMENT_METHOD_TYPE as vi,SDK_VERSION as Wc}from"@flopay/shared";import{loadScript as Gc}from"@paypal/paypal-js";import{useCallback as kr,useEffect as Lt,useMemo as Yo,useRef as lt,useState as Dr}from"react";import{isValidEmail as Tc}from"@flopay/shared";import{useCallback as Qs,useEffect as Ac,useRef as el,useState as nl}from"react";import{jsx as tl,jsxs as Vo}from"react/jsx-runtime";function Bn(e,t=!1){let{firstName:n,lastName:r,...o}=e,i=n?.trim(),s=r?.trim();return{...o,...i||t?{firstName:i??""}:{},...s||t?{lastName:s??""}:{}}}function mo(){let[e,t]=nl(null),n=el(null),r=el(0),o=Qs((s,l)=>(n.current?.(null),r.current+=1,t({id:r.current,methodLabel:s,identity:l}),new Promise(p=>{n.current=p})),[]),i=Qs(s=>{let l=n.current;n.current=null,t(null),l?.(s)},[]);return Ac(()=>()=>{n.current?.(null),n.current=null},[]),{request:e,collect:o,finish:i}}function yo({identity:e,methodLabel:t,onComplete:n,onCancel:r,submitting:o=!1,testId:i="flopay-buyer-identity-pane"}){let[s,l]=nl(e.email?.trim()??""),p=Tc(s.trim());return Vo("div",{"data-testid":i,style:{display:"flex",flexDirection:"column",gap:"0.75rem",padding:"0.875rem",border:"1px solid #d1d5db",borderRadius:8,background:"#fff",color:"#262833"},children:[Vo("div",{style:{fontWeight:700},children:["Continue with ",t]}),Vo("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",tl("input",{type:"email",autoComplete:"email","data-testid":"flopay-email",required:!0,value:s,onChange:f=>l(f.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]}),Vo("div",{style:{display:"flex",gap:"0.5rem"},children:[r&&tl("button",{type:"button",onClick:r,style:{flex:1,minHeight:42},children:"Cancel"}),Vo("button",{type:"button",disabled:!p||o,onClick:()=>{n(Bn({...e,email:s.trim()}))},style:{flex:2,minHeight:42},children:["Continue with ",t]})]})]})}function xc(e){if(e instanceof Error)return e.message;if(typeof e=="object"&&e!==null){let t=e.message;return typeof t=="string"?t:void 0}return typeof e=="string"?e:void 0}function Hr(e){if(typeof e!="string")return;let t=e.trim();return/^[a-z0-9_.-]{1,64}$/i.test(t)?t:void 0}function wr(e){if(typeof e!="object"||e===null)return;let t=e;return Hr(t.code)??Hr(t.type)??Hr(t.name)}function fo(e){if(!(typeof e!="object"||e===null))return Hr(e.decline_code)}function Ho(e){return typeof e!="object"||e===null?!1:Hr(e.type)?.toLowerCase()==="card_error"||fo(e)!==void 0}function Ir(e){let t=xc(e)?.toLowerCase()??"",r=`${wr(e)?.toLowerCase()??""} ${t}`;return r.includes("popup")&&r.includes("block")}import{resolveBillingApiUrl as Mc}from"@flopay/shared";import{useContext as Pa}from"react";function Br(){return Pa(er).flopay}function mi(){return Pa(er).paypalFlopay??null}function Bc(){return Pa(cr)}function rl(){return Pa(er).billingApiUrl||Mc()}function ba(e){let t=e??(typeof navigator>"u"?"":navigator.userAgent),n=r=>({inAppBrowser:r!=="none",appFamily:r,popupCapability:"unknown"});return t?/FBAN|FBAV|FB_IAB|FBIOS/i.test(t)?n("facebook"):/Instagram/i.test(t)?n("instagram"):/musical_ly|BytedanceWebview|TikTok/i.test(t)?n("tiktok"):/Twitter|Snapchat|Pinterest|LinkedInApp|Line\/|MicroMessenger|GSA\//i.test(t)?n("other_in_app"):/Android.*;\s?wv\)/.test(t)||/(iPhone|iPad|iPod).*AppleWebKit(?!.*Safari)/.test(t)?n("generic_webview"):n("none"):n("none")}function Ca(e,t,n){return!e.inAppBrowser||n!=="order"?"popup":t==="app_switch"||t==="redirect"?t:"popup"}import{FLO_INSTRUMENT_SCHEMA_VERSION as Fc}from"@flopay/shared";import{useCallback as Dc,useRef as Sa}from"react";var Nc={"checkout.mount":"checkout_mount","sdk.initialize.ready":"sdk_loaded","provider.ready":"sdk_loaded","checkout.rendered":"form_rendered","vault.widget.ready":"form_rendered","vault.submission.started":"tokenize","payment.tokenization.started":"tokenize","payment.processing.started":"process_attempt","payment.intent.started":"process_attempt","vault.action.required":"3ds_challenge","payment.three_ds.handoff":"3ds_challenge"};function Lc(e){return e==="stripe"||e==="paypal"?e:void 0}function Oc(e){let t=Lc(e.provider),n={schemaVersion:Fc,...t?{gateway:t}:{}};if(e.class==="lifecycle"){let r=Nc[e.name];return r?{...n,name:r}:null}return e.class==="card_surface"?{...n,name:"card_expanded"}:e.errorCode==="CHECKOUT_SESSION_CREATE_FAILED"?{...n,name:"checkout_error",phase:"session_create"}:e.errorCode==="SDK_INITIALIZATION_FAILED"||e.errorCode==="PROVIDER_LOAD_FAILED"?{...n,name:"checkout_error",phase:"sdk_load"}:e.errorCode==="PAYMENT_PROCESSING_FAILED"?{...n,name:"checkout_error",phase:e.requestCategory==="intent_create"?"wallets":"process"}:null}var yi=new Set(["checkout_mount","sdk_loaded","form_rendered","card_expanded"]);function go(e,t){let n=Sa(e);n.current=e;let r=Sa(new Set),o=Sa(t),i=Sa(t);return Uo(()=>{i.current=t,o.current!==t&&(o.current=t,r.current.clear())},[t]),Dc(s=>{if(i.current!==t)return;let l=Oc(s);if(l){if(yi.has(l.name)){if(r.current.has(l.name))return;r.current.add(l.name)}Bt(()=>n.current?.(l))}},[t])}var zc=Symbol.for("@flopay/js.telemetry.bridge.v1"),Uc=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function qc(){return{error:()=>{},log:()=>{},performance:()=>{},terminal:()=>{},now:()=>globalThis.performance?.now()??0,elapsed:e=>Math.max(0,(globalThis.performance?.now()??e)-e),setCheckoutContext:()=>{},beginCheckout:()=>globalThis.performance?.now()??0,disable:()=>{},subscribe:()=>()=>{},flush:async()=>{},destroy:()=>{}}}function jc(e){let t=qc(),n=(o,i)=>o?o.bind(e):i,r=n(e.now,t.now);return{error:n(e.error,t.error),log:n(e.log,t.log),performance:n(e.performance,t.performance),terminal:n(e.terminal,t.terminal),now:r,elapsed:e.elapsed?e.elapsed.bind(e):o=>Math.max(0,r()-o),setCheckoutContext:n(e.setCheckoutContext,t.setCheckoutContext),beginCheckout:n(e.beginCheckout,t.beginCheckout),disable:n(e.disable,t.disable),subscribe:n(e.subscribe,t.subscribe),flush:n(e.flush,t.flush),destroy:n(e.destroy,t.destroy)}}function wa(e){let t=globalThis[Uc];return jc(t?.(e)??{})}function Qt(e){if(e)return e[zc]}import{useCallback as Fr,useEffect as $c,useRef as fi}from"react";function Wo(e){let t=fi(0),n=fi(null),r=fi(null),o=Fr((m=r.current)=>{m?.timer&&(clearTimeout(m.timer),m.timer=null)},[]),i=Fr(m=>{o();let w=t.current+1;return t.current=w,n.current=null,r.current={generation:w,method:m,timer:null,yieldedControl:!1},w},[o]),s=Fr(m=>{let w=r.current;return m!==void 0&&w?.generation!==m?!1:(o(w),r.current=null,(m===void 0||n.current===m)&&(n.current=null),!0)},[o]),l=Fr(m=>{let w=r.current,_=m??w?.generation??t.current;(m===void 0||w?.generation===m)&&(o(w),r.current=null),n.current=_},[o]),p=Fr(m=>n.current===(m??t.current),[]),f=Fr(m=>r.current?.generation===m&&n.current!==m,[]),C=Fr(()=>{let m=r.current;m&&(m.yieldedControl=!0,o(m))},[o]),h=Fr(()=>{let m=r.current;!m?.yieldedControl||document.visibilityState!=="visible"||(o(m),m.timer=setTimeout(()=>{m.timer=null,r.current?.generation===m.generation&&(r.current=null,n.current=m.generation,e(m.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}))},600))},[o,e]);return $c(()=>{let m=()=>{document.visibilityState==="visible"?h():C()};return document.addEventListener("visibilitychange",m),window.addEventListener("blur",C),window.addEventListener("focus",h),()=>{document.removeEventListener("visibilitychange",m),window.removeEventListener("blur",C),window.removeEventListener("focus",h),o()}},[o,C,h]),{startAttempt:i,finishAttempt:s,invalidateAttempt:l,isAttemptInvalidated:p,isAttemptCurrent:f,generationRef:t}}import{jsx as Wr,jsxs as bi}from"react/jsx-runtime";var Ia=45,Yc=1e3,Jc=11e3,Xc=["https://www.paypal.com","https://www.sandbox.paypal.com"],Pi="We couldn't open PayPal. Try again or choose another payment method.",Zc={width:"100%",minHeight:Ia,margin:"0 0 0.5rem",padding:"0.75rem 0.875rem",border:"1px solid #2563eb",borderRadius:8,background:"#eff6ff",color:"#1d4ed8",fontSize:"0.95rem",fontWeight:700,cursor:"pointer"};function Qc(e){return e.includes("No ack for postMessage init()")&&Xc.some(t=>e.includes(t))&&e.includes("10000ms")}var ed={script_rejected:{errorCode:"PROVIDER_LOAD_FAILED",stage:"provider_load",operationOutcome:"rejected"},namespace_unusable:{errorCode:"PROVIDER_LOAD_FAILED",stage:"provider_load",operationOutcome:"returned_error"},pre_ready_callback:{errorCode:"PROVIDER_RUNTIME_FAILED",stage:"provider_ready",operationOutcome:"returned_error"},render_rejected:{errorCode:"PROVIDER_RUNTIME_FAILED",stage:"provider_ready",operationOutcome:"rejected"},watchdog_expired:{errorCode:"PROVIDER_RUNTIME_FAILED",stage:"provider_ready",operationOutcome:"watchdog_expired"}};function td(e){return!e.generationActive||e.kind==="teardown"?{action:"ignore"}:e.kind==="ineligible"?{action:"unavailable"}:e.automaticRetryAllowed&&!e.automaticRetryUsed?{action:"retry"}:{action:"exhaust",report:ed[e.kind]??null}}function nd(e,t){return e==="watchdog_expired"?"paypal_render_timeout":Qc(t)?"paypal_init_timeout":"paypal_init_failure"}function rd(e,t=!1){return e?t?`${Pi} Open this page in your system browser, then try again.`:`${Pi} Allow pop-ups for this site, then try again.`:Pi}function od(e){let t=Ho(e),n=Ir(e);return t?{errorCode:"PROVIDER_RUNTIME_FAILED",popupBlocked:n,providerDeclined:t,terminalReason:"provider_declined"}:{errorCode:n?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",popupBlocked:n,providerDeclined:t,terminalReason:n?"popup_blocked":"provider_error"}}function ad(e){let t=e,n=t?.payer??t?.payment_source?.paypal;return{email:n?.email_address?.trim()||void 0,firstName:n?.name?.given_name?.trim()||void 0,lastName:n?.name?.surname?.trim()||void 0}}function id(e){return e>=500?"5xx":e>=400?"4xx":e>=300?"3xx":"unknown"}function ol({sessionId:e,nonce:t,billingApiUrl:n,email:r,billingName:o,onBuyerIdentityReady:i,clientId:s,environment:l,currency:p,isSubscription:f,providerObjectType:C,approvalPresentation:h,onTokenizedBody:m,onComplete:w,onErrorChange:_,onDecline:ae,onTechnicalFailure:Y,isProcessing:Pe=!1,onLoadStateChange:S,onInitializationStateChange:G,allowAutomaticRetry:X=!0,onButtonClick:ce,runBeforeButtonClick:Te,session:Fe,existingOrderId:ve,telemetry:Ue,telemetryContext:bt,onInstrument:ot,debug:$e=!1}){let De=Br(),ye=go(ot,e),we=Yo(()=>{if(De)return null;let M=wa({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:Wc,enabled:Ue!==!1});return M.setCheckoutContext(bt??{}),M.beginCheckout(bt??{}),M},[n,De,Ue,bt?.checkoutMode,bt?.layout]),Qe=Yo(()=>Qt(De),[De]);Lt(()=>()=>{we&&we.flush().catch(()=>{}).finally(()=>we.destroy())},[we]);let Z=Yo(()=>({error:M=>{Qe?Qe.error(M):we?.error(M),ye({class:"technical_error",errorCode:M.requestCategory==="intent_create"?"PAYMENT_PROCESSING_FAILED":M.errorCode,requestCategory:M.requestCategory,provider:M.provider})},log:M=>{Qe?Qe.log(M):we?.log(M),ye({class:"lifecycle",name:M.name,provider:M.provider})},performance:M=>{Qe?Qe.performance(M):we?.performance(M)},terminal:M=>{Qe?Qe.terminal(M):we?.terminal(M)},startTiming:()=>Qe?.now()??we?.now()??0,elapsed:M=>Qe?.elapsed(M)??Math.max(0,(we?.now()??M)-M)}),[ye,Qe,we]),Ie=lt(null),be=lt(0),ct=lt(null),dt=lt(null),U=lt(null),V=lt(!1),[de,fe]=Dr(!1),[ut,Ne]=Dr(!1),[x,at]=Dr(0),Ye=lt(0),[re,Q]=Dr(!1),L=lt(!1),Ae=lt(!1),[xe,Me]=Dr(!1),[qe,ke]=Dr(!1),{request:Ee,collect:ee,finish:dn}=mo(),Yt=lt({sessionId:e,required:!Go(r?.trim()||Fe?.customer?.email?.trim())});Yt.current.sessionId!==e&&(Yt.current={sessionId:e,required:!Go(r?.trim()||Fe?.customer?.email?.trim())});let H=Yt.current.required,Je=Yo(()=>n.replace(/\/+$/,""),[n]),K=Fe?.gateways?.paypal?.providerObjectType??C,ie=K??(f?"subscription":"order"),[u]=Dr(ba),B=Fe?.gateways?.paypal?.approvalPresentation??h,_e=Ca(u,B==="app_switch"?"app_switch":void 0,ie),Ke=K==="order"||K==="setup_token",Re=Yo(()=>JSON.stringify([Je,s,p,l??"",ie,Ke,_e,e,ve??""]),[Je,s,p,l,ve,ie,Ke,_e,e]),$t=lt(Re),N=$t.current!==Re,Ct=lt($e),Et=lt(null),[pt,un]=Dr([]),O=kr(M=>{Ct.current&&un(Oe=>[...Oe,`${new Date().toISOString().slice(11,23)} ${M}`])},[]);Lt(()=>{Ct.current=$e,$e&&O("debug:enabled"),Et.current?.setEnabled($e)},[O,$e]);let Ot=lt(m),Cn=lt(w),pn=lt(_),mn=lt(ae),_n=lt(Y),Fn=lt(ce),Dn=lt(S),Jt=lt(G),je=lt(i),He=lt(Te),St=lt(Fe),rn=lt(r),wt=lt(o),$n=lt(t),mt=lt(null),Tt=lt(new Map),zt=lt(new Map),yn=lt(!1);Lt(()=>(yn.current=!0,()=>{yn.current=!1}),[]),Lt(()=>{Ot.current=m},[m]),Lt(()=>{je.current=i},[i]),Lt(()=>{Cn.current=w},[w]),Lt(()=>{pn.current=_},[_]),Lt(()=>{mn.current=ae},[ae]),Lt(()=>{_n.current=Y},[Y]),Lt(()=>{Fn.current=ce},[ce]),Lt(()=>{Dn.current=S},[S]),Lt(()=>{Jt.current=G},[G]),Lt(()=>{He.current=Te},[Te]),Lt(()=>{St.current=Fe},[Fe]),Lt(()=>{rn.current=r},[r]),Lt(()=>{wt.current=o},[o]),Lt(()=>{$n.current=t},[t]),Lt(()=>{Ye.current=x},[x]),Lt(()=>{re&&U.current?.focus()},[re,x]);let Ut=kr(()=>{window.setTimeout(()=>{U.current?.focus()},0)},[]),At=kr(()=>{fe(!1),at(M=>M+1)},[]),Sn=kr(()=>{Q(!1),(Ie.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??Ie.current)?.focus?.()},[]);Lt(()=>{!de||!V.current||(V.current=!1,Sn())},[Sn,de,x]);let wn=kr((M,Oe)=>{let D=Oe?.popupBlocked??Ir(M),kt=rd(D,u.inAppBrowser),xt=_n.current;if(xt){let Gt=D&&u.inAppBrowser?new hi(kt,"api_error",{code:Oe?.code??"paypal_popup_blocked"}):M;xt("paypal",Gt,Oe);return}pn.current?.(kt)},[u.inAppBrowser]),It=kr(M=>{let Oe=ct.current,D=dt.current;Oe===null||!D||(Z.log({...D,name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:M}),Z.performance({...D,stage:"overlay_return",durationMs:Z.elapsed(Oe),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:M}),ct.current=null)},[Z]),te=kr((M,Oe,D)=>{let kt=dt.current;It("overlay_timeout"),kt&&Z.error({...kt,errorCode:"REQUEST_TIMEOUT",failureCategory:"provider_runtime",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",statusClass:"timeout",terminalReason:"overlay_timeout"}),wn(Oe,D),Q(!0),At(),Ut()},[It,Ut,wn,At,Z]),{finishAttempt:on,generationRef:Kn,invalidateAttempt:Ht,isAttemptCurrent:Kt,isAttemptInvalidated:an,startAttempt:nr}=Wo(te),Nn=kr(()=>(Q(!1),nr("paypal")),[nr]),Wt=kr(M=>{Ht(M?.generation),M?.showRetry&&Q(!0),M?.remount&&At(),M?.focus!==!1&&Ut()},[Ut,Ht,At]),Le=M=>{let Oe=mt.current;return Oe&&zt.current.set(M,Oe),M};Lt(()=>{$t.current!==Re&&($t.current=Re,L.current=!1,Ae.current=!1,fe(!1),Ne(!1),Me(!1),Jt.current?.("loading"))},[Re]),Lt(()=>{Bt(()=>Dn.current?.(de&&!xe))},[de,xe]);let fn=Hc(l);Lt(()=>{let M={attempt:Kn.current+1,...u,presentationMode:_e},Oe=()=>dt.current??M,D={error:R=>Z.error({...R,...Oe()}),log:R=>Z.log({...R,...Oe()}),performance:R=>Z.performance({...R,...Oe()}),terminal:R=>Z.terminal({...R,...Oe()}),startTiming:Z.startTiming,elapsed:Z.elapsed},kt=s?`${s.slice(0,6)}\u2026(len ${s.length})`:"(empty)",xt=typeof navigator>"u"?"(no navigator)":navigator.userAgent;if(O(`mount clientId=${kt} env=${l??"(unset)"}\u2192${fn??"live"} ccy=${p} sub=${f}`),O(`ua=${xt.slice(0,80)}${xt.length>80?"\u2026":""}`),!s){O("FAIL: clientId empty \u2014 gateway misconfigured"),Me(!0),D.error({errorCode:"CONFIGURATION_INVALID",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),console.error("[FloPay] DirectPayPal: clientId empty \u2014 gateway misconfigured");return}if(!Ie.current){O("FAIL: containerRef not attached");return}be.current=D.startTiming(),D.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let Gt=!1,Vn=!1,ge=()=>Gt||Vn,sn,Hn=!1,Pr=()=>{sn=Vc(),sn||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),Hn=!0},rr=null,zr=!1,Ur=null,or=!1,Er=()=>{!Ur||or||(or=!0,Ur.close().catch(()=>{}))},Rn=!1,ar=!1,Dt=Ie.current,Ln=null,Wn=null,Gn=[],yt=null,En=!1,Yn=!1,ir=null,gn=R=>{if(!R||typeof R.getBoundingClientRect!="function")return"(no rect)";let d=R.getBoundingClientRect();return`${Math.round(d.width)}\xD7${Math.round(d.height)}`},We=R=>{if(!R)return"(empty)";try{let d=new URL(R,typeof window>"u"?"https://localhost":window.location.href),A=d.pathname.toLowerCase();return A.includes("checkcaptcha")||A.includes("captcha")?`CAPTCHA(${d.host}${A})`:A.includes("risk")||A.includes("challenge")?`RISK(${d.host}${A})`:A.includes("smart/buttons")?`smart-buttons(${d.host})`:`${d.host}${A}`.slice(0,100)}catch{return R.slice(0,80)}},hn=R=>{let d=R.getAttribute("src"),A=R.getAttribute("srcdoc"),g=R.getAttribute("name"),P=R.getAttribute("sandbox"),I=[];return d&&I.push(`src=${We(d)}`),A&&I.push(`srcdoc[${A.length}ch]`),!d&&!A&&I.push("src=(empty) srcdoc=(empty)"),g&&I.push(`name=${g.slice(0,40)}`),P!==null&&I.push(`sandbox="${P.slice(0,40)}"`),I.join(" ")},ln=R=>{if(!(R instanceof HTMLIFrameElement))return"";try{let d=R.contentDocument;if(!d)return"cd=null";let A=d.body?.children.length??0,g=d.body?.innerHTML.length??0,P=d.head?.innerHTML.length??0;return`cd=same-origin readyState=${d.readyState} body[${A}children,${g}ch] head[${P}ch]`}catch(d){return`cd=cross-origin(${d.message.slice(0,30)})`}},On=[],br=R=>{if(ge())return;let d=R.message??String(R.error??"(no message)");d&&(d.toLowerCase().includes("paypal")||d.toLowerCase().includes("zoid")||d.toLowerCase().includes("postrobot")||d.toLowerCase().includes("storage"))&&(O(`window:error ${d.slice(0,140)}`),On.push(d))},qr=R=>{if(ge())return;let d=R.reason instanceof Error?R.reason.message:String(R.reason??"(no reason)");d&&(d.toLowerCase().includes("paypal")||d.toLowerCase().includes("zoid")||d.toLowerCase().includes("postrobot")||d.toLowerCase().includes("storage"))&&(O(`window:rejection ${d.slice(0,140)}`),On.push(d))},Cr={value:0},zn=()=>{Ln?.disconnect(),Ln=null,Wn?.disconnect(),Wn=null;for(let R of Gn.splice(0))clearTimeout(R);Yn=!1,En&&typeof window<"u"&&(window.removeEventListener("error",br),window.removeEventListener("unhandledrejection",qr)),En=!1},vn=()=>{if(!(En||ge()||Rn)){if(En=!0,On.length=0,Cr.value=0,typeof window<"u"&&(window.addEventListener("error",br),window.addEventListener("unhandledrejection",qr)),typeof PerformanceObserver<"u")try{Wn=new PerformanceObserver(R=>{if(!ge())for(let d of R.getEntries()){if(!d.name.toLowerCase().includes("paypal"))continue;Cr.value+=1;let A=Math.round(d.duration);O(`net ${A}ms ${d.name.slice(0,90)}`)}}),Wn.observe({type:"resource",buffered:!0})}catch{}ir?.()}},Xr=()=>{yt&&(clearTimeout(yt),yt=null)},Tn=()=>{zn(),Xr()},Tr={setEnabled:R=>{R?vn():zn()}};Et.current=Tr,Ct.current&&vn();let In=R=>{if(!R)return!1;let d=R.toLowerCase();return d.includes("zoid destroyed")||d.includes("destroyed all components")||d.includes("window closed")||d.includes("detected container element removed")},Un=R=>{if(ge()||In(R))return;let d=xr(R)??R;Bt(()=>pn.current?.(d))},et=(R,d)=>{if(Gt||zr)return;zr=!0,Vn=!0,Tn(),Er();let A=td({kind:R,generationActive:!0,automaticRetryAllowed:X,automaticRetryUsed:L.current});if(A.action==="retry"){L.current=!0,fe(!1),ke(!1),Ne(!0),Jt.current?.("retrying"),rr=setTimeout(()=>{Gt||at(g=>g+1)},Yc);return}if(fe(!1),ke(!1),Ne(!1),Me(!0),A.action!=="ignore"){if(Jt.current?.("exhausted"),A.action==="unavailable"){console.error("[FloPay] DirectPayPal load/render failure:",d);return}A.report&&D.error({errorCode:A.report.errorCode,stage:A.report.stage,operationOutcome:A.report.operationOutcome,provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime"}),Ae.current||(Ae.current=!0,console.error("[FloPay] Direct PayPal initialization failed:",nd(R,d)))}};Me(!1);let Jn=async(R,d=mt.current)=>{if(ge())return;let A=d?.sessionId??e;if(Ot.current){await Ot.current(R,{sessionId:A,accountPatch:d?.accountPatch,nonce:d?.nonce});return}let g=D.startTiming();D.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let P=()=>{D.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),D.performance({stage:"processing",durationMs:D.elapsed(g),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment"})};try{let I=St.current,v=d?.accountPatch?.email??rn.current,q=d?.accountPatch?.userId??I?.customer?.id??I?.accountData?.userId??"",Ve=d?.accountPatch?.firstName??I?.customer?.firstName??I?.accountData?.firstName,Nt=d?.accountPatch?.lastName??I?.customer?.lastName??I?.accountData?.lastName,ne=await new gi(Je,{telemetry:!1}).processPayment(q,{sessionId:A,nonce:d?.nonce??$n.current,paymentMethodCategory:"paypal",tokenizedData:R,accountData:{userId:q,email:v??I?.customer?.email??"",...Ve?{firstName:Ve}:{},...Nt?{lastName:Nt}:{},country:d?.accountPatch?.country??I?.customer?.country??I?.accountData?.country??void 0,zip:d?.accountPatch?.zip??I?.customer?.zip??I?.accountData?.zip??void 0}});if(ne.ok){if(Vn||Gt&&yn.current)return;P(),D.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),Bt(()=>Cn.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(ge())return;let y=await ne.json().catch(()=>null),k=y?.message??"PayPal payment failed.",J=xr(k)??k;P(),ne.status===400&&(typeof y?.declineCode=="string"||!Array.isArray(y?.fields))?D.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}):ne.status===400||ne.status===422?D.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx",terminalReason:"approved"}):D.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:id(ne.status),failureCategory:ne.status>=500?"server_error":void 0}),Un(J),Bt(()=>mn.current?.(nn("paypal",J,{code:y?.code,declineCode:y?.declineCode})));return}catch(I){if(ge())return;P(),D.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let v=I instanceof Error?I.message:"PayPal payment failed.",q=xr(v)??v;Un(q),Bt(()=>mn.current?.(nn("paypal",q)));return}},Xt=()=>new hi("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),_t=R=>ge()?Promise.reject(Xt()):Promise.resolve(R),T=async R=>{if(ge())throw Xt();Hn||Pr();let d=mt.current,A=d?.sessionId??e,g=d?.nonce??$n.current;D.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let P;try{P=await new gi(Je,{telemetry:!1}).createSessionIntent(A,g??"",Ke?{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:vi,paymentMethodId:null,intentKind:ie==="setup_token"?"setup":"payment"}:{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"},{idempotencyKey:sn})}catch(I){throw D.error({...Kc(I,"PAYMENT_PROCESSING_FAILED","unknown"),stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"}),I}if(ge())throw Xt();if(P.provider!=="paypal"||P.providerObjectType!==ie)throw new Error(R);return D.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),P.providerObjectId},E=(R,d)=>{let A=d?.nonce??$n.current;if(!A)return;let g=d?.sessionId??e,P=fo(R)??wr(R)??"provider_declined";new gi(Je,{telemetry:!1}).reportSessionIntentDecline(g,A,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:P}).catch(()=>{})},F=x;O("loadScript:scheduled (deferred 1 tick)");let z=null,it=setTimeout(()=>{if(Gt){O("loadScript:skipped (cancelled before defer ran)");return}O("loadScript:start");let R=fn==="live"?"production":fn,d={};ie==="subscription"?d={intent:"subscription",vault:!0}:ie==="order"&&(d={intent:"capture"}),z=Gc({clientId:s,currency:p,...d,...R?{environment:R}:{},...R==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}});let A=!1;z.then(g=>{if(A=!0,O(`loadScript:resolved inactive=${ge()} ns=${!!g} buttons=${!!g?.Buttons}`),ge())return;if(!g?.Buttons){O("FAIL: namespace missing Buttons factory"),et("namespace_unusable","PayPal SDK did not expose the Buttons factory.");return}D.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),D.performance({stage:"provider_ready",durationMs:D.elapsed(be.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),D.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let P=async(ne,y)=>{if(ge()||Ye.current!==F)return;let k=ne.vaultSetupToken??ne.subscriptionID??ne.orderID??"",J=k?zt.current.get(k):Tt.current.get(F);if(!(!J||!Kt(J.generation))&&on(J.generation)){zt.current.delete(k),Tt.current.delete(J.surfaceKey),It("approved");try{if(ke(!0),Bt(()=>pn.current?.(null)),!k)throw new hi("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});let ue=St.current,Se=Vr(wt.current??[ue?.customer?.firstName,ue?.customer?.lastName].filter(Boolean).join(" ")),pe=Bn({email:J.accountPatch?.email?.trim()||rn.current?.trim()||ue?.customer?.email?.trim(),firstName:J.accountPatch?.firstName?.trim()||Se.firstName,lastName:J.accountPatch?.lastName?.trim()||Se.lastName});if(!Go(pe.email)||!(pe.firstName||pe.lastName))try{let ht=ad(await y?.order?.get?.());pe=Bn({email:ht.email||pe.email,firstName:ht.firstName||pe.firstName,lastName:ht.lastName||pe.lastName})}catch{}if((je.current||H)&&!Go(pe.email)){let ht=await ee("PayPal",pe);if(!ht)return;pe=ht}Go(pe.email)&&(J.accountPatch=Bn({...J.accountPatch,...pe}),await je.current?.(pe));let Ge;ie==="setup_token"?Ge={id:k,type:"paypal_setup_token",isPaypal:!0,gateway:"paypal",paymentMethodType:vi}:Ke?Ge={id:k,isPaypal:!0,gateway:"paypal",paymentMethodType:vi}:Ge={id:k,isPaypal:!0},await Jn(Ge,J)}catch(ue){Un(ue instanceof Error?ue.message:"PayPal capture failed.")}finally{ge()||ke(!1)}}},I=ne=>{let y=ve?()=>_t(ve):()=>T(ne);return async()=>Le(await y())},v=g.Buttons({style:{layout:"horizontal",height:Ia,tagline:!1},..._e==="app_switch"?{appSwitchWhenAvailable:!0}:{},onClick:async(ne,y)=>{if(ge()){await y.reject();return}Pr();let k=He.current,J={};if(k)try{let pe=await k("paypal");if(ge()){await y.reject();return}if(!pe.proceed){mt.current=null,Tt.current.delete(F),await y.reject();return}J={sessionId:pe.sessionId,accountPatch:pe.accountPatch,nonce:pe.nonce}}catch(pe){O(`onClick:runBeforeButtonClick rejected msg=${(pe instanceof Error?pe.message:String(pe)).slice(0,120)}`),mt.current=null,Tt.current.delete(F),await y.reject();return}Bt(()=>Fn.current?.("paypal"));let ue=Nn(),Se={generation:ue,surfaceKey:F,...J};mt.current=Se,Tt.current.set(F,Se),dt.current={...M,attempt:ue},await y.resolve(),D.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),D.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),ct.current=D.startTiming()},createOrder:ie==="order"?I("Failed to create PayPal order."):void 0,createSubscription:ie==="subscription"?I("Failed to create PayPal subscription."):void 0,createVaultSetupToken:ie==="setup_token"?async()=>Le(await T("Failed to create PayPal setup token.")):void 0,onApprove:P,onCancel:()=>{if(ge())return;let ne=Tt.current.get(F)??mt.current;ne&&Tt.current.delete(ne.surfaceKey),mt.current=null,It("cancelled"),D.terminal({outcome:"payment_cancelled",terminalReason:"cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),V.current=!0,Wt({generation:ne?.generation,remount:!0,focus:!1})},onError:ne=>{if(ge()||Ye.current!==F)return;let y=ne instanceof Error?ne.message:"PayPal failed to render.";if(O(`onError rendered=${Rn} msg=${y.slice(0,120)}`),Rn){let k=Tt.current.get(F)??mt.current;if(k&&!Kt(k.generation)||!k&&an())return;if(In(y)){on(k?.generation);return}let{errorCode:J,popupBlocked:ue,providerDeclined:Se,terminalReason:pe}=od(ne);if(It(pe),Se){D.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:pe}),E(ne,k),Bt(()=>mn.current?.(nn("paypal",y))),k&&Tt.current.delete(k.surfaceKey),mt.current=null,on(k?.generation);return}D.error({errorCode:J,failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",terminalReason:pe}),k&&Tt.current.delete(k.surfaceKey),mt.current=null,Wt({generation:k?.generation,remount:!0,showRetry:!0,focus:!0}),wn(ne,{code:"paypal_runtime_failed",popupBlocked:ue});return}et(In(y)?"teardown":"pre_ready_callback",y)}}),q=v.isEligible();if(O(`isEligible=${q}`),D.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!q){fe(!1),et("ineligible","PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}ar=!0,Ur=v,ir=()=>{if(!En||Yn||ge()||Rn)return;Yn=!0,O(`container:dims ${gn(Dt)} visibility=${typeof document>"u"?"(no document)":document.visibilityState}`),typeof MutationObserver<"u"&&(Ln=new MutationObserver(y=>{if(!ge()){for(let k of y)if(k.type==="childList")k.addedNodes.forEach(J=>{if(!(J instanceof Element))return;let ue=J.tagName.toLowerCase(),Se=(J.getAttribute("title")??"").slice(0,40),pe=ue==="iframe"?` ${hn(J)}`:"";O(`child+ ${ue}${Se?` title="${Se}"`:""}${pe} dims=${gn(J)}`)});else if(k.type==="attributes"&&k.target instanceof Element){let J=k.target;if(J.tagName.toLowerCase()!=="iframe")continue;let ue=k.attributeName;(ue==="src"||ue==="srcdoc")&&O(`attr~ iframe ${ue}=${ue==="srcdoc"?`[${(J.getAttribute("srcdoc")??"").length}ch]`:We(J.getAttribute("src"))} dims=${gn(J)}`)}}}),Ln.observe(Dt,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let ne=y=>{if(ge()||Rn)return;let k=Dt.querySelectorAll("iframe"),J=typeof document<"u"&&"hasStorageAccess"in document;O(`watchdog:${y} container=${gn(Dt)} children=${Dt.childElementCount} iframes=${k.length} visibility=${typeof document>"u"?"(no document)":document.visibilityState} cookies=${typeof navigator>"u"?"?":navigator.cookieEnabled} hasStorageAccessApi=${J} paypalNetRequests=${Cr.value}`),k.forEach((ue,Se)=>{let pe=(ue.getAttribute("title")??"").slice(0,40);O(` iframe[${Se}] ${gn(ue)}${pe?` title="${pe}"`:""} ${hn(ue)}`);let Ge=ln(ue);Ge&&O(` ${Ge}`)}),On.length===0&&O(" (no PayPal/zoid window errors captured)")};Gn.push(setTimeout(()=>ne("3s"),3e3)),Gn.push(setTimeout(()=>ne("8s"),8e3)),Gn.push(setTimeout(()=>ne("15s"),15e3))},ir(),O("render:start");let Nt=D.startTiming();yt=setTimeout(()=>{ge()||Rn||(O("watchdog:11s retryable render timeout"),et("watchdog_expired","PayPal Buttons render did not settle within 11000ms."))},Jc);let Ce=v.render(Dt);(async()=>{try{if(await Ce,O(`render:resolved inactive=${ge()}`),Tn(),ge()){Er();return}Rn=!0,fe(!0),Ne(!1),Jt.current?.("ready"),D.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),D.performance({stage:"checkout_render",durationMs:D.elapsed(Nt),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}catch(ne){let y=ne instanceof Error?ne.message:"PayPal failed to render.";O(`render:rejected msg=${y.slice(0,120)}`),Tn(),et(In(y)?"teardown":"render_rejected",y)}})()}).catch(g=>{let P=g instanceof Error?g.message:"PayPal operation failed.";O(`provider:failed msg=${P.slice(0,120)}`);let I="script_rejected";A&&In(P)?I="teardown":A&&ar&&(I="render_rejected"),et(I,P)})},0);return()=>{Gt=!0,clearTimeout(it),rr&&clearTimeout(rr),Tn(),Et.current===Tr&&(Et.current=null),Er(),ct.current=null,dt.current=null}},[X,Je,s,p,l,ie,_e,Ke,e,ve,x,Z,ee,H,O,It]);let se=$e?bi("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:xe?"#fef2f2":"#f3f4f6",border:`1px solid ${xe?"#fca5a5":"#d1d5db"}`,borderRadius:6,color:"#111827",font:"11px/1.35 ui-monospace, SFMono-Regular, Menlo, monospace",whiteSpace:"pre-wrap",wordBreak:"break-word",maxHeight:220,overflowY:"auto"},children:[`FloPay/DirectPayPal-debug (ready=${de} failed=${xe})`,pt.length===0?`
|
|
2
2
|
(waiting for first lifecycle event\u2026)`:`
|
|
3
|
-
${
|
|
4
|
-
`)}`]}):null;return ot&&!K?je?Kr("div",{children:Pe}):null:hi("div",{children:[Pe,le&&Kr(po,{identity:le.identity,methodLabel:le.methodLabel,testId:"flopay-direct-paypal-identity-pane",onComplete:Vt,onCancel:()=>Vt(null)}),hi("div",{"aria-hidden":rt||le?!0:void 0,style:rt||le?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:Sa},children:[!Ee&&!rt&&Kr("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"}}),Kr("div",{ref:Ie,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,role:"group","aria-label":"PayPal payment method",style:{minHeight:Sa,display:"flex",opacity:Ee?1:0},"aria-busy":Ke||ge},Te)]},Te),se&&Kr("button",{ref:T,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:an,style:Gc,children:"Try PayPal again"})]})}function wa(e){return Kr(el,{...e})}function tl(e){return Kr(el,{...e})}import{jsx as nl,jsxs as rd}from"react/jsx-runtime";function fo({children:e,margin:t,icon:n=!0,styleOverride:r}){return rd("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&&nl("svg",{"aria-hidden":"true",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:nl("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 ad}from"@flopay/shared";function go(){return typeof window<"u"&&typeof window.sessionStorage<"u"}var Pi=":idempotency-key";function bi(e,t){if(!go())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 Ci(e,t){if(!go())return null;try{let n=window.sessionStorage.getItem(e+Pi);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 Ia(e,t){if(go())try{bi(e,t)&&window.sessionStorage.removeItem(e)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout session cache.",n)}}function ka(e,t){if(Ia(e,t),!!go())try{Ci(e,t)&&window.sessionStorage.removeItem(e+Pi)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout idempotency key.",n)}}function _a(e,t,n,r){if(go())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 Ra(e,t,n){if(go())try{window.sessionStorage.setItem(e+Pi,JSON.stringify({canonicalIdentity:t,idempotencyKey:n}))}catch(r){console.warn("[FloPayCheckout] Failed to persist checkout idempotency key.",r)}}function vi(e,t){return`${e}:${t.totalAmount??""}:${t.overrideAmount??""}:${t.quantity??1}:${t.currency??""}`}function id(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 ho(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=>vi(`${o.type??""}:${o.code??o.providerItemId??o.providerPlanId??""}`,o)).sort(),i:e?.items?.map(o=>vi(o.code??o.providerItemId??"",o)).sort(),s:e?.subscriptions?.map(o=>vi(o.code??o.providerPlanId??"",o)).sort(),couponCodes:e?.couponCodes?[...e.couponCodes].sort():void 0,checkoutMetadata:id(e?.checkoutMetadata),...t?{tagsData:e?.tagsData,utmMetadata:e?.utmMetadata,tokenizedData:e?.tokenizedData,checkoutMode:e?.checkoutMode??"full"}:{}};return JSON.stringify(r)}function rl(e,t=!1){let n=ho(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 ol(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=ad(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(v=>({type:v.type,code:v.code??v.providerItemId??v.providerPlanId??"",quantity:v.quantity??1,totalAmount:v.totalAmount,overrideAmount:v.overrideAmount??null,currency:(v.currency??o).toUpperCase()})).sort((v,g)=>`${v.code}:${v.type??""}`.localeCompare(`${g.code}:${g.type??""}`)),s=e.products.map(v=>({type:v.type,code:v.code??"",quantity:v.quantity??1,totalAmount:v.totalAmount,overrideAmount:v.overrideAmount??null,currency:(v.currency??e.currency).toUpperCase()})).sort((v,g)=>`${v.code}:${v.type??""}`.localeCompare(`${g.code}:${g.type??""}`));if(i.length!==s.length)return!1;for(let[v,g]of i.entries()){let h=s[v];if(h===void 0||g.code!==h.code||g.type!==void 0&&g.type!==h.type||g.quantity!==h.quantity||g.totalAmount!==h.totalAmount||g.overrideAmount!==h.overrideAmount||g.currency!==h.currency)return!1}let l=[...t.couponCodes??[]].sort(),p=[...e.coupons??[]].sort();return l.length===p.length&&l.every((v,g)=>v===p[g])}import{resolveBillingApiUrl as sd}from"@flopay/shared";import{useEffect as Er,useMemo as ld,useRef as al,useState as il}from"react";import{jsx as cd}from"react/jsx-runtime";function Ea({flopay:e,paypalFlopay:t,options:n,onInstrument:r,children:o}){let[i,s]=il(e instanceof Promise?null:e),[l,p]=il(t instanceof Promise||!t?null:t),v=al(null),g=al(null),h=yo(r);Er(()=>{h({class:"lifecycle",name:"checkout.mount"})},[h]),Er(()=>{i&&h({class:"lifecycle",name:"sdk.initialize.ready"})},[h,i]),Er(()=>{if(i)return Qt(i)?.subscribe?.(h)},[h,i]),Er(()=>{if(!(!l||l===i))return Qt(l)?.subscribe?.(h)},[h,i,l]),Er(()=>{if(!i)return;let M=Qt(i);return v.current=M?.beginCheckout()??M?.now()??0,M?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{M?.log({name:"checkout.unmount",stage:"unmount"})}},[i]),Er(()=>{let M=!1;return e instanceof Promise?e.then(U=>{M||s(U)},()=>{M||h({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"})}):s(e),()=>{M=!0}},[h,e]),Er(()=>{let M=!1;if(!t){p(null);return}return t instanceof Promise?t.then(U=>{M||p(U)},()=>{M||h({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED",provider:"paypal"})}):p(t),()=>{M=!0}},[h,t]),Er(()=>{if(!i||g.current===i)return;g.current=i;let M=Qt(i);M?.log({name:"checkout.rendered",stage:"checkout_render"}),h({class:"lifecycle",name:"checkout.rendered"}),M?.performance({stage:"checkout_render",durationMs:M.elapsed(v.current??0),durationMode:"machine"})},[h,i]);let y=sd(n?.billingApiUrl),_=ld(()=>({flopay:i,paypalFlopay:l,billingApiUrl:y,emitInstrument:h}),[i,l,y,h]);return cd(Gn.Provider,{value:_,children:o})}var Ta="flopay_recent_completion_";function vo(e){if(!(!e||typeof window>"u"))try{let t={expiresAt:Date.now()+6e4};window.sessionStorage.setItem(Ta+e,JSON.stringify(t))}catch{}}function Si(e){if(!e||typeof window>"u")return!1;try{let t=window.sessionStorage.getItem(Ta+e);if(!t)return!1;let n=JSON.parse(t);return typeof n?.expiresAt!="number"||n.expiresAt<=Date.now()?(window.sessionStorage.removeItem(Ta+e),!1):!0}catch{return!1}}import{loadFloPay as sl,PaymentAPI as dl}from"@flopay/js";import{classifyPaymentRejection as dd,FloPayError as bt,isAuthorizationOnlySession as ud,isSetupIntentClientSecret as pd,normalizeCheckoutFailureOutcome as ll}from"@flopay/shared";var Yo="card";async function md(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 yd(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 Ii(e,t){return Object.assign(e,{checkoutMethod:t})}function Sr(e,t){let n=e instanceof bt?e:new bt(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 Go(e,t){try{return await e()}catch(n){throw Sr(n,t)}}function ul(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 fd(e){return e.status==="succeeded"||e.status==="authorized"||e.status==="declined"}async function pl(e){if(typeof document>"u"||typeof window>"u")throw new bt("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});if(e.signal?.aborted)throw new bt("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"});let t=3e5,n=1e3,r=15e3,o=`${e.billingApiUrl.replace(/\/$/,"")}/v1/checkouts/sessions/${encodeURIComponent(e.sessionId)}/3ds/complete`,i=async()=>{let g=new AbortController,h=()=>g.abort();e.signal?.aborted?g.abort():e.signal?.addEventListener("abort",h);let y=window.setTimeout(()=>g.abort(),r);try{let _=await fetch(o,{method:"POST",headers:{"x-checkout-session-token":e.nonce,"content-type":"application/json"},body:"{}",signal:g.signal});if(!_.ok)return{status:"unknown"};let M=await _.json().catch(()=>null);return gd(M)}catch{return{status:"unknown"}}finally{window.clearTimeout(y),e.signal?.removeEventListener("abort",h)}},s=document.activeElement instanceof HTMLElement?document.activeElement:null,l=document.createElement("div");l.setAttribute("data-flopay-auto-3ds-overlay","1"),l.setAttribute("role","dialog"),l.setAttribute("aria-modal","true"),l.setAttribute("aria-label","Card authentication"),l.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 p=document.createElement("iframe");p.setAttribute("title","Card authentication"),p.setAttribute("allow","payment"),p.tabIndex=0,p.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(";"),p.src=e.nextActionRedirectUrl,l.appendChild(p),document.body.appendChild(l),p.focus();let v=null;try{v=new URL(e.billingApiUrl,window.location.href).origin}catch{v=null}try{let g=await new Promise((h,y)=>{let _=!1,M=0,U=0,qe=0,ge=!1,S=()=>{window.clearTimeout(M),window.clearInterval(U),window.clearTimeout(qe),window.removeEventListener("message",Le),p.removeEventListener("load",Y),e.signal?.removeEventListener("abort",de)},W=async()=>{if(!(_||ge)){ge=!0;try{let Se=await i();if(_||!fd(Se))return;_=!0,S(),h(Se)}finally{ge=!1}}},Y=()=>{window.clearTimeout(qe),qe=window.setTimeout(()=>{W()},250)},de=()=>{_||(_=!0,S(),y(new bt("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"})))},Le=Se=>{if(Se.source!==p.contentWindow||v&&Se.origin!==v)return;let Re=Se.data;!Re||typeof Re!="object"||Re.source!=="flopay-vault-3ds-return"||_||(_=!0,S(),h(null))};M=window.setTimeout(()=>{_||(_=!0,S(),y(new bt("Card authentication timed out.","api_error",{code:"three_ds_timeout"})))},t),U=window.setInterval(()=>{W()},n),p.addEventListener("load",Y),window.addEventListener("message",Le),e.signal?.addEventListener("abort",de),e.signal?.aborted&&de()});return g||await i()}finally{l.parentNode?.removeChild(l),s?.isConnected&&s.focus()}}function gd(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 Tr(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=Ir(o)??o;return Ii(new bt(i,"api_error",{code:ll(e?.outcome)??ll(e?.type)??e?.gatewayErrorCode}),r)}function wi(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function Aa(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}function ml(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let o of n)if(typeof o=="string"&&o.length>0&&(!t?.requirePaymentIntentClientSecret||Aa(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||Aa(l)))return l;let s=o.gateways;if(s&&typeof s=="object"){let l=s.stripe;if(l&&typeof l=="object"){let p=l,v=[p.stripeClientSecret,p.clientSecret];for(let g of v)if(typeof g=="string"&&g.length>0&&(!t?.requirePaymentIntentClientSecret||Aa(g)))return g}}}}async function hd({billingApiUrl:e,sessionId:t,nonce:n,responseJson:r}){let o=ml(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 dl(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(Aa(l))return{type:"3ds_required",threeDSecureToken:l}}catch{}return null}async function Po({billingApiUrl:e,sessionId:t,session:n,nonce:r,tokenizedData:o,returnUrl:i,telemetry:s}){let l=e.replace(/\/+$/,""),p=t??n.id,v=r??n.clientSecret,g=n.customer?.id??n.accountData?.userId??"",h=n.customer?.email??n.accountData?.email??"",y=n.customer?.firstName??n.accountData?.firstName??"",_=n.customer?.lastName??n.accountData?.lastName??"",M=n.customer?.country??n.accountData?.country??void 0,U=n.customer?.zip??n.accountData?.zip??void 0,ge=await new dl(l,s===!1?{telemetry:!1}:void 0).processPayment(g,{sessionId:p,nonce:v,paymentMethodCategory:"saved",tokenizedData:o,accountData:{userId:g,email:h,firstName:y,lastName:_,country:M,zip:U},returnUrl:i??wi(n)});if(ge.ok){let Y=typeof ge.json=="function"?await ge.json().catch(()=>null):null;return ud(n)||Y?.status==="authorized"?{type:"success",result:{status:"authorized",paymentId:typeof Y?.paymentId=="string"?Y.paymentId:n.paymentId,sessionId:typeof Y?.sessionId=="string"?Y.sessionId:p,authorizationExpiresAt:typeof Y?.authorizationExpiresAt=="string"?Y.authorizationExpiresAt:n.authorizationExpiresAt,paymentMethodId:jo(o),checkoutMethod:cl(o)}}:{type:"success",result:{status:"succeeded",paymentIntentId:o?.threeDSecureActionResultTokenId,paymentMethodId:jo(o),checkoutMethod:cl(o)}}}let S;try{S=await ge.json()}catch(Y){throw new bt("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:ge.status,cause:Y})}if(S?.type==="paypal_redirect_required"||S?.type==="3ds_required"){let Y=ml(S);if(!Y)throw new bt("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:ge.status});return{type:S.type,threeDSecureToken:Y,paymentMethodId:S.paymentMethodId}}if(S?.gatewayErrorCode==="authentication_required"){let Y=await hd({billingApiUrl:l,sessionId:p,nonce:v,responseJson:S});if(Y)return Y;throw Ii(new bt("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}let W=new bt(S?.message??"Payment failed. Please try again.","api_error",{code:S?.code??S?.gatewayErrorCode,declineCode:S?.declineCode??S?.gatewayDeclineReason,statusCode:ge.status});throw Object.assign(W,{telemetryOutcome:dd(ge.status,S)})}async function Ma(e,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:i,session:s,returnUrl:l,telemetry:p}){let v=t?.getRawProvider();if(!v)throw Sr(new bt("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!r||!e.threeDSecureToken)throw Ii(new bt("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let g=pd(e.threeDSecureToken),h=null,y=e.paymentMethodId,_=await Go(()=>md(v,e.threeDSecureToken,g),"card");if(_){if(_.error)throw Sr(new bt(_.error.message??`Failed to retrieve 3DS ${g?"setup":"payment"} status.`,"api_error",{code:_.error.code}),"card");let U=_.intent;!y&&U?.payment_method&&(typeof U.payment_method=="string"?y=U.payment_method:"id"in U.payment_method&&(y=U.payment_method.id??void 0))}let M=y?await Go(()=>yd(v,e.threeDSecureToken,{payment_method:y,return_url:l??wi(s)??window.location.href},g),"card"):null;if(M){if(M.error)throw Sr(new bt(M.error.message??"3DS authentication failed.","api_error",{code:M.error.code}),"card");h=M.intent}else{let U=await Go(()=>v.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(U.error)throw Sr(new bt(U.error.message??"3DS authentication failed.","api_error",{code:U.error.code}),"card");h=(g?U.setupIntent:U.paymentIntent)??null}if(h&&(h.status==="requires_capture"||h.status==="succeeded"||h.status==="processing")){let U=await Po({billingApiUrl:o,sessionId:i,session:s,telemetry:p,tokenizedData:{id:h.id,type:"card",threeDSecureActionResultTokenId:h.id},returnUrl:l});return U.type==="success"?{...U.result,paymentIntentId:U.result.paymentIntentId??h.id,paymentMethodId:U.result.paymentMethodId??y}:Ma(U,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:i,session:s,returnUrl:l,telemetry:p})}throw Sr(new bt("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let g=(n??t)?.getRawProvider();if(!g)throw Sr(new bt("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:y}=await Go(()=>g.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(y)throw Sr(new bt(y.message??"PayPal authorization failed.","api_error",{code:y.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:h}=await Go(()=>g.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:l??wi(s)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(h)throw Sr(new bt(h.message??"PayPal authorization failed.","api_error",{code:h.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new bt("Unsupported payment redirect state.","api_error")}function Jo(e){if(e instanceof bt){let r=Ir(e.message);return r&&r!==e.message?Object.assign(new bt(r,e.type,{code:e.code,declineCode:e.declineCode,param:e.param,statusCode:e.statusCode}),{checkoutMethod:e.checkoutMethod,telemetryFailureCategory:e.telemetryFailureCategory,telemetryOutcome:e.telemetryOutcome,telemetryRequestCategory:e.telemetryRequestCategory}):e}let t=e instanceof Error?e.message:"Payment failed. Please try again.",n=Ir(t)??t;return new bt(n,"api_error")}function ki(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 bt("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 cl(e){if(e)return e.isPaypal?"paypal":"card"}async function _i({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([sl(e,{billingApiUrl:n,locale:r,telemetry:o}),i?sl(i,{billingApiUrl:n,locale:r,telemetry:o}).catch(v=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",v),null)):Promise.resolve(null)]);if(!s)throw new bt("The payment provider did not initialize.","authentication_error");let p=null;return i?p=l:t&&(p=s),{flopay:s,paypalFlopay:p}}import{PaymentAPI as bo,PciVaultCardCapture as vd,toStripeAppearance as Pd}from"@flopay/js";import{COUNTRY_OPTIONS as bd,classifyPaymentRejection as Cd,FloPayError as ir,filterStripeMethodsByCountry as Sd,getPostalCodeExample as wd,getPostalCodeLabel as Ni,getStateFromPostalCode as fl,getStateLabel as Ri,getStateOptions as Id,getStripeMethodDisplayName as Hr,hasVendoredStripeMethodLogo as kd,isAuthorizationOnlySession as Ei,isAVSFieldVisible as et,isPostalCodeSupported as _d,isSetupIntentClientSecret as Ti,isValidEmail as ln,isValidPostalCode as Rd,needsStripeMethodExplicitConfirm as gl,normalizeCheckoutFailureOutcome as Ed,partitionStripeMethods as Td,randomUuidV4 as Ad,resolveAVSConfig as Md,resolveButtonsLayoutTheme as xd,resolveStripeMethodBrandVariant as Bd,resolveTheme as Fd,stripeExpressMethodToOptionKey as hl}from"@flopay/shared";import{ExpressCheckoutElement as Al,PaymentElement as Dd,Elements as Vr,useElements as Ui,useStripe as qi}from"@stripe/react-stripe-js";import Nd,{useCallback as Je,useContext as Co,useEffect as ft,useMemo as Et,useRef as ce,useState as oe}from"react";var yl={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 Wr,jsx as c,jsxs as Ue}from"react/jsx-runtime";var fr="flopay_stripe_resume",vl="flopay_wallet_resume",Ml="fw1",Ld="fw2",xl=300*1e3,Od=900,zd=25e3,Ud=25e3,qd=1e4,Ai={},Mi={};function ji(e){return`${Ld}:${e}`}function xa(e){if(typeof window>"u")return!1;try{return localStorage.removeItem(ji(e)),!0}catch{return!1}}function Ba(e,t){if(typeof window>"u")return null;let n=ji(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>xl||o.sessionId!==e||o.nonce!==t||typeof o.clientSecret!="string"||typeof o.providerObjectId!="string"||typeof o.paymentMethodType!="string"?(xa(e),null):o}catch{return xa(e),null}}function jd(e){if(typeof window>"u")return!1;try{return localStorage.setItem(ji(e.sessionId),JSON.stringify(e)),!0}catch{return!1}}function Pl(e,t,n){let r=Ba(e,t);return!r||r.clientSecret!==n?!1:xa(e)}function xi(e,t,n){if(typeof window>"u")return;Ba(e,t)?.clientSecret===n&&xa(e)}function $d(e){return typeof e.payment_method=="string"?e.payment_method:typeof e.payment_method?.id=="string"?e.payment_method.id:null}function Bi(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":qo(e.status),o=$d(e);return!r||!o?{kind:"ambiguous"}:{kind:"confirmed",intentId:e.id,paymentMethodId:o}}async function bl(e,t,n){let r=null;try{return await Promise.race([Ws(e,t),new Promise(o=>{r=window.setTimeout(()=>{r!==null&&n?.delete(r),o(null)},qd),n?.add(r)})])}finally{r!==null&&(window.clearTimeout(r),n?.delete(r))}}function Kd(e){return e==="provider_sdk"?"PROVIDER_RUNTIME_FAILED":"REQUEST_TIMEOUT"}function Bl(e){return e instanceof ir&&(e.type==="validation_error"||e.statusCode===400||e.statusCode===422)}async function Da(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 Bl(o)||t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"intent_create",provider:r}),o}}var Xo="flopay_paypal_resume",Vd=250,Cl="Just a moment \u2014 we are finalizing your order. Please press pay again.",Wd="We are still confirming your last payment with your bank. Please wait a moment before trying again.";function $i(e,t,n){e?.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:"provider_runtime",stage:"provider_load",provider:t,paymentMethodCategory:n,requestCategory:"provider_sdk"})}async function Na({billingApiUrl:e,sessionId:t,nonce:n,request:r}){if(!(!t||!n))try{await new bo(e,{telemetry:!1}).reportSessionIntentDecline(t,n,r)}catch{}}function Hd(e){return e instanceof ir&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function Fi(e){return e?.html?{html:e.html,...e.messageToken?{messageToken:e.messageToken}:{},...e.expectedOrigin?{expectedOrigin:e.expectedOrigin}:{}}:null}function Fl({event:e,fallbackEmail:t,fallbackName:n}){let r=e.billingDetails,o=t?.trim(),i=qr(n),s=i.firstName?i:qr(r?.name);return Dn({email:ln(o)?o:r?.email?.trim(),firstName:s.firstName,lastName:s.lastName})}async function Gd({event:e,prepared:t,email:n,billingName:r,methodLabel:o,collect:i}){let s=Fl({event:e,fallbackEmail:t?.accountPatch?.email??n,fallbackName:[t?.accountPatch?.firstName,t?.accountPatch?.lastName].join(" ").trim()||r});return ln(s.email)?s:i(o,s)}var Yd=`
|
|
3
|
+
${pt.join(`
|
|
4
|
+
`)}`]}):null;return xe&&!N?$e?Wr("div",{children:se}):null:bi("div",{children:[se,Ee&&Wr(yo,{identity:Ee.identity,methodLabel:Ee.methodLabel,testId:"flopay-direct-paypal-identity-pane",onComplete:dn,onCancel:()=>dn(null)}),bi("div",{"aria-hidden":ut||Ee?!0:void 0,style:ut||Ee?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:Ia},children:[!de&&!ut&&Wr("div",{"data-testid":"flopay-direct-paypal-placeholder",style:{position:"absolute",inset:0,borderRadius:8,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite",pointerEvents:"none"}}),Wr("div",{ref:Ie,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,role:"group","aria-label":"PayPal payment method",style:{minHeight:Ia,display:"flex",opacity:de?1:0},"aria-busy":qe||Pe},x)]},x),re&&Wr("button",{ref:U,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:Sn,style:Zc,children:"Try PayPal again"})]})}function ka(e){return Wr(ol,{...e})}function al(e){return Wr(ol,{...e})}import{jsx as il,jsxs as sd}from"react/jsx-runtime";function ho({children:e,margin:t,icon:n=!0,styleOverride:r}){return sd("div",{role:"alert","data-testid":"flopay-error",style:{margin:t,padding:"0.625rem 0.875rem",background:"#FEF2F2",border:"1px solid #FECACA",borderRadius:"8px",color:"#991B1B",fontSize:"0.85rem",fontWeight:600,...n?{display:"flex",alignItems:"center",gap:"0.5rem"}:{},...r??{}},children:[n&&il("svg",{"aria-hidden":"true",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:il("path",{d:"M12 9v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z",stroke:"#DC2626",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}),e]})}import{foldIntoProducts as ld,resolveSessionCurrency as cd}from"@flopay/shared";function vo(){return typeof window<"u"&&typeof window.sessionStorage<"u"}var Si=":idempotency-key";function wi(e,t){if(!vo())return null;let n=window.sessionStorage.getItem(e);if(!n)return null;try{let r=JSON.parse(n);return!r||typeof r.sid!="string"||!r.sid||"canonicalIdentity"in r&&r.canonicalIdentity!==t?null:{..."canonicalIdentity"in r?{canonicalIdentity:t}:{},sid:r.sid,nonce:typeof r.nonce=="string"?r.nonce:void 0}}catch{return{sid:n}}}function Ii(e,t){if(!vo())return null;try{let n=window.sessionStorage.getItem(e+Si);if(!n)return null;try{let r=JSON.parse(n);return typeof r=="string"?r?{idempotencyKey:r}:null:!r||typeof r.idempotencyKey!="string"||!r.idempotencyKey||"canonicalIdentity"in r&&r.canonicalIdentity!==t?null:{..."canonicalIdentity"in r?{canonicalIdentity:t}:{},idempotencyKey:r.idempotencyKey}}catch{return{idempotencyKey:n}}}catch{return null}}function _a(e,t){if(vo())try{wi(e,t)&&window.sessionStorage.removeItem(e)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout session cache.",n)}}function Ra(e,t){if(_a(e,t),!!vo())try{Ii(e,t)&&window.sessionStorage.removeItem(e+Si)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout idempotency key.",n)}}function Ea(e,t,n,r){if(vo())try{window.sessionStorage.setItem(e,JSON.stringify(r?{canonicalIdentity:t,sid:n,nonce:r}:{canonicalIdentity:t,sid:n}))}catch(o){console.warn("[FloPayCheckout] Failed to persist checkout session cache.",o)}}function Ta(e,t,n){if(vo())try{window.sessionStorage.setItem(e+Si,JSON.stringify({canonicalIdentity:t,idempotencyKey:n}))}catch(r){console.warn("[FloPayCheckout] Failed to persist checkout idempotency key.",r)}}function Ci(e,t){return`${e}:${t.totalAmount??""}:${t.overrideAmount??""}:${t.quantity??1}:${t.currency??""}`}function dd(e){if(e==null)return e;let t=JSON.stringify(Object.entries(e).sort(([s],[l])=>s<l?-1:s>l?1:0)),n=1779033703,r=3144134277,o=1013904242,i=2773480762;for(let s=0;s<t.length;s++){let l=t.charCodeAt(s);n=r^Math.imul(n^l,597399067),r=o^Math.imul(r^l,2869860233),o=i^Math.imul(o^l,951274213),i=n^Math.imul(i^l,2716044179)}return n=Math.imul(o^n>>>18,597399067),r=Math.imul(i^r>>>22,2869860233),o=Math.imul(n^o>>>17,951274213),i=Math.imul(r^i>>>19,2716044179),n^=r^o^i,r^=n,o^=n,i^=n,[n,r,o,i].map(s=>(s>>>0).toString(16).padStart(8,"0")).join("")}function Po(e,t=!1){let n=e?.account?.email?.trim().toLowerCase()??"",r={c:e?.clientId,cur:e?.currency??"",captureMethod:e?.captureMethod??"",a:{e:n,u:n?"":e?.account?.userId??"",country:e?.account?.country??""},successUrl:e?.successUrl,cancelUrl:e?.cancelUrl,p:e?.products?.map(o=>Ci(`${o.type??""}:${o.code??o.providerItemId??o.providerPlanId??""}`,o)).sort(),i:e?.items?.map(o=>Ci(o.code??o.providerItemId??"",o)).sort(),s:e?.subscriptions?.map(o=>Ci(o.code??o.providerPlanId??"",o)).sort(),couponCodes:e?.couponCodes?[...e.couponCodes].sort():void 0,checkoutMetadata:dd(e?.checkoutMetadata),...t?{tagsData:e?.tagsData,utmMetadata:e?.utmMetadata,tokenizedData:e?.tokenizedData,checkoutMode:e?.checkoutMode??"full"}:{}};return JSON.stringify(r)}function sl(e,t=!1){let n=Po(e,t),r=0;for(let o=0;o<n.length;o++)r=(r<<5)-r+n.charCodeAt(o)|0;return`flopay_session_${Math.abs(r).toString(36)}`}function ll(e,t){if(!e?.customer||!e.products||t.checkoutMetadata!==void 0)return!1;let n=t.account.email?.trim().toLowerCase()??"",r=e.customer.email?.trim().toLowerCase()??"";if((n?r!==n:e.customer.id!==t.account.userId)||(t.account.country??"").trim().toUpperCase()!==(e.customer.country??"").trim().toUpperCase()||e.successUrl!==t.successUrl||e.cancelUrl!==t.cancelUrl||(e.captureMethod??"automatic")!==(t.captureMethod??"automatic"))return!1;let o=cd(t.currency,t.items,t.subscriptions,t.products);if(!o||e.currency.toUpperCase()!==o.toUpperCase())return!1;let i=(t.products??ld(t.items,t.subscriptions)).map(f=>({type:f.type,code:f.code??f.providerItemId??f.providerPlanId??"",quantity:f.quantity??1,totalAmount:f.totalAmount,overrideAmount:f.overrideAmount??null,currency:(f.currency??o).toUpperCase()})).sort((f,C)=>`${f.code}:${f.type??""}`.localeCompare(`${C.code}:${C.type??""}`)),s=e.products.map(f=>({type:f.type,code:f.code??"",quantity:f.quantity??1,totalAmount:f.totalAmount,overrideAmount:f.overrideAmount??null,currency:(f.currency??e.currency).toUpperCase()})).sort((f,C)=>`${f.code}:${f.type??""}`.localeCompare(`${C.code}:${C.type??""}`));if(i.length!==s.length)return!1;for(let[f,C]of i.entries()){let h=s[f];if(h===void 0||C.code!==h.code||C.type!==void 0&&C.type!==h.type||C.quantity!==h.quantity||C.totalAmount!==h.totalAmount||C.overrideAmount!==h.overrideAmount||C.currency!==h.currency)return!1}let l=[...t.couponCodes??[]].sort(),p=[...e.coupons??[]].sort();return l.length===p.length&&l.every((f,C)=>f===p[C])}import{resolveBillingApiUrl as ud}from"@flopay/shared";import{useEffect as Nr,useMemo as pd,useRef as cl,useState as dl}from"react";import{jsx as md}from"react/jsx-runtime";function Aa({flopay:e,paypalFlopay:t,options:n,onInstrument:r,children:o}){let[i,s]=dl(e instanceof Promise?null:e),[l,p]=dl(t instanceof Promise||!t?null:t),f=cl(null),C=cl(null),h=go(r);Nr(()=>{h({class:"lifecycle",name:"checkout.mount"})},[h]),Nr(()=>{i&&h({class:"lifecycle",name:"sdk.initialize.ready"})},[h,i]),Nr(()=>{if(i)return Qt(i)?.subscribe?.(h)},[h,i]),Nr(()=>{if(!(!l||l===i))return Qt(l)?.subscribe?.(h)},[h,i,l]),Nr(()=>{if(!i)return;let _=Qt(i);return f.current=_?.beginCheckout()??_?.now()??0,_?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{_?.log({name:"checkout.unmount",stage:"unmount"})}},[i]),Nr(()=>{let _=!1;return e instanceof Promise?e.then(ae=>{_||s(ae)},()=>{_||h({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"})}):s(e),()=>{_=!0}},[h,e]),Nr(()=>{let _=!1;if(!t){p(null);return}return t instanceof Promise?t.then(ae=>{_||p(ae)},()=>{_||h({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED",provider:"paypal"})}):p(t),()=>{_=!0}},[h,t]),Nr(()=>{if(!i||C.current===i)return;C.current=i;let _=Qt(i);_?.log({name:"checkout.rendered",stage:"checkout_render"}),h({class:"lifecycle",name:"checkout.rendered"}),_?.performance({stage:"checkout_render",durationMs:_.elapsed(f.current??0),durationMode:"machine"})},[h,i]);let m=ud(n?.billingApiUrl),w=pd(()=>({flopay:i,paypalFlopay:l,billingApiUrl:m,emitInstrument:h}),[i,l,m,h]);return md(er.Provider,{value:w,children:o})}var xa="flopay_recent_completion_";function bo(e){if(!(!e||typeof window>"u"))try{let t={expiresAt:Date.now()+6e4};window.sessionStorage.setItem(xa+e,JSON.stringify(t))}catch{}}function ki(e){if(!e||typeof window>"u")return!1;try{let t=window.sessionStorage.getItem(xa+e);if(!t)return!1;let n=JSON.parse(t);return typeof n?.expiresAt!="number"||n.expiresAt<=Date.now()?(window.sessionStorage.removeItem(xa+e),!1):!0}catch{return!1}}async function Ma(e,t){e.current?.abort();let n=new AbortController;e.current=n;try{return await t(n.signal)}finally{e.current===n&&(e.current=null)}}import{loadFloPay as ul,PaymentAPI as Ri}from"@flopay/js";import{classifyPaymentRejection as yd,FloPayError as Pt,isAuthorizationOnlySession as fd,isSetupIntentClientSecret as gd,normalizeCheckoutFailureOutcome as pl}from"@flopay/shared";var Xo="card",hd=1e3,yl=3e5;async function vd(e,t,n){if(n){if(typeof e.retrieveSetupIntent!="function")return null;let{setupIntent:i,error:s}=await e.retrieveSetupIntent(t);return{error:s,intent:i??null}}if(typeof e.retrievePaymentIntent!="function")return null;let{paymentIntent:r,error:o}=await e.retrievePaymentIntent(t);return{error:o,intent:r??null}}async function Pd(e,t,n,r){if(r){if(typeof e.confirmCardSetup!="function")return null;let{setupIntent:s,error:l}=await e.confirmCardSetup(t,n);return{error:l,intent:s??null}}if(typeof e.confirmCardPayment!="function")return null;let{paymentIntent:o,error:i}=await e.confirmCardPayment(t,n);return{error:i,intent:o??null}}function Zo(e){return new Pt("Card authentication was cancelled.","api_error",{code:"three_ds_aborted",cause:e})}function Ei(e,t){return Object.assign(e,{checkoutMethod:t})}function _r(e,t){let n=e instanceof Pt?e:new Pt(e instanceof Error?e.message:"Payment provider failed.","api_error",{code:"provider_runtime_failure"});return Object.assign(n,{checkoutMethod:t,telemetryFailureCategory:"provider_runtime",telemetryRequestCategory:"provider_sdk"})}async function Jo(e,t){try{return await e()}catch(n){throw _r(n,t)}}function fl(e){return!e?.type||!e.threeDSecureToken||e.type!=="3ds_required"&&e.type!=="paypal_redirect_required"?null:{type:e.type,threeDSecureToken:e.threeDSecureToken,paymentMethodId:e.paymentMethodId}}function bd(e){return e.status==="succeeded"||e.status==="authorized"||e.status==="declined"}async function Ti(e){if(typeof document>"u"||typeof window>"u")throw new Pt("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});if(e.signal?.aborted)throw new Pt("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"});let t=1e3,n=15e3,r=`${e.billingApiUrl.replace(/\/$/,"")}/v1/checkouts/sessions/${encodeURIComponent(e.sessionId)}/3ds/complete`,o=async()=>{let h=new AbortController,m=()=>h.abort();e.signal?.aborted?h.abort():e.signal?.addEventListener("abort",m);let w=window.setTimeout(()=>h.abort(),n);try{let _=await fetch(r,{method:"POST",headers:{"x-checkout-session-token":e.nonce,"content-type":"application/json"},body:"{}",signal:h.signal});if(!_.ok)return{status:"unknown"};let ae=await _.json().catch(()=>null);return Cd(ae)}catch{return{status:"unknown"}}finally{window.clearTimeout(w),e.signal?.removeEventListener("abort",m)}},i,s=()=>e.pollCompletionEndpoint!==!1?o():(i??(i=o()),i),l=document.activeElement instanceof HTMLElement?document.activeElement:null,p=document.createElement("div");p.setAttribute("data-flopay-auto-3ds-overlay","1"),p.setAttribute("role","dialog"),p.setAttribute("aria-modal","true"),p.setAttribute("aria-label","Card authentication"),p.style.cssText=["position:fixed","inset:0","z-index:2147483647","background:rgba(15,23,42,0.6)","display:flex","align-items:center","justify-content:center","padding:16px"].join(";");let f=document.createElement("iframe");f.setAttribute("title","Card authentication"),f.setAttribute("allow","payment"),f.tabIndex=0,f.style.cssText=["width:min(100%,460px)","height:min(100%,640px)","border:0","border-radius:12px","background:#fff","box-shadow:0 12px 30px rgba(0,0,0,0.35)"].join(";");let C=null;try{C=new URL(e.billingApiUrl,window.location.href).origin}catch{C=null}try{let h=await new Promise((m,w)=>{let _=!1,ae=0,Y=0,Pe=0,S=!1,G=()=>{window.clearTimeout(ae),window.clearInterval(Y),window.clearTimeout(Pe),window.removeEventListener("message",Fe),f.removeEventListener("load",ce),e.signal?.removeEventListener("abort",Te)},X=async()=>{if(!(_||S)){S=!0;try{let ve=await s();if(_||!bd(ve))return;_=!0,G(),m(ve)}finally{S=!1}}},ce=()=>{e.pollCompletionEndpoint!==!1&&(window.clearTimeout(Pe),Pe=window.setTimeout(()=>{X()},250))},Te=()=>{_||(_=!0,G(),w(new Pt("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"})))},Fe=ve=>{if(ve.source!==f.contentWindow||C&&ve.origin!==C)return;let Ue=ve.data;!Ue||typeof Ue!="object"||Ue.source!=="flopay-vault-3ds-return"||_||(_=!0,G(),m(null))};ae=window.setTimeout(()=>{_||(_=!0,G(),w(new Pt("Card authentication timed out.","api_error",{code:"three_ds_timeout"})))},yl),e.pollCompletionEndpoint!==!1&&(Y=window.setInterval(()=>{X()},t)),f.addEventListener("load",ce),window.addEventListener("message",Fe),e.signal?.addEventListener("abort",Te),f.src=e.nextActionRedirectUrl,p.appendChild(f),document.body.appendChild(p),f.focus(),e.signal?.aborted&&Te()});return h||await s()}finally{p.parentNode?.removeChild(p),l?.isConnected&&l.focus()}}async function Co(e,t){let n=t.nonce??t.session.clientSecret,r=new Ri(t.billingApiUrl,{telemetry:!1}),o=new AbortController,i=new AbortController,s=()=>{o.abort(t.signal.reason),i.abort(t.signal.reason)};t.signal.aborted?s():t.signal.addEventListener("abort",s,{once:!0});let l=Ti({billingApiUrl:t.billingApiUrl,sessionId:t.sessionId,nonce:n,nextActionRedirectUrl:e.nextActionRedirectUrl,signal:o.signal,pollCompletionEndpoint:!1}),p=null,f=()=>(p??(p=r.waitForCheckoutSessionCompletion(t.sessionId,{initialDelayMs:hd,nonce:n,statusUrl:`${t.billingApiUrl.replace(/\/+$/,"")}/v1/checkouts/sessions/${encodeURIComponent(t.sessionId)}/status`,continueAfterActionRequired:!0,timeoutMs:yl,signal:i.signal})),p),C=f(),h;try{let w=await Promise.race([l.then(_=>({kind:"challenge",outcome:_})),C.then(_=>({kind:"status",session:_}))]);if(w.kind==="status")o.abort(),h=w.session;else{if(w.outcome.status==="declined")throw gr({type:w.outcome.declineReason??"authorization_declined",message:"Card was declined.",gatewayErrorCode:w.outcome.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:"card"});h=await f()}}catch(w){throw t.signal.aborted||w instanceof Error&&w.name==="AbortError"?Zo(w):w}finally{t.signal.removeEventListener("abort",s),o.abort(),i.abort()}let m=h.data.session;if(!Mr(m))throw po(m);return{...Sr(m,t.sessionId),checkoutMethod:"card"}}function Cd(e){if(!e||typeof e!="object")return{status:"unknown"};let t=typeof e.status=="string"?e.status:"unknown",n=typeof e.providerIntentId=="string"?e.providerIntentId:null;switch(t){case"succeeded":return{status:"succeeded",providerIntentId:n};case"authorized":return{status:"authorized",providerIntentId:n};case"declined":return{status:"declined",providerIntentId:n,declineReason:typeof e.declineReason=="string"?e.declineReason:null,gatewayDeclineReason:typeof e.gatewayDeclineReason=="string"?e.gatewayDeclineReason:null};case"requires_action":return{status:"requires_action",providerIntentId:n,nextActionRedirectUrl:typeof e.nextActionRedirectUrl=="string"?e.nextActionRedirectUrl:null};case"pending":return{status:"pending",providerIntentId:n};case"timeout":return{status:"timeout",providerIntentId:n};case"no_attempt":return{status:"no_attempt"};default:return{status:"unknown"}}}function gr(e,t="Payment failed. Please try again.",n){let r=n?.checkoutMethod??e?.checkoutMethod??(e?.type==="paypal_redirect_required"?"paypal":"card"),o=e?.message??t,i=xr(o)??o,s=Ei(new Pt(i,"api_error",{code:e?.code??pl(e?.outcome)??pl(e?.type)??e?.gatewayErrorCode}),r);return e?.orderId&&(s.orderId=e.orderId),s}function _i(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function Ba(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}function gl(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let o of n)if(typeof o=="string"&&o.length>0&&(!t?.requirePaymentIntentClientSecret||Ba(o)))return o;let r=e?.data;if(r&&typeof r=="object"){let o=r,i=[o.threeDSecureToken,o.clientSecret,o.stripeClientSecret,o.id];for(let l of i)if(typeof l=="string"&&l.length>0&&(!t?.requirePaymentIntentClientSecret||Ba(l)))return l;let s=o.gateways;if(s&&typeof s=="object"){let l=s.stripe;if(l&&typeof l=="object"){let p=l,f=[p.stripeClientSecret,p.clientSecret];for(let C of f)if(typeof C=="string"&&C.length>0&&(!t?.requirePaymentIntentClientSecret||Ba(C)))return C}}}}async function Sd({billingApiUrl:e,sessionId:t,nonce:n,responseJson:r}){let o=gl(r,{requirePaymentIntentClientSecret:!0});if(typeof o=="string"&&o.length>0)return{type:"3ds_required",threeDSecureToken:o};if(!t)return null;try{let l=(await new Ri(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(Ba(l))return{type:"3ds_required",threeDSecureToken:l}}catch{}return null}async function So({billingApiUrl:e,sessionId:t,session:n,nonce:r,tokenizedData:o,returnUrl:i,telemetry:s}){let l=e.replace(/\/+$/,""),p=t??n.id,f=r??n.clientSecret,C=n.customer?.id??n.accountData?.userId??"",h=n.customer?.email??n.accountData?.email??"",m=n.customer?.firstName??n.accountData?.firstName??"",w=n.customer?.lastName??n.accountData?.lastName??"",_=n.customer?.country??n.accountData?.country??void 0,ae=n.customer?.zip??n.accountData?.zip??void 0,Pe=await new Ri(l,s===!1?{telemetry:!1}:void 0).processPayment(C,{sessionId:p,nonce:f,paymentMethodCategory:"saved",tokenizedData:o,accountData:{userId:C,email:h,firstName:m,lastName:w,country:_,zip:ae},returnUrl:i??_i(n)});if(Pe.ok){let X=typeof Pe.json=="function"?await Pe.json().catch(()=>null):null;if(fd(n)||X?.status==="authorized")return{type:"success",result:{status:"authorized",paymentId:typeof X?.paymentId=="string"?X.paymentId:n.paymentId,sessionId:typeof X?.sessionId=="string"?X.sessionId:p,authorizationExpiresAt:typeof X?.authorizationExpiresAt=="string"?X.authorizationExpiresAt:n.authorizationExpiresAt,paymentMethodId:Ko(o),checkoutMethod:ml(o,n)}};let ce=o?.threeDSecureActionResultTokenId;return{type:"success",result:{status:"succeeded",...ce?{paymentIntentId:ce}:{},paymentMethodId:Ko(o),checkoutMethod:ml(o,n)}}}let S;try{S=await Pe.json()}catch(X){throw new Pt("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:Pe.status,cause:X})}if(S?.type==="3ds_required"&&typeof S.nextActionRedirectUrl=="string")return{type:"next_action_required",nextActionRedirectUrl:S.nextActionRedirectUrl};if(S?.type==="paypal_redirect_required"||S?.type==="3ds_required"){let X=gl(S);if(!X)throw new Pt("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:Pe.status});return{type:S.type,threeDSecureToken:X,paymentMethodId:S.paymentMethodId}}if(S?.gatewayErrorCode==="authentication_required"){let X=await Sd({billingApiUrl:l,sessionId:p,nonce:f,responseJson:S});if(X)return X;throw Ei(new Pt("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}let G=new Pt(S?.message??"Payment failed. Please try again.","api_error",{code:S?.code??S?.gatewayErrorCode,declineCode:S?.declineCode??S?.gatewayDeclineReason,statusCode:Pe.status});throw Object.assign(G,{telemetryOutcome:yd(Pe.status,S)})}async function Fa(e,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:i,session:s,returnUrl:l,telemetry:p,signal:f}){let C=t?.getRawProvider();if(!C)throw _r(new Pt("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!r||!e.threeDSecureToken)throw Ei(new Pt("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let h=gd(e.threeDSecureToken),m=null,w=e.paymentMethodId,_=await Jo(()=>vd(C,e.threeDSecureToken,h),"card");if(_){if(_.error)throw _r(new Pt(_.error.message??`Failed to retrieve 3DS ${h?"setup":"payment"} status.`,"api_error",{code:_.error.code}),"card");let Y=_.intent;!w&&Y?.payment_method&&(typeof Y.payment_method=="string"?w=Y.payment_method:"id"in Y.payment_method&&(w=Y.payment_method.id??void 0))}let ae=w?await Jo(()=>Pd(C,e.threeDSecureToken,{payment_method:w,return_url:l??_i(s)??window.location.href},h),"card"):null;if(ae){if(ae.error)throw _r(new Pt(ae.error.message??"3DS authentication failed.","api_error",{code:ae.error.code}),"card");m=ae.intent}else{let Y=await Jo(()=>C.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(Y.error)throw _r(new Pt(Y.error.message??"3DS authentication failed.","api_error",{code:Y.error.code}),"card");m=(h?Y.setupIntent:Y.paymentIntent)??null}if(m&&(m.status==="requires_capture"||m.status==="succeeded"||m.status==="processing")){let Y=await So({billingApiUrl:o,sessionId:i,session:s,telemetry:p,tokenizedData:{id:m.id,type:"card",threeDSecureActionResultTokenId:m.id},returnUrl:l});return Y.type==="success"?{...Y.result,paymentIntentId:Y.result.paymentIntentId??m.id,paymentMethodId:Y.result.paymentMethodId??w}:Y.type==="next_action_required"?Co(Y,{billingApiUrl:o,sessionId:i??s.id,session:s,signal:f}):Fa(Y,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:i,session:s,returnUrl:l,telemetry:p,signal:f})}throw _r(new Pt("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let h=(n??t)?.getRawProvider();if(!h)throw _r(new Pt("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:w}=await Jo(()=>h.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(w)throw _r(new Pt(w.message??"PayPal authorization failed.","api_error",{code:w.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:m}=await Jo(()=>h.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:l??_i(s)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(m)throw _r(new Pt(m.message??"PayPal authorization failed.","api_error",{code:m.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new Pt("Unsupported payment redirect state.","api_error")}function Qo(e){if(e instanceof Pt){let r=xr(e.message);return r&&r!==e.message?Object.assign(new Pt(r,e.type,{code:e.code,declineCode:e.declineCode,param:e.param,statusCode:e.statusCode}),{checkoutMethod:e.checkoutMethod,orderId:e.orderId,telemetryFailureCategory:e.telemetryFailureCategory,telemetryOutcome:e.telemetryOutcome,telemetryRequestCategory:e.telemetryRequestCategory}):e}let t=e instanceof Error?e.message:"Payment failed. Please try again.",n=xr(t)??t;return new Pt(n,"api_error")}function Ai(e){let t=e.data.stripe?.publishableKey,n=!!e.data.paypal?.publishableKey,r=!!e.data.session?.vault?.html||Ar(e.data.session);if(!t&&!n&&!r)throw new Pt("Session advertises no supported gateways or hosted vault (expected `gateways.stripe`, `gateways.paypal`, or vault markup).","validation_error");return t?{publishableKey:t,paypalPublishableKey:e.data.stripe?.paypalPublishableKey??t}:{}}function ml(e,t){return e?e.isPaypal?"paypal":"card":t&&Ar(t)?"card":void 0}async function xi({publishableKey:e,paypalPublishableKey:t,billingApiUrl:n,locale:r,telemetry:o}){if(!e)return{flopay:null,paypalFlopay:null};let i=t&&t!==e?t:void 0,[s,l]=await Promise.all([ul(e,{billingApiUrl:n,locale:r,telemetry:o}),i?ul(i,{billingApiUrl:n,locale:r,telemetry:o}).catch(f=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",f),null)):Promise.resolve(null)]);if(!s)throw new Pt("The payment provider did not initialize.","authentication_error");let p=null;return i?p=l:t&&(p=s),{flopay:s,paypalFlopay:p}}import{PaymentAPI as wo,PciVaultCardCapture as wd,toStripeAppearance as Id}from"@flopay/js";import{COUNTRY_OPTIONS as kd,classifyPaymentRejection as _d,FloPayError as dr,filterStripeMethodsByCountry as Rd,getPostalCodeExample as Ed,getPostalCodeLabel as qi,getStateFromPostalCode as vl,getStateLabel as Mi,getStateOptions as Td,getStripeMethodDisplayName as Jr,hasVendoredStripeMethodLogo as Ad,isAuthorizationOnlySession as Bi,isAVSFieldVisible as rt,isPostalCodeSupported as xd,isSetupIntentClientSecret as Fi,isValidEmail as cn,isValidPostalCode as Md,needsStripeMethodExplicitConfirm as Pl,normalizeCheckoutFailureOutcome as Bd,partitionStripeMethods as Fd,randomUuidV4 as Dd,resolveAVSConfig as Nd,resolveButtonsLayoutTheme as Ld,resolveStripeMethodBrandVariant as Od,resolveTheme as zd,stripeExpressMethodToOptionKey as bl}from"@flopay/shared";import{ExpressCheckoutElement as Bl,PaymentElement as Ud,Elements as Gr,useElements as Vi,useStripe as Hi}from"@stripe/react-stripe-js";import qd,{useCallback as Ze,useContext as Io,useEffect as gt,useMemo as Ft,useRef as me,useState as le}from"react";var hl={alipay:"https://cdn.flopay.com/sdk-logos/v1/alipay.svg",bancontact:"https://cdn.flopay.com/sdk-logos/v1/bancontact.svg",blik:"https://cdn.flopay.com/sdk-logos/v1/blik.svg",eps:"https://cdn.flopay.com/sdk-logos/v1/eps.svg",giropay:"https://cdn.flopay.com/sdk-logos/v1/giropay.svg",ideal:"https://cdn.flopay.com/sdk-logos/v1/ideal.svg",klarna:"https://cdn.flopay.com/sdk-logos/v1/klarna.svg",p24:"https://cdn.flopay.com/sdk-logos/v1/p24.svg",sepa_debit:"https://cdn.flopay.com/sdk-logos/v1/sepa_debit.svg",wechat_pay:"https://cdn.flopay.com/sdk-logos/v1/wechat_pay.svg"};import{Fragment as Yr,jsx as c,jsxs as ze}from"react/jsx-runtime";var hr="flopay_stripe_resume",Cl="flopay_wallet_resume",Fl="fw1",jd="fw2",Dl=300*1e3,$d=900,Kd=25e3,Vd=25e3,Hd=1e4,Di={},Ni={};function Wi(e){return`${jd}:${e}`}function Da(e){if(typeof window>"u")return!1;try{return localStorage.removeItem(Wi(e)),!0}catch{return!1}}function Na(e,t){if(typeof window>"u")return null;let n=Wi(e);try{let r=localStorage.getItem(n);if(!r)return null;let o=JSON.parse(r);return typeof o.createdAt!="number"||Date.now()-o.createdAt<0||Date.now()-o.createdAt>Dl||o.sessionId!==e||o.nonce!==t||typeof o.clientSecret!="string"||typeof o.providerObjectId!="string"||typeof o.paymentMethodType!="string"?(Da(e),null):o}catch{return Da(e),null}}function Wd(e){if(typeof window>"u")return!1;try{return localStorage.setItem(Wi(e.sessionId),JSON.stringify(e)),!0}catch{return!1}}function Sl(e,t,n){let r=Na(e,t);return!r||r.clientSecret!==n?!1:Da(e)}function Li(e,t,n){if(typeof window>"u")return;Na(e,t)?.clientSecret===n&&Da(e)}function Gd(e){return typeof e.payment_method=="string"?e.payment_method:typeof e.payment_method?.id=="string"?e.payment_method.id:null}function Oi(e,t,n){if(!e||typeof e.id!="string"||t&&e.id!==t)return{kind:"ambiguous"};if(e.status==="canceled"||e.status==="requires_payment_method")return{kind:"terminal"};let r=n?e.status==="succeeded":$o(e.status),o=Gd(e);return!r||!o?{kind:"ambiguous"}:{kind:"confirmed",intentId:e.id,paymentMethodId:o}}async function wl(e,t,n){let r=null;try{return await Promise.race([Js(e,t),new Promise(o=>{r=window.setTimeout(()=>{r!==null&&n?.delete(r),o(null)},Hd),n?.add(r)})])}finally{r!==null&&(window.clearTimeout(r),n?.delete(r))}}function Yd(e){return e==="provider_sdk"?"PROVIDER_RUNTIME_FAILED":"REQUEST_TIMEOUT"}function Nl(e){return e instanceof dr&&(e.type==="validation_error"||e.statusCode===400||e.statusCode===422)}async function Oa(e,t,...n){let r=n[2].provider;t?.({class:"lifecycle",name:"payment.intent.started",provider:r});try{return await new wo(e,{telemetry:!1}).createSessionIntent(...n)}catch(o){throw Nl(o)||t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"intent_create",provider:r}),o}}var ea="flopay_paypal_resume",Jd=250,Il="Just a moment \u2014 we are finalizing your order. Please press pay again.",Xd="We are still confirming your last payment with your bank. Please wait a moment before trying again.";function Gi(e,t,n){e?.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:"provider_runtime",stage:"provider_load",provider:t,paymentMethodCategory:n,requestCategory:"provider_sdk"})}async function za({billingApiUrl:e,sessionId:t,nonce:n,request:r}){if(!(!t||!n))try{await new wo(e,{telemetry:!1}).reportSessionIntentDecline(t,n,r)}catch{}}function Zd(e){return e instanceof dr&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function zi(e){return e?.html?{html:e.html,...e.messageToken?{messageToken:e.messageToken}:{},...e.expectedOrigin?{expectedOrigin:e.expectedOrigin}:{}}:null}function Ll({event:e,fallbackEmail:t,fallbackName:n}){let r=e.billingDetails,o=t?.trim(),i=Vr(n),s=i.firstName?i:Vr(r?.name);return Bn({email:cn(o)?o:r?.email?.trim(),firstName:s.firstName,lastName:s.lastName})}async function Qd({event:e,prepared:t,email:n,billingName:r,methodLabel:o,collect:i}){let s=Ll({event:e,fallbackEmail:t?.accountPatch?.email??n,fallbackName:[t?.accountPatch?.firstName,t?.accountPatch?.lastName].join(" ").trim()||r});return cn(s.email)?s:i(o,s)}var eu=`
|
|
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 @@ ${yn.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
|
-
`,Fa=44,Zo=180,Sl=`flopay-card-enter ${Zo}ms cubic-bezier(0, 0, 0.2, 1) both`,wl=`flopay-card-exit ${Zo}ms cubic-bezier(0.4, 0, 0.2, 1) both`,Jd=`flopay-buttons-enter ${Zo}ms cubic-bezier(0, 0, 0.2, 1) both`,Xd=`flopay-buttons-exit ${Zo}ms cubic-bezier(0.4, 0, 0.2, 1) both`;function Zd(e){return e.gateway==="stripe"?"stripe":e.gateway==="paypal"||e.isPaypal?"paypal":void 0}function Ki(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 Qd={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"};function eu(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 Li={width:"100%",minHeight:Fa,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 tu(e){switch(e){case"paypal":return"PayPal";case"apple_pay":return"Apple Pay";case"google_pay":return"Google Pay";default:return"Card"}}function Il(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function Oi(e){return e==="paypal"?"PayPal":Hr(e)}function nu(e,t){let n=`We couldn't open ${Oi(e)}. Try again or choose another payment method.`;return t?`${n} Allow pop-ups for this site, then try again.`:n}function ru(e){let t=wd(e);return`Enter a valid ${Ni(e)}${t?` (e.g. ${t})`:""}`}function ou(e,t,n){let r=_d(e),o=t.trim(),i=n&&r,s=i&&!o,l=i&&!!o&&!Rd(e,o);return{visible:n,supported:r,required:i,empty:s,malformed:l}}function au(e,t){let n=e.trim(),r=t&&!n,o=t&&!!n&&!ln(n);return{required:t,empty:r,malformed:o,value:n}}function kl(e,t){return t instanceof ir?t:new ir(t instanceof Error?t.message:`${tu(e)} before-click hook failed.`,"validation_error")}function Di(){return c("style",{children:Yd})}function iu(e){return typeof e=="number"?`${e}px`:e}function Dl(e,t){let n=e.availablePaymentMethods;return n&&t.some(r=>n[r])?"ready":"unavailable"}function Nl({state:e,placeholderTestId:t,borderRadius:n=8,children:r}){return e==="unavailable"||e==="load_error"?null:Ue("div",{style:{position:"relative",minHeight:44},children:[c("div",{"data-testid":t,"aria-hidden":e==="ready",style:{position:"absolute",inset:0,height:44,borderRadius:n,background:"#e5e7eb",animation:e==="ready"?void 0:"flopay-pulse 1.5s ease-in-out infinite",opacity:e==="ready"?0:1,transform:e==="ready"?"scale(0.985)":"scale(1)",transition:"opacity 140ms ease-out, transform 140ms ease-out",pointerEvents:"none"}}),c("div",{style:{minHeight:44,opacity:e==="ready"?1:0,transform:e==="ready"?"translateY(0)":"translateY(2px)",transition:"opacity 140ms ease-out, transform 140ms ease-out",pointerEvents:e==="ready"?"auto":"none"},children:r})]})}function _l(e){return e!=="unavailable"&&e!=="load_error"}function Vi(e){return c(lu,{...e})}function Rl({sessionId:e,nonce:t,email:n,billingApiUrl:r,onTokenizedBody:o,onErrorChange:i,isProcessing:s=!1,onButtonClick:l,onDecline:p,onTechnicalFailure:v,runBeforeButtonClick:g,billingName:h,onBuyerIdentityReady:y,onLoadStateChange:_,placeholderBorderRadius:M}){let U=kr(),{emitInstrument:qe}=Co(Gn),ge=qi(),S=Ui(),[W,Y]=oe("loading");ft(()=>{_?.(W)},[W,_]);let[de,Le]=oe(!1),Se=!ln(n?.trim())||!h?.trim(),{request:Re,collect:Ge,finish:St}=uo(),tt=ce(!1),je=ce(null),$e=ce(null),[ue,we]=oe(0),[Xe,ee]=oe(!1),Ie=ce(!1),he=ce(new Map),{startAttempt:st,finishAttempt:lt,invalidateAttempt:T,isAttemptInvalidated:$,isAttemptCurrent:Ee}=Vo((se,x,Q)=>{v?.(se,x,{...Q,popupBlocked:Q?.popupBlocked??br(x)}),ee(!0),we(Me=>Me+1)});ft(()=>{Xe&&$e.current?.focus()},[Xe,ue]);let ie=Je(()=>{we(se=>se+1)},[]),rt=Je((se,x,Q)=>{T(Q),v?.("paypal",se,{code:x,popupBlocked:br(se)}),ee(!0),ie()},[T,v,ie]),A=Je(()=>{window.setTimeout(()=>{(je.current?.querySelector("iframe")??je.current)?.focus()},0)},[]);ft(()=>{Ie.current&&(Ie.current=!1,A())},[A,ue]);let Te=Je(()=>{ee(!1),i?.(null),A()},[A,i]);ft(()=>{if(!ge||tt.current)return;let se=new URLSearchParams(window.location.search),x=se.get("payment_intent"),Q=se.get("payment_intent_client_secret"),Me=se.get("redirect_status");if(!x||!Q)return;tt.current=!0;let ot;try{let Ke=localStorage.getItem(Xo);if(Ke){let _e=JSON.parse(Ke);_e.clientSecret===Q&&(ot={..._e.accountPatch?{accountPatch:_e.accountPatch}:{},..._e.sessionId?{sessionId:_e.sessionId}:{},..._e.nonce?{nonce:_e.nonce}:{}})}}catch{}try{localStorage.removeItem(Xo)}catch{}let ke=new URL(window.location.href);ke.searchParams.delete("payment_intent"),ke.searchParams.delete("payment_intent_client_secret"),ke.searchParams.delete("redirect_status"),window.history.replaceState({},"",ke.toString()),(async()=>{try{if(Le(!0),Me==="failed"){let le="PayPal payment was declined. Please try again.";i?.(le),p?.(nn("paypal",le));return}let{paymentIntent:Ke,error:_e}=await ge.retrievePaymentIntent(Q);if(_e){i?.(_e.message??"Failed to retrieve PayPal payment status.");return}if(Ke&&(Ke.status==="requires_capture"||Ke.status==="succeeded")){let le=typeof Ke.payment_method=="string"?Ke.payment_method:Ke.payment_method?.id;o({id:le??Ke.id,type:"card",threeDSecureActionResultTokenId:Ke.id,isPaypal:!0},ot)}else{let le="PayPal payment was not completed. Please try again.";i?.(le),p?.(nn("paypal",le))}}catch(Ke){i?.(Ke instanceof Error?Ke.message:"Failed to complete PayPal payment.")}finally{Le(!1)}})()},[ge,o,i,p]);let dt=Je(async se=>{if(s||de){se.reject();return}let x=g?await g("paypal"):{proceed:!0};if(!x.proceed){he.current.delete(ue),se.reject();return}let Q=st("paypal");he.current.set(ue,{generation:Q,accountPatch:x.accountPatch,sessionId:x.sessionId,nonce:x.nonce}),ee(!1),l?.("paypal"),se.resolve()},[s,l,g,st,de,ue]),We=Je(async se=>{if(!ge||!S)return;let x=he.current.get(ue);if(x&&!Ee(x.generation)){he.current.delete(ue);return}if(!x&&$()||x&&!lt(x.generation))return;x||lt();let Q=x??null;if(he.current.delete(ue),!Q&&g){let le=await g("paypal");if(!le.proceed){se.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}Q={accountPatch:le.accountPatch,sessionId:le.sessionId,nonce:le.nonce}}let Me=Q?.sessionId??e,ot=Q?.nonce??t,ke=await Gd({event:se,prepared:Q,email:n,billingName:h,methodLabel:"PayPal",collect:Ge});if(!ke){se.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let Ke=ke.email,_e={...Q?.accountPatch,...Dn(ke,!0)};try{if(Le(!0),i?.(null),!Me||!ln(Ke))throw new Error("Missing sessionId or email for PayPal payment");await y?.(ke);let le=ge.createPaymentMethod,{error:ve,paymentMethod:Vt}=await le({type:"paypal"});if(ve){rt(ve,"stripe_paypal_create_payment_method_failed",x?.generation),se.paymentFailed({reason:"fail"});return}let H=await Da(r,qe,Me,ot??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:Vt?.id??null,intentKind:"payment"});if(H.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let Mt=H.clientSecret,mt={return_url:window.location.href};if(Vt?.id&&(mt.payment_method=Vt.id),typeof window<"u")try{localStorage.setItem(Xo,JSON.stringify({clientSecret:Mt,sessionId:Me,nonce:ot,accountPatch:_e}))}catch{}let{error:R,paymentIntent:ne}=await ge.confirmPayment({clientSecret:Mt,confirmParams:mt,redirect:"if_required"});if(R){if(typeof window<"u")try{localStorage.removeItem(Xo)}catch{}if(Ko(R)){let w=R.message??"Your payment was declined.";i?.(w),p?.(nn("paypal",w,{code:Pr(R),declineCode:mo(R)})),await Na({billingApiUrl:r,sessionId:Me,nonce:ot,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:Pr(R)??"provider_declined"}})}else rt(R,"stripe_paypal_confirm_failed",x?.generation);return}if(typeof window<"u")try{localStorage.removeItem(Xo)}catch{}let u=typeof ne?.payment_method=="string"?ne.payment_method:ne?.payment_method?.id;o({id:u??ne?.id,type:"card",threeDSecureActionResultTokenId:ne?.id,isPaypal:!0},{accountPatch:_e,paymentMethodCategory:"paypal",sessionId:Me,nonce:ot});return}catch(le){rt(le,"stripe_paypal_failed",x?.generation)}finally{Le(!1)}},[ge,S,e,t,n,h,Ge,y,r,qe,o,i,p,g,rt,lt,Ee,$,ue]);return Ue(Wr,{children:[c(Nl,{state:W,placeholderTestId:"flopay-paypal-placeholder",borderRadius:M,children:Ue("div",{ref:je,tabIndex:-1,"data-testid":"flopay-paypal-focus-target",role:"group","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[Xe&&c("button",{ref:$e,type:"button","data-testid":"flopay-paypal-retry-button",onClick:Te,style:Li,children:"Try PayPal again"}),Re&&c(po,{identity:Re.identity,methodLabel:Re.methodLabel,onComplete:St,onCancel:()=>St(null)},Re.id),c("div",{style:{display:Re?"none":void 0},children:c(Al,{onReady:se=>Y(Dl(se,["paypal"])),onLoadError:()=>{Y("load_error"),$i(Qt(U),"paypal","paypal")},onClick:dt,onConfirm:We,onCancel:()=>{let se=he.current.get(ue);he.current.delete(ue),Qt(U)?.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),T(se?.generation),ee(!1),Ie.current=!0,ie()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:Se,emailRequired:Se,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},ue)})]})}),de&&c(yr,{status:"processing"})]})}function El({sessionId:e,nonce:t,email:n,billingApiUrl:r,intentKind:o,expressMethods:i,onTokenizedBody:s,onErrorChange:l,onButtonClick:p,onDecline:v,onTechnicalFailure:g,runBeforeButtonClick:h,billingName:y,onBuyerIdentityReady:_,onLoadStateChange:M,placeholderBorderRadius:U}){let qe=kr(),{emitInstrument:ge}=Co(Gn),S=qi(),W=Ui(),[Y,de]=oe("loading");ft(()=>{M?.(Y)},[Y,M]);let[Le,Se]=oe(!1),Re=ce(!ln(n?.trim())||!y?.trim()).current,{request:Ge,collect:St,finish:tt}=uo(),je=ce(null),$e=ce(null),[ue,we]=oe(0),[Xe,ee]=oe(!1),[Ie,he]=oe(()=>Ba(e,t)?"blocked":"idle"),[st,lt]=oe("google_pay"),T=ce(null),$=ce(!0),Ee=ce(!1),ie=ce("google_pay"),rt=ce("google_pay"),A=ce(null),Te=ce(null),dt=ce(new Set);ft(()=>($.current=!0,()=>{$.current=!1;for(let R of dt.current)window.clearTimeout(R);dt.current.clear()}),[]);let We=ce(new Map),{startAttempt:se,finishAttempt:x,invalidateAttempt:Q,isAttemptInvalidated:Me,isAttemptCurrent:ot,generationRef:ke}=Vo((R,ne,u)=>{g?.(R,ne,{...u,popupBlocked:u?.popupBlocked??br(ne)}),lt(R),ee(!0),we(w=>w+1)});ft(()=>{Xe&&$e.current?.focus()},[Xe,ue]);let Ke=Je(()=>{we(R=>R+1)},[]),_e=Je((R,ne,u,w)=>{Q(w),g?.(R,ne,{code:u,popupBlocked:br(ne)}),lt(R),ee(!0),Ke()},[Q,g,Ke]),le=Je(()=>{window.setTimeout(()=>{(je.current?.querySelector("iframe")??je.current)?.focus()},0)},[]);ft(()=>{Ee.current&&(Ee.current=!1,le())},[le,ue]);let ve=Je(()=>{ee(!1),l?.(null),le()},[le,l]),Vt=Je(()=>{T.current?.()},[]);ft(()=>{let R=Ba(e,t);if(!R)return;let ne=!1,u=!1,w=async()=>{if(!u){u=!0,ne||he("checking");try{let xe=await bl(S,R.clientSecret,dt.current);if(ne)return;let me=Bi(xe,R.providerObjectId,Ti(R.clientSecret));if(me.kind==="confirmed"){if(!Pl(e,t,R.clientSecret))return;T.current=null,he("idle"),s({id:me.paymentMethodId,type:"card",threeDSecureActionResultTokenId:me.intentId},{...R.accountPatch?{accountPatch:R.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t});return}if(me.kind==="terminal"){xi(e,t,R.clientSecret),T.current=null,he("idle"),lt(R.paymentMethodType),ee(!0),Ke();return}he("blocked")}catch{ne||he("blocked")}finally{u=!1}}};return T.current=w,he("blocked"),()=>{ne=!0,T.current===w&&(T.current=null)}},[t,s,Ke,e,S]);let H=Je(async R=>{let ne=!1,u=Ae=>{ne||(ne=!0,R.paymentFailed({reason:"fail",...Ae?{message:Ae}:{}}))};if(!S||!W){u();return}let w=We.current.get(ue);if(w&&!ot(w.generation)){We.current.delete(ue),u();return}if(!w&&Me()){u();return}if(w&&!x(w.generation)){u();return}w||x();let xe=R.expressPaymentType??w?.method??ie.current,me=w??null,Ct=Il(xe),nt;xe==="apple_pay"?nt="apple_pay":xe==="google_pay"&&(nt="google_pay");let xt=w?.generation??ke.current,K=Qt(qe),Wt=K?.now()??globalThis.performance?.now()??Date.now(),wt=new AbortController,yn=!1,sr=!1,N=null,fn=e,In="processing",cn="other",rn="provider_runtime",gn,Jn=new Promise((Ae,Oe)=>{gn=Oe}),dn=window.setTimeout(()=>{yn=!0,wt.abort(),gn(Ai)},zd),Ht=async(Ae,Oe,on)=>{In=Ae,cn=Oe,rn=Oe==="intent_create"||Oe==="session_claim"?"transport_error":"provider_runtime";let ut=K?.now()??globalThis.performance?.now()??Date.now();try{return await Promise.race([on,Jn])}finally{let jn=K?.now()??globalThis.performance?.now()??Date.now();K?.performance({stage:Ae,durationMs:Math.max(0,jn-ut),durationMode:"machine",requestCategory:Oe,paymentMethodCategory:"wallet",provider:"stripe",...yn?{statusClass:"timeout"}:{}})}};try{if(Se(!0),l?.(null),!me&&h){let Pe=await Ht("processing","other",h(Ct));if(!Pe.proceed){u();return}me={accountPatch:Pe.accountPatch,sessionId:Pe.sessionId,nonce:Pe.nonce}}let Ae=me?.sessionId??e;fn=Ae;let Oe=me?.nonce??t,on=A.current??me?.accountPatch,ut=Fl({event:R,fallbackEmail:on?.email??n,fallbackName:[on?.firstName,on?.lastName].join(" ").trim()||y});if(!ln(ut.email)){u("Buyer details are required."),St(Oi(xe),ut).then(Pe=>{Pe&&(A.current=Pe)});return}A.current=null;let jn={...me?.accountPatch,...Dn(ut,!0)};await Ht("processing","session_claim",Promise.resolve(_?.(ut)));let{error:Bt}=await Ht("tokenization","provider_sdk",W.submit());if(Bt){u(),_e(xe,Bt,"stripe_wallet_submit_failed",w?.generation);return}if(!Ae)throw new Error("Missing sessionId or email for payment.");let Gt={provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:xe,paymentMethodId:null,intentKind:o},gt=JSON.stringify({sessionId:Ae,nonce:Oe??"",request:Gt}),$t=Te.current,un=$t?.retryIdentity===gt?$t.authorizationAttemptId:Ad();Te.current={authorizationAttemptId:un,retryIdentity:gt};let Ft=await Ht("processing","intent_create",Da(r,ge,Ae,Oe??"",{...Gt,authorizationAttemptId:un},{signal:wt.signal}));if(Ft.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let It=Ft.clientSecret,an=jd({createdAt:Date.now(),sessionId:Ae,...Oe?{nonce:Oe}:{},clientSecret:It,providerObjectId:Ft.providerObjectId,paymentMethodType:xe,accountPatch:jn});window.clearTimeout(dn),sr=!0,K?.performance({stage:"callback",durationMs:Math.max(0,(K?.now()??globalThis.performance?.now()??Date.now())-Wt),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe"});let Nn=K?.now()??globalThis.performance?.now()??Date.now(),vt={stage:"provider_confirmation",provider:"stripe",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",...nt?{walletType:nt}:{},attempt:xt},J=!1,hn=null;K?.log({name:"payment.provider_confirmation.started",...vt}),N=window.setTimeout(()=>{N!==null&&dt.current.delete(N),J=!0;let Pe=K?.now()??globalThis.performance?.now()??Date.now();K?.error({errorCode:"PROVIDER_RUNTIME_FAILED",...vt,operationOutcome:"watchdog_expired",durationMs:Math.max(0,Pe-Nn),statusClass:"timeout",failureCategory:"provider_runtime"}),K?.flush?.().catch(()=>{}),hn?.()},Ud),dt.current.add(N);let vn=Pe=>{N!==null&&(window.clearTimeout(N),dt.current.delete(N),N=null);let E=K?.now()??globalThis.performance?.now()??Date.now(),be=Math.max(0,E-Nn),I=Pe;return J&&(Pe==="resolved"?I="resolved_late":Pe==="returned_error"?I="returned_error_late":I="rejected_late"),K?.log({name:"payment.provider_confirmation.returned",...vt,operationOutcome:I}),K?.performance({...vt,durationMs:be,durationMode:"buyer",operationOutcome:I}),{durationMs:be,operationOutcome:I}},Dt=!1,zt=!1,Ln=Pe=>{if(!Pe||typeof Pe!="object")return null;let E=Pe;if(E.error)return null;let be=E.setupIntent??E.paymentIntent,I=Bi(be??null,void 0,!!E.setupIntent);return I.kind==="confirmed"?I:null},$n=Pe=>{if(Dt||w&&ke.current!==w.generation)return;let E=Ln(Pe);if(!E)return;if(an&&!Pl(Ae,Oe,It)){Dt=!0;return}let{intentId:be,paymentMethodId:I}=E;Dt=!0,zt=!0,Te.current=null,T.current=null,$.current&&(he("idle"),Se(!1));let Nt=`${Ml}:${Ae}`;if(typeof window<"u")try{localStorage.setItem(Nt,JSON.stringify({createdAt:Date.now(),sessionId:Ae,nonce:Oe,accountPatch:jn,paymentMethodId:I,providerIntentId:be,paymentMethodType:xe}))}catch{}try{s({id:I,type:"card",threeDSecureActionResultTokenId:be},{accountPatch:jn,paymentMethodCategory:"wallet",sessionId:Ae,nonce:Oe})}finally{if(typeof window<"u")try{localStorage.removeItem(Nt)}catch{}}},Xn=!1;hn=async()=>{if(!(Xn||Dt||zt)){Xn=!0,$.current&&he("checking");try{let Pe=await bl(S,It,dt.current);if(Dt||zt)return;let E=Ti(It),be=Bi(Pe,Ft.providerObjectId,E);if(be.kind==="confirmed"){$n(E?{setupIntent:Pe}:{paymentIntent:Pe});return}if(be.kind==="terminal"){if(zt=!0,xi(Ae,Oe,It),Te.current=null,T.current=null,!$.current)return;he("idle"),u(),_e(xe,new Error("Wallet confirmation did not complete."),"stripe_wallet_confirmation_terminal",w?.generation);return}$.current&&!zt&&(he("blocked"),Se(!1))}catch{$.current&&!zt&&(he("blocked"),Se(!1))}finally{Xn=!1}}},T.current=hn;let Yt,ze;try{let Pe=await(Ti(It)?S.confirmSetup({elements:W,clientSecret:It,redirect:"if_required"}):S.confirmPayment({elements:W,clientSecret:It,redirect:"if_required"}));if(!Pe||typeof Pe!="object"||(Yt=Pe,!Yt.error&&!Ln(Yt)))throw Mi;ze=vn(Yt.error?"returned_error":"resolved")}catch(Pe){let E=Pe===Mi,be=vn(E?"returned_error":"rejected");if(K?.error({...E?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response"}:ci(Pe),...vt,operationOutcome:be.operationOutcome,durationMs:be.durationMs,statusClass:"unknown"}),!$.current||Dt)return;await hn?.();return}let Ut=Yt.error;if(Ut){if(!$.current||Dt)return;if(Ko(Ut)){zt=!0,xi(Ae,Oe,It),Te.current=null,T.current=null,he("idle");let Pe=Ut.message??"Your payment was declined.";u(Pe),l?.(Pe),v?.(nn(Ct,Pe,{code:Pr(Ut),declineCode:mo(Ut)})),Na({billingApiUrl:r,sessionId:Ae,nonce:Oe,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:xe,providerDeclineReason:Pr(Ut)??"provider_declined",...Ft.intentKind==="payment"&&Ft.providerObjectId.startsWith("pi_")?{providerIntentId:Ft.providerObjectId}:{}}})}else K?.error({...ci(Ut),...vt,operationOutcome:ze.operationOutcome,durationMs:ze.durationMs,statusClass:"unknown"}),await hn?.();return}if($n(Yt),!Dt)throw new Error("Invalid provider returned for APM intent")}catch(Ae){if(Ae===Ai){let Oe=K?.now()??globalThis.performance?.now()??Date.now();K?.error({errorCode:Kd(cn),stage:In,requestCategory:cn,paymentMethodCategory:"wallet",provider:"stripe",...nt?{walletType:nt}:{},operationOutcome:"watchdog_expired",checkoutSessionId:fn,durationMs:Math.max(0,Oe-Wt),statusClass:"timeout",failureCategory:rn,attempt:xt}),K?.flush?.().catch(()=>{})}u(),_e(xe,Ae,Ae===Ai?"stripe_wallet_authorization_timeout":"stripe_wallet_failed",w?.generation)}finally{if(window.clearTimeout(dn),N!==null&&(window.clearTimeout(N),dt.current.delete(N)),!sr){let Ae=K?.now()??globalThis.performance?.now()??Date.now();K?.performance({stage:"callback",durationMs:Math.max(0,Ae-Wt),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe",...yn?{statusClass:"timeout"}:{}})}$.current&&Se(!1)}},[S,W,e,t,n,y,St,_,r,ge,o,s,l,v,h,_e,x,ot,Me,ke,qe,ue]),Mt=Et(()=>{let R=["applePay","googlePay","paypal","link","amazonPay","klarna"],ne=new Set(["applePay","googlePay"]),u=new Set(i.map(hl)),w={};for(let xe of R)u.has(xe)?w[xe]=ne.has(xe)?"always":"auto":w[xe]="never";return w},[i]),mt=Et(()=>i.map(hl),[i]);return Ue(Wr,{children:[c(Nl,{state:Y,placeholderTestId:"flopay-wallet-placeholder",borderRadius:U,children:Ue("div",{ref:je,tabIndex:-1,"data-testid":"flopay-wallet-focus-target",role:"group","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[Xe&&Ue("button",{ref:$e,type:"button","data-testid":"flopay-wallet-retry-button",onClick:ve,style:Li,children:["Try ",Oi(st)," again"]}),Ie!=="idle"&&Ue("div",{role:"status","aria-live":"polite",children:[c("p",{children:"We are still confirming your payment. Check its status before trying again."}),c("button",{type:"button",onClick:Vt,disabled:Ie==="checking",style:Li,children:Ie==="checking"?"Checking payment status\u2026":"Check payment status"})]}),Ge&&c(po,{identity:Ge.identity,methodLabel:Ge.methodLabel,onComplete:tt,onCancel:()=>tt(null)},Ge.id),Ie==="idle"&&c("div",{style:{display:Ge?"none":void 0},children:c(Al,{onReady:R=>{de(Dl(R,mt))},onLoadError:R=>{de("load_error"),$i(Qt(qe),"stripe","wallet")},onClick:async R=>{ie.current=R.expressPaymentType,rt.current=Il(R.expressPaymentType);let ne=!0,u=window.setTimeout(()=>{ne=!1,R.reject()},Od),w=h?await h(rt.current):{proceed:!0};if(window.clearTimeout(u),!ne)return;if(!w.proceed){We.current.delete(ue),R.reject();return}let xe=se(R.expressPaymentType);We.current.set(ue,{generation:xe,method:R.expressPaymentType,accountPatch:w.accountPatch,sessionId:w.sessionId,nonce:w.nonce}),ee(!1),p?.(rt.current),R.resolve()},onConfirm:H,onCancel:()=>{let R=We.current.get(ue);We.current.delete(ue),Qt(qe)?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet"}),Q(R?.generation),Te.current=null,ee(!1),Ee.current=!0,Ke()},options:{buttonType:{applePay:"plain",googlePay:"plain"},paymentMethods:Mt,emailRequired:Re,billingAddressRequired:Re,layout:{maxColumns:1,overflow:"never"}}},ue)})]})}),Le&&c(yr,{status:"processing"})]})}function Ll(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:p,textColor:v,borderRadius:g,fontFamily:h}){let y=Bd(e,t),_=yl[e],[M,U]=oe(!1),qe=!!_&&!M,ge=y?.backgroundColor??l??"#ffffff",S=y?.borderColor??p??"#d1d5db",W=y?.textColor??v??"#262833";return c("button",{type:"button","data-testid":`flopay-stripe-method-button-${e}`,"data-method":e,onClick:()=>{!n&&!r&&s()},disabled:n||r,"aria-busy":n||void 0,style:{position:"relative",width:"100%",boxSizing:"border-box",height:Fa,padding:"0 1rem",backgroundColor:ge,color:W,border:`1px solid ${S}`,borderRadius:g??8,fontSize:"0.95rem",fontWeight:600,fontFamily:h,cursor:n||r?"not-allowed":"pointer",opacity:r&&!n?.55:1,animation:n?"flopay-pulse 1.5s ease-in-out infinite":void 0,display:"flex",alignItems:"center",justifyContent:"center",gap:8,transition:"transform 0.1s, opacity 140ms ease-out, border-color 140ms ease-out",boxShadow:o?"0 0 0 2px rgba(74, 73, 255, 0.15)":void 0},children:n?c("span",{style:{margin:"0 auto"},children:`Connecting to ${Hr(e)}\u2026`}):Ue(Wr,{children:[Ue("span",{style:{display:"inline-flex",alignItems:"center",gap:kd(e)?8:0},children:[qe?c("img",{src:_,alt:"","aria-hidden":"true",onError:()=>U(!0),loading:"lazy",decoding:"async",width:30,height:20,style:{width:30,height:20,flexShrink:0,borderRadius:3,objectFit:"contain",display:"inline-flex"}}):null,!qe&&y?.logoSvg?c("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:y.logoSvg}}):null,c("span",{children:Hr(e)})]}),i&&c("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:W,strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{position:"absolute",right:"1rem",top:"50%",transform:"translateY(-50%)",flexShrink:0,opacity:.7},"aria-hidden":"true",children:c("path",{d:"M9 18l6-6-6-6"})})]})})}function zi({method:e,sessionId:t,nonce:n,email:r,billingName:o,onBuyerIdentityReady:i,billingApiUrl:s,onTokenizedBody:l,onErrorChange:p,onDecline:v,onCancel:g,runBeforeButtonClick:h,onButtonClick:y,isProcessing:_,submitButtonColor:M,submitButtonBorderRadius:U,submitButtonStyle:qe,errorText:ge}){let S=kr(),{emitInstrument:W}=Co(Gn),Y=qi(),de=Ui(),[Le,Se]=oe(!1),Re=ce(!1),[Ge,St]=oe(!1),[tt,je]=oe("loading"),[$e,ue]=oe(""),we=!ln(r?.trim()),Xe=!we||ln($e.trim()),ee=Je(async()=>{if(!Y||!de||_||Re.current||!Ge)return;Re.current=!0,Se(!0);let Ie=h?await h("card"):{proceed:!0};if(!Ie.proceed){Re.current=!1,Se(!1);return}y?.("card");let he=Ie.sessionId??t,st=Ie.nonce??n,lt=qr(o?.trim()),T=Dn({email:Ie.accountPatch?.email?.trim()||r?.trim()||$e.trim(),firstName:Ie.accountPatch?.firstName?.trim()||lt.firstName,lastName:Ie.accountPatch?.lastName?.trim()||lt.lastName}),$=T.email,Ee=Dn({...Ie.accountPatch,...T});try{if(p?.(null),!ln($))throw new Error("A valid email address is required for payment.");await i?.(T);let ie=await de.submit();if(ie.error){p?.(ie.error.message??"Payment failed.");return}let rt=[T.firstName,T.lastName].filter(Boolean).join(" "),A=await Y.createPaymentMethod({elements:de,params:{billing_details:{email:$,...rt?{name:rt}:{}}}});if(A.error||!A.paymentMethod){p?.(A.error?.message??"Failed to create payment method.");return}let Te=A.paymentMethod;if(!he||!$)throw new Error("Missing sessionId or email for payment.");let dt=Te.type||e,We=await Da(s,W,he,st??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:dt,paymentMethodId:null,intentKind:"payment"});if(We.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let se=We.clientSecret;if(typeof window<"u")try{localStorage.setItem(fr,JSON.stringify({clientSecret:se,sessionId:he,nonce:st,accountPatch:Ee,paymentMethodId:Te.id,paymentMethodType:Te.type??e,gateway:"stripe"}))}catch{}let{error:x,paymentIntent:Q}=await Y.confirmPayment({clientSecret:se,confirmParams:{return_url:window.location.href,payment_method:Te.id},redirect:"if_required"});if(x){if(typeof window<"u")try{localStorage.removeItem(fr)}catch{}let ke=x.message??"Payment failed.";p?.(ke),v?.(nn("card",ke,{code:x.code})),await Na({billingApiUrl:s,sessionId:he,nonce:st,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:x.code??"provider_declined"}});return}let Me=Q?.status;if(!qo(Me)){if(typeof window<"u")try{localStorage.removeItem(fr)}catch{}let ke=Me==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";p?.(ke),v?.(nn("card",ke,{code:Me??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(fr)}catch{}let ot=typeof Q?.payment_method=="string"?Q.payment_method:Q?.payment_method?.id;l({id:ot??Te.id,type:"card",threeDSecureActionResultTokenId:Q?.id,gateway:"stripe",paymentMethodType:Te.type??e},{accountPatch:Ee,paymentMethodCategory:"apm",sessionId:he,nonce:st})}catch(ie){p?.(ie instanceof Error?ie.message:"Payment failed. Please try again.")}finally{Re.current=!1,Se(!1)}},[Y,de,_,Ge,h,y,t,n,r,o,$e,i,s,W,e,l,p,v]);return Ue("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[we&&c("div",{"data-testid":"flopay-apm-identity-fields",style:{display:"flex",flexDirection:"column",gap:"0.75rem",marginBottom:"0.75rem"},children:we&&Ue("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",c("input",{type:"email",autoComplete:"email",required:!0,value:$e,onChange:Ie=>ue(Ie.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]})}),c(Dd,{onReady:()=>je("ready"),onLoadError:()=>{je("load_error"),$i(Qt(S),"stripe","apm")},onChange:Ie=>{St(!!Ie.complete)},options:{layout:{type:"accordion",defaultCollapsed:!1,radios:"never"},fields:{billingDetails:{email:"never"}},defaultValues:{billingDetails:{...o?.trim()?{name:o.trim()}:{},...ln(r?.trim())?{email:r?.trim()}:{}}}}}),c("button",{type:"button","data-testid":`flopay-stripe-method-pay-${e}`,onClick:()=>{ee()},disabled:!Ge||!Xe||Le||_||tt!=="ready",style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:M,color:"white",border:"none",borderRadius:U,fontSize:"1rem",fontWeight:600,cursor:!Ge||!Xe||Le||_||tt!=="ready"?"not-allowed":"pointer",opacity:!Ge||!Xe||Le||_||tt!=="ready"?.5:1,transition:"opacity 120ms ease-out",...qe??{}},children:Le?"Processing\u2026":`Pay with ${Hr(e)}`}),ge&&c(fo,{margin:"0.75rem 0 0",children:ge})]})}function Tl({sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:i,paymentElementMethods:s,stripeInstance:l,paymentElementBaseOptions:p,onTokenizedBody:v,onErrorChange:g,onButtonClick:h,onDecline:y,runBeforeButtonClick:_,onLoadStateChange:M,isProcessing:U=!1,submitButtonColor:qe="#4A49FF",submitButtonBorderRadius:ge=8,submitButtonStyle:S,buttonAppearance:W,themeId:Y,onExpandApm:de,expandedApmMethod:Le}){let{emitInstrument:Se}=Co(Gn),[Re,Ge]=oe(null),[St,tt]=oe(null),je=ce(!1),{request:$e,collect:ue,finish:we}=uo();ft(()=>{s.length>0&&l?M?.("ready"):l||M?.("loading")},[s.length,l,M]);let Xe=Je(async T=>{if(!l||je.current||U)return;je.current=!0,tt(T);let $=_?await _("card"):{proceed:!0};if(!$.proceed){je.current=!1,tt(null);return}h?.("card");let Ee=$.sessionId??e,ie=$.nonce??t,rt=qr([$.accountPatch?.firstName,$.accountPatch?.lastName].filter(Boolean).join(" ")||r),A=Dn({email:$.accountPatch?.email?.trim()||n?.trim(),firstName:$.accountPatch?.firstName?.trim()||rt.firstName,lastName:$.accountPatch?.lastName?.trim()||rt.lastName});if(!ln(A.email)){tt(null);let We=await ue(Hr(T),A);if(!We){je.current=!1;return}A=We,tt(T)}let Te=A.email,dt=Dn({...$.accountPatch,...A});try{if(g?.(null),!Ee||!ln(Te))throw new Error("Missing sessionId or email for payment.");await o?.(A);let We=await Da(i,Se,Ee,ie??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:T,paymentMethodId:null,intentKind:"payment"});if(We.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let se=We.clientSecret;if(typeof window<"u")try{localStorage.setItem(fr,JSON.stringify({clientSecret:se,sessionId:Ee,nonce:ie,accountPatch:dt,paymentMethodType:T,gateway:"stripe"}))}catch{}let{error:x,paymentIntent:Q}=await l.confirmPayment({clientSecret:se,confirmParams:{return_url:window.location.href,payment_method_data:{type:T,billing_details:{name:[A.firstName,A.lastName].filter(Boolean).join(" "),...Te?{email:Te}:{}}}},redirect:"if_required"});if(x){if(typeof window<"u")try{localStorage.removeItem(fr)}catch{}let ke=x.message??"Payment failed.";g?.(ke),y?.(nn("card",ke,{code:x.code})),await Na({billingApiUrl:i,sessionId:Ee,nonce:ie,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:T,providerDeclineReason:x.code??"provider_declined"}});return}let Me=Q?.status;if(!qo(Me)){if(typeof window<"u")try{localStorage.removeItem(fr)}catch{}let ke=Me==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";g?.(ke),y?.(nn("card",ke,{code:Me??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(fr)}catch{}let ot=typeof Q?.payment_method=="string"?Q.payment_method:Q?.payment_method?.id;v({id:ot??Q?.id,type:"card",threeDSecureActionResultTokenId:Q?.id,gateway:"stripe",paymentMethodType:T},{accountPatch:dt,paymentMethodCategory:"apm",sessionId:Ee,nonce:ie})}catch(We){g?.(We instanceof Error?We.message:"Payment failed. Please try again.")}finally{je.current=!1,tt(null)}},[l,U,_,h,e,t,n,ue,i,Se,r,o,v,g,y]),[ee,Ie]=oe(null),he=de?Le??null:ee,st=Je(T=>{je.current||U||he&&he!==T||(gl(T)?de?de(T):Ie(T):Xe(T))},[he,U,Xe,de]),lt=Et(()=>ee?Ll(p,ee):null,[ee,p]);return c("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:$e?c(po,{identity:$e.identity,methodLabel:$e.methodLabel,onComplete:we,onCancel:()=>we(null)},$e.id):s.map(T=>{let $=Le===T,Ee=St===T,ie=St!==null&&St!==T||Le!=null&&Le!==T;return Ue(Nd.Fragment,{children:[c(su,{method:T,themeId:Y,submitting:Ee,disabled:ie,highlighted:$,hasNextStep:gl(T),onClick:()=>st(T),backgroundColor:W?.backgroundColor,borderColor:W?.borderColor,textColor:W?.textColor,borderRadius:W?.borderRadius,fontFamily:W?.fontFamily}),!de&&ee===T&<&&l&&c(Vr,{stripe:l,options:lt,children:c(zi,{method:T,sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:i,onTokenizedBody:v,onErrorChange:g,onDecline:y,onCancel:()=>Ie(null),runBeforeButtonClick:_,onButtonClick:h,isProcessing:U,submitButtonColor:qe,submitButtonBorderRadius:ge,submitButtonStyle:S})},T)]},T)})})}function lu({sessionId:e,nonce:t,billingApiUrl:n,telemetry:r,email:o,userId:i,onComplete:s,onError:l,onDecline:p,onTokenizedBody:v,firstName:g,lastName:h,chv:y,className:_,submitLabel:M,isProcessing:U,error:qe,onErrorChange:ge,showPayPal:S=!0,showStripe:W=!0,enabledPaymentMethods:Y,enabledPaymentMethodCountries:de,showApplePay:Le=!0,showGooglePay:Se=!0,layout:Re="default",theme:Ge,buttonsTheme:St,buttonsStyles:tt,appearance:je,cardButtonContent:$e,cardBackButtonContent:ue,cardTitleContent:we,showSecurityFooter:Xe,onButtonClick:ee,onBeforeButtonClick:Ie,onBuyerIdentityReady:he,enableAVS:st,cardFieldOrder:lt,cardPreFormSlot:T,avsLayout:$="row",country:Ee,zip:ie,addressLine1:rt,addressLine2:A,city:Te,state:dt,onCountryChange:We,onZipChange:se,avsCheck:x,checkoutType:Q,checkoutLayout:Me,totalAmount:ot=0,currency:ke="usd",initialCardOpen:Ke=!1,directPaypal:_e,isSubscription:le=!1,session:ve,dataAttachmentPending:Vt=!1,dataAttachmentRequiresIdentity:H=!1,debug:Mt=!1}){let mt=kr(),R=di(),ne=Co(ar),{emitInstrument:u}=Co(Gn),w=ve??ne.session,xe=w?.gateways?.paypal?.providerObjectType??_e?.providerObjectType,me=Vt||ne.claimPending===!0,Ct=H||ne.claimRequiresIdentity===!0,nt=me&&!Ct,xt=Qs(),K=n||xt,[Wt,wt]=oe(!1),[yn,sr]=oe(null),[N,fn]=oe(Ee??"US"),[In,cn]=oe(ie??""),[rn,gn]=oe(rt??""),[Jn,dn]=oe(A??""),[Ht,Ae]=oe(Te??""),[Oe,on]=oe(dt??""),[ut,jn]=oe(""),[Bt,Gt]=oe({}),gt=ce(ie??""),$t=ce(Ee??"US"),un=ce(rt??""),Ft=ce(A??""),It=ce(Te??""),an=ce(dt??""),Nn=ce(""),vt=ce({});ft(()=>{let a=(P,O,Ne,j,at)=>{if(vt.current[P])return;let Ze=O?.trim();!Ze||Ze===Ne.current||(Ne.current=Ze,j(Ze),at?.(Ze))};a("country",Ee,$t,fn,We),a("zip",ie,gt,cn,se),a("addressLine1",rt,un,gn),a("addressLine2",A,Ft,dn),a("city",Te,It,Ae),a("state",dt,an,on)},[Ee,ie,rt,A,Te,dt,We,se]);let J=Et(()=>Md(st),[st]),hn=J!==null,vn=Et(()=>Ei(ve),[ve]),Dt=!!ve?.vault?.html,zt=!!ve?.gateways?.pcivault,Ln=ii(ve),Xn=!!(ve?.gateways?.stripe?.enabledPaymentMethods??Y)?.includes("card")||Ur(ve),Yt=Dt||Xn||zt,ze=!!(W&&Yt&&e),[Ut,Pe]=oe(()=>Re!=="buttons"||Ke?e??null:null),[E,be]=oe(0),I=Re!=="buttons"||Ke||!!e&&Ut===e,Nt=ve?.captureMethod,Pn=ce(mt);ft(()=>{Pn.current=mt},[mt]);let[sn,On]=oe(null);ft(()=>{if(!ze||!e||!I){On(null);return}let a=Pn.current?Pn.current.cardCapture({sessionId:e,captureMethod:Nt}):new vd({sessionId:e,captureMethod:Nt,billingApiUrl:K,telemetry:r});return On({sessionId:e,captureMethod:Nt,billingApiUrl:K,telemetry:r,capture:a}),()=>{a.unmount()}},[ze,e,I,Nt,K,r]);let ae=ze&&e&&I&&sn?.sessionId===e&&sn.captureMethod===Nt&&sn.billingApiUrl===K&&sn.telemetry===r?sn.capture:null,bn=Et(()=>{let a=N,P=J?et(J.postal_code,a):!1;return ou(a,In,P)},[J,N,In]),{avsInvalid:Br,invalidAvsFields:Gr}=Et(()=>{let a={line1:!1,city:!1,state:!1,zip:!1};if(!ze||!J)return{avsInvalid:!1,invalidAvsFields:a};let P=N,O=(at,Ze)=>et(at,P)&&!Ze.trim(),Ne={line1:O(J.address_line_1,rn),city:O(J.city,Ht),state:O(J.state,Oe),zip:bn.empty||bn.malformed};return{avsInvalid:Ne.line1||Ne.city||Ne.state||Ne.zip,invalidAvsFields:Ne}},[ze,J,N,rn,Ht,Oe,bn]),[kn,wr]=oe(!1),[lr,Zn]=oe(!1),[Kt,_n]=oe(!1),[vr,zn]=oe({line1:!1,city:!1,state:!1}),Rn=ce(!1),Qn=ce({email:!1,line1:!1,city:!1,state:!1,zip:!1}),er=ce(!1),Pt=Je(a=>{Qn.current[a]=!0,er.current=!0},[]),Cn=Je(a=>!Rn.current&&Qn.current[a],[]),Kn=Je(a=>{Cn(a)&&zn(P=>P[a]?P:{...P,[a]:!0})},[Cn]),[tr,En]=oe(()=>Fi(ve?.vault)),[Ve,tn]=oe(Ke&&Yt?"card":"buttons"),[pn,cr]=oe(null),Fr=Ve==="expanding"||Ve==="card",nr=ve?.gateways?.stripe&&!Ln?"stripe":void 0,dr=Je(()=>{u?.({class:"card_surface",provider:nr})},[nr,u]),Tn=ce(null),An=Je(a=>{Tn.current&&clearTimeout(Tn.current),Tn.current=setTimeout(()=>{Tn.current=null,a()},Zo)},[]);ft(()=>()=>{Tn.current&&clearTimeout(Tn.current)},[]);let Dr=Je(()=>{dr(),Pe(e??null),be(a=>a+1),tn("expanding"),An(()=>tn("card"))},[An,dr,e]),Un=Je(()=>{tn("collapsing"),An(()=>tn("buttons"))},[An]),Nr=Je(a=>{cr(a),tn("apm-expanding"),An(()=>tn("apm-form"))},[An]),Jt=Je(()=>{tn("apm-collapsing"),An(()=>{tn("buttons"),cr(null)})},[An]);ft(()=>{Re==="buttons"&&Ke&&Yt&&(Pe(e??null),tn("card"))},[Re,Ke,Yt,e]);let[k,f]=oe(null),G=ce(!1),B=ce(null),Ce=ce("idle"),[ct,ye]=oe(!1),z=ce(ct);z.current=ct;let[X,F]=oe(null),m=ce(X);ft(()=>{m.current=X},[X]);let d=ce(null),C=Et(()=>{if(he||ne.claimBuyerIdentity||ve?.buyerIdentified!==!1||!e||!t)return;let a=`${K}|${e}|${t}`;d.current?.key!==a&&(d.current={key:a,claim:lo(new bo(K,{telemetry:!1}),e,t,{...i?{userId:i}:{},...g?{firstName:g}:{},...h?{lastName:h}:{}})});let P=d.current.claim;return async O=>{await P(O)}},[he,ne.claimBuyerIdentity,ve?.buyerIdentified,e,t,K,i,g,h]),L=he??ne.claimBuyerIdentity??C,te=qe??yn,V=Et(()=>Fd(Ge),[Ge]),b=Et(()=>{let a=V?.buttonsLayout??xd(St);return tt?{...a,...tt,cardButton:{...a.cardButton,...tt.cardButton},cardFormContainer:{...a.cardFormContainer,...tt.cardFormContainer},backButton:{...a.backButton,...tt.backButton},backButtonIcon:{...a.backButtonIcon,...tt.backButtonIcon},submitButton:{...a.submitButton,...tt.submitButton},title:{...a.title,...tt.title}}:a},[V,St,tt]),Z=je??V?.appearance,pt=Et(()=>Ns({appearance:Z,buttonsStyles:b,layout:Re}),[Z,b,Re]),qt=ne.inlineSessionPatchProcessing??!1,Be=(U??Wt)||qt,fe=K.replace(/\/+$/,""),D=Et(()=>li({userId:i,email:o,firstName:g,lastName:h,country:Ee,zip:ie},Bt),[i,o,g,h,Ee,ie,Bt]),q=[D.firstName,D.lastName].filter(a=>!!a?.trim()).join(" "),Fe=!ln(D.email?.trim()),De=ce(null);ze&&De.current===null&&(De.current=Fe);let kt=ze&&(De.current??Fe),He=Et(()=>au(ut,kt),[ut,kt]),Mn=He.empty||He.malformed,Xt=Et(()=>mt?mt.getRawProvider():null,[mt]),Yr=Et(()=>R?R.getRawProvider():null,[R]),_o=ot||100,Jr=ke.toLowerCase(),qa=Et(()=>Z?Pd(Z):null,[Z]),Xr=qa,rs=Et(()=>{let a=qa??{},P=a.rules??{};return{...a,rules:{...P,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...P[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...P[".AccordionItemContents"]??{}}}}},[qa]),os=Et(()=>({...Hs(ot,ve?.captureMethod),currency:Jr,...Xr?{appearance:Xr}:null}),[ot,Jr,ve?.captureMethod,Xr]),as=Et(()=>({mode:"payment",amount:_o,currency:Jr,captureMethod:"manual",setupFutureUsage:"off_session",...Xr?{appearance:Xr}:null}),[_o,Jr,Xr]),pe=Je(a=>{sr(a),ge?.(a)},[ge]),ja=ce(""),[is,Yl]=oe(!1),$a=Je(()=>{Yl(!0)},[]);ft(()=>{if(!ze||!kt||!L||!is||Mn||ja.current)return;let a=Dn({email:ln(D.email?.trim())?D.email?.trim():Nn.current.trim(),firstName:D.firstName?.trim(),lastName:D.lastName?.trim()});ja.current=JSON.stringify(a),Gt(P=>({...P,...a})),Promise.resolve(L(a)).catch(P=>{ja.current="",pe(P instanceof Error?P.message:"Failed to attach buyer details.")})},[ze,kt,L,is,Mn,D.email,D.firstName,D.lastName,pe]),ft(()=>{!ze||!ae||ae.setCardFieldOrder?.(lt??null,J==null&&!kt)},[ze,ae,lt,J,kt]),ft(()=>{(Ve==="expanding"||Ve==="collapsing"||Ve==="apm-expanding"||Ve==="apm-collapsing")&&pe(null)},[Ve,pe]);let ur=Je((a,P,O)=>{p?.(nn(a,P,O))},[p]),Zr=Je((a,P,O)=>{let Ne=O?.popupBlocked??br(P),j=nu(a,Ne),at=$r(O?.code)??Pr(P)??"external_payment_method_failed",Ze=new ir(j,"api_error",{code:"external_payment_method_failed",param:a});f(null),Re==="buttons"&&(tn("buttons"),cr(null)),pe(j),l?.(Ze),console.error("[FloPay] External payment method failed:",{method:a,code:at,popupBlocked:Ne})},[Re,l,pe]);ft(()=>{if(!ze||!e){En(null);return}let a=Fi(ve?.vault);if(a){En(a);return}if(!I){En(null);return}En(null);let P=!0;return new bo(fe).getVaultCapture(e,t).then(O=>{if(!P)return;let Ne=Fi(O);Ne?En(Ne):pe("Failed to load the secure card form.")}).catch(O=>{P&&pe(O instanceof Error?O.message:"Failed to load the secure card form.")}),()=>{P=!1}},[ze,I,E,e,ve?.vault,fe,t,pe]);let rr=ce({onComplete:s,onError:l,updateError:pe,emitDecline:ur,resolvedAccount:D,avsConfig:J,avsCheckProp:x,sessionId:e,nonce:t,baseUrl:fe,captureMethod:ve?.captureMethod,paymentId:ve?.paymentId,authorizationExpiresAt:ve?.authorizationExpiresAt,serverSideCardGateway:Ln});rr.current={onComplete:s,onError:l,updateError:pe,emitDecline:ur,resolvedAccount:D,avsConfig:J,avsCheckProp:x,sessionId:e,nonce:t,baseUrl:fe,captureMethod:ve?.captureMethod,paymentId:ve?.paymentId,authorizationExpiresAt:ve?.authorizationExpiresAt,serverSideCardGateway:Ln};let Ka=ce(!1),ss=Je(()=>{let a=rr.current,P=a.resolvedAccount.email?.trim(),O=ln(P)?P:Nn.current.trim();if(!ln(O))return null;let Ne=a.resolvedAccount.firstName?.trim(),j=a.resolvedAccount.lastName?.trim(),at=$t.current||a.resolvedAccount.country||"US",Ze=a.avsConfig?et(a.avsConfig.state,at):!1,mr=a.avsConfig?et(a.avsConfig.address_line_1,at):!1,Ye=a.avsConfig?et(a.avsConfig.postal_code,at):!1,_t=a.avsConfig?et(a.avsConfig.city,at):!1,yt=a.avsConfig?et(a.avsConfig.address_line_2,at):!1,Qe=mr&&!Ze&&Ye?fl(at,(gt.current??"").trim()):null,Fn=Ze?an.current:Qe;return{accountData:{userId:a.resolvedAccount.userId??"",email:O,...Ne?{firstName:Ne}:{},...j?{lastName:j}:{},...Ye&>.current?{zip:gt.current}:{},..._t&&It.current?{city:It.current}:{},...Fn?{state:Fn}:{},...mr&&un.current?{addressLine1:un.current}:{},...yt&&Ft.current?{addressLine2:Ft.current}:{},country:at},...a.avsCheckProp===void 0?{}:{avsCheck:a.avsCheckProp},...a.avsConfig?{avsConfig:{country:et(a.avsConfig.country,at),postal_code:Ye,address_line_1:mr,address_line_2:yt,city:_t,state:Ze}}:{}}},[]),ls=ce(me);ls.current=me,ft(()=>{me||te!==Cl||rr.current.updateError(null)},[me,te]),ft(()=>{!ze||!ae||ae.setSubmitGate?.(Br||me||Mn||ct)},[ze,ae,Br,me,Mn,ct]),ft(()=>{if(!ze||!ae)return;Ka.current=!1;let a=null,P=()=>{a&&clearTimeout(a),a=setTimeout(()=>{a=null,Ce.current="idle",f(null)},400)},O=ae.on("submitting",()=>{wr(!0),B.current&&clearTimeout(B.current),Ce.current="validation-window",B.current=setTimeout(()=>{B.current=null,Ce.current==="validation-window"&&(Ce.current="processing")},Vd),f("processing");let Ye=rr.current;if(!Ye.sessionId||!Ye.nonce)return;let _t=ss();if(!_t){Ye.updateError("Enter a valid email address."),Ce.current="idle",f(null);return}new bo(Ye.baseUrl).patchAccountSnapshot(Ye.sessionId,Ye.nonce,_t,{telemetryMode:"best_effort"}).catch(yt=>{if(!Hd(yt))return;let Qe=yt instanceof Error?yt.message:"Please check your billing address and try again.";Ye.updateError(Qe),Ce.current="idle",f(null),Ye.onError?.(yt instanceof ir?yt:new ir(Qe,"api_error"))})}),Ne=ae.on("complete",async Ye=>{if(vo(Ye.sessionId??rr.current.sessionId),Ce.current="terminal",ye(!1),f("success"),await new Promise(Fn=>setTimeout(Fn,600)),Ka.current)return;Ka.current=!0;let _t=rr.current,yt=Ei(_t)||Ye.outcome==="authorized",Qe=_t.serverSideCardGateway?{}:{paymentIntentId:Ye.intentId};rr.current.onComplete?.(yt?{status:"authorized",...Qe,paymentId:Ye.paymentId??_t.paymentId,sessionId:Ye.sessionId??_t.sessionId,authorizationExpiresAt:Ye.authorizationExpiresAt??_t.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",...Qe,checkoutMethod:"card"})}),j=ae.on("decline",Ye=>{let _t=rr.current,yt=Ye.message??"Your payment was declined. Please try another card or contact your bank.";Ce.current="terminal",ye(!1),_t.updateError(yt),f("error");let Qe=Ye.failureOutcome??Ed(Ye.declineReason)??"authorization_declined";_t.emitDecline("card",yt,{code:Qe,declineCode:Qe}),P()}),at=ae.on("error",Ye=>{let _t=rr.current,yt=Ye.message??"There was a problem processing your payment. Please try again.";Ce.current="terminal",ye(!1),_t.updateError(yt),f("error"),_t.onError?.(new ir(yt,"api_error",{code:Ye.failureOutcome??"capture_failed"})),P()}),Ze=ae.on("challenge_dismissed",()=>{B.current&&(clearTimeout(B.current),B.current=null),Ce.current="processing",ye(!0),f(null)}),mr=ae.on("blocked",()=>{if(z.current){rr.current.updateError(Wd);return}if(!ls.current){wr(!0);return}$a(),rr.current.updateError(Cl)});return()=>{a&&(clearTimeout(a),a=null),B.current&&(clearTimeout(B.current),B.current=null),Ce.current="idle",ye(!1),f(null),O(),Ne(),j(),at(),Ze(),mr()}},[ze,ae,$a,ss]);let pr=!!_e?.clientId,Ro=Array.isArray(Y),oa=Ro&&Y.length>0,Jl=Ro&&Y.includes("paypal"),{expressMethods:aa,paymentElementMethods:Eo}=Et(()=>Td(Y,{excludePaypal:pr}),[Y,pr]),cs=pr||!!R,Xl=Et(()=>cs?aa.filter(a=>a!=="paypal"):aa,[aa,cs]),Zl=Et(()=>{let a=[];return Le&&a.push("apple_pay"),Se&&a.push("google_pay"),a},[Le,Se]),Qr=Ro?Xl:Zl,Ql=W&&Qr.length>0,Va=hn?N:Ee,ia=Et(()=>{let a=Va?.trim().toUpperCase();return a?de?Eo.filter(P=>{let O=de[P];return!O||O.length===0||O.includes(a)}):Sd(Eo,Va):Eo},[Eo,Va,de]),Wa=Et(()=>({mode:"payment",amount:_o,currency:Jr,paymentMethodCreation:"manual",appearance:rs}),[_o,Jr,rs]),[ds,us]=oe("loading"),[ps,ms]=oe("loading"),[ys,fs]=oe("loading"),[ec,Ha]=oe(!1),[gs,Ga]=oe("loading"),[Ya,tc]=oe();ft(()=>{tc(va())},[]);let sa=Ya?.inAppBrowser,la=Ya?Pa(Ya,_e?.approvalPresentation,xe??(le?"subscription":"order")):"popup",hs=S&&(pr||(Ro?Jl:sa===!1)),vs=W&&Ql,To=(!nt||!!ne.waitForDataAttachment)&&hs&&pr,Ps=gs==="retrying"||gs==="exhausted",Ao=!nt&&hs&&!!Yr&&(!pr||Ps),eo=!nt&&vs&&!!Xt,Mo=!nt&&W&&oa&&ia.length>0&&!!Xt,nc=To&&!Ps?ec:Ao&&_l(ds),rc=eo&&_l(ps),oc=Mo&&ys!=="load_error",bs=a=>a==="loading"||a==="ready",Cs=To||Ao&&bs(ds)||eo&&bs(ps)||Mo&&ys!=="load_error",ca=ce(!1);ft(()=>{if(!ca.current){if(!W&&!S){ca.current=!0;let a=new ir("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");l?.(a),pe(a.message)}else if(!W&&S&&!pr&&!Yr){ca.current=!0;let a=new ir("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");l?.(a),pe(a.message)}else if(sa!==void 0&&!nt&&!Yt&&!Cs){ca.current=!0;let a=new ir("FloPay: this checkout session has no vault card capability and no usable supported non-card payment methods. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});l?.(a),pe(a.message)}}},[W,S,pr,Yr,sa,nt,Yt,Cs,l,pe]);let Ss=ce(!1);ft(()=>{if(Ss.current||!oa)return;let a=[];Le!==!0&&a.push("showApplePay"),Se!==!0&&a.push("showGooglePay"),a.length!==0&&(Ss.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.`))},[oa,Le,Se]);let ws=Je((a,P)=>ne.applyInlineSessionPatch?ne.applyInlineSessionPatch(a).then(O=>({error:null,sessionId:O.sessionId||e,nonce:O.session?.clientSecret||t})).catch(O=>{let Ne=kl(P,O);return pe(Ne.message),l?.(Ne),{error:Ne,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[ne.applyInlineSessionPatch,t,l,e,pe]),or=Je(async a=>{if(a!=="card"&&nt&&await ne.waitForDataAttachment?.(),!Ie)return{proceed:!0};try{let P=await Ie({method:a,sessionId:e||void 0,createSession:ne.inlineSessionDraft});if(P===!1)return{proceed:!1};if(P&&typeof P=="object"){P.account&&Gt(Ne=>({...Ne??{},...P.account}));let O=await ws(P,a);return O.error?{proceed:!1,accountPatch:P.account}:{proceed:!0,accountPatch:P.account,sessionId:O.sessionId,nonce:O.nonce}}return{proceed:!0}}catch(P){let O=kl(a,P);return pe(O.message),l?.(O),{proceed:!1}}},[ws,ne.inlineSessionDraft,ne.waitForDataAttachment,nt,Ie,l,e,pe]),Is=Je(async(a,P)=>{if(G.current)return;G.current=!0,wt(!0),f("processing"),pe(null);let O=P?.sessionId??e,Ne=P?.nonce??t,j=li(D,P?.accountPatch),at=P?.completionPaymentMethodId??jo(a),Ze=a.originalPaymentMethodId?{...a,originalPaymentMethodId:void 0}:a,mr=Zd(a),Ye=()=>{u?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"process_payment",provider:mr})};try{let yt=await new bo(fe).processPayment(j.userId??"",{sessionId:O,nonce:Ne,paymentMethodCategory:P?.paymentMethodCategory??eu(a),tokenizedData:Ze,accountData:{...P?.accountPatch,userId:j.userId??"",email:j.email??"",firstName:j.firstName||void 0,lastName:j.lastName||void 0,...J?(()=>{let ht=$t.current,Wn=et(J.state,ht),Sn=et(J.address_line_1,ht),Zt=et(J.postal_code,ht),zr=Sn&&!Wn&&Zt?fl(ht,(gt.current??"").trim()):null,Lo=Wn?an.current:zr;return{country:ht,...Zt&>.current?{zip:gt.current}:{},...et(J.city,ht)&&It.current?{city:It.current}:{},...Lo?{state:Lo}:{},...Sn&&un.current?{addressLine1:un.current}:{},...et(J.address_line_2,ht)&&Ft.current?{addressLine2:Ft.current}:{}}})():{}},chv:y,avsCheck:x??!1,checkoutType:Q,checkoutLayout:Me,avsConfig:J?{country:et(J.country,$t.current),postal_code:et(J.postal_code,$t.current),address_line_1:et(J.address_line_1,$t.current),address_line_2:et(J.address_line_2,$t.current),city:et(J.city,$t.current),state:et(J.state,$t.current)}:void 0});if(yt.ok){let ht=yt.status===204?null:await yt.json().catch(()=>null),Wn=Ei(ve)||ht?.status==="authorized";vo(O),f("success"),F(null),await new Promise(zr=>setTimeout(zr,600));let Sn;typeof ht?.paymentId=="string"?Sn=ht.paymentId:ve?.paymentId&&(Sn=ve.paymentId);let Zt;typeof ht?.authorizationExpiresAt=="string"?Zt=ht.authorizationExpiresAt:ve?.authorizationExpiresAt&&(Zt=ve.authorizationExpiresAt),s?.(Wn?{status:"authorized",...Sn===void 0?{}:{paymentId:Sn},sessionId:typeof ht?.sessionId=="string"?ht.sessionId:O,...Zt===void 0?{}:{authorizationExpiresAt:Zt},paymentIntentId:a.threeDSecureActionResultTokenId,paymentMethodId:at,checkoutMethod:a.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:a.threeDSecureActionResultTokenId,paymentMethodId:at,checkoutMethod:a.isPaypal?"paypal":"card"});return}let Qe=await yt.json().catch(()=>null);if(Qe?.type==="paypal_redirect_required"){let ht=Qe.threeDSecureToken,Wn=Qe.paymentMethodId||a.id||"";if(!mt||!ht){f("error"),pe("PayPal authorization required but no token provided.");return}try{let Sn=R?.getRawProvider();if(!Sn){pe("PayPal is not available.");return}let Zt={return_url:window.location.href};Wn&&(Zt.payment_method=Wn);let{error:zr}=await Sn.confirmPayment({clientSecret:ht,confirmParams:Zt,redirect:"if_required"});if(zr){f("error");let Lo=zr.message??"PayPal payment failed.";pe(Lo),ur("paypal",Lo,{code:zr.code})}}catch(Sn){f("error"),pe(Sn instanceof Error?Sn.message:"PayPal authorization failed.")}return}if(Qe?.type==="paypal_direct_required"){let ht=Qe.orderId;if(!ht){f("error"),pe("PayPal retry required but no order id provided.");return}let Wn=m.current?.attempts??0;if(Wn>=2){f("error"),pe("PayPal payment could not be completed after multiple attempts."),ur("paypal","paypal_direct_required retry limit exceeded");return}Ha(!1),Ga("loading"),F({orderId:ht,attempts:Wn+1}),f(null);return}Cd(yt.status,Qe)||Ye(),f("error");let Fn=Qe?.message??"Payment failed. Please try again.";pe(Fn),ur(a.isPaypal?"paypal":"card",Fn,{code:Qe?.code??Qe?.gatewayErrorCode,declineCode:Qe?.declineCode??Qe?.gatewayDeclineReason}),await new Promise(ht=>setTimeout(ht,400))}catch(_t){Bl(_t)||Ye(),f("error"),pe(_t instanceof Error?_t.message:"An unexpected error occurred"),await new Promise(yt=>setTimeout(yt,400))}finally{wt(!1),f(null),G.current=!1}},[fe,e,t,D,J,x,Q,Me,y,mt,R,ve,s,pe,ur,u]),xn=Je((a,P)=>{v?v(a):Is(a,P)},[v,Is]),xo=`${Ml}:${e}`;ft(()=>{if(typeof window>"u")return;let a=localStorage.getItem(xo);if(!a)return;let P;try{P=JSON.parse(a)}catch{localStorage.removeItem(xo);return}if(!P||typeof P.createdAt!="number"||Date.now()-P.createdAt<0||Date.now()-P.createdAt>xl||typeof P.paymentMethodId!="string"||typeof P.providerIntentId!="string"||typeof P.paymentMethodType!="string"||P.sessionId!==e||!t||P.nonce!==t||!Qr.includes(P.paymentMethodType)){localStorage.removeItem(xo);return}localStorage.removeItem(xo),xn({id:P.paymentMethodId,type:"card",threeDSecureActionResultTokenId:P.providerIntentId,gateway:"stripe",paymentMethodType:P.paymentMethodType},{...P.accountPatch?{accountPatch:P.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t})},[xn,t,e,xo,Qr]);let ks=ce(!1);ft(()=>{if(typeof window>"u"||ks.current)return;let a=new URLSearchParams(window.location.search),P=a.get("payment_intent"),O=a.get("payment_intent_client_secret"),Ne=a.get("redirect_status");if(!P||!O||!mt)return;let j=mt.getRawProvider();if(!j)return;let at=Qe=>{let Fn=localStorage.getItem(Qe);if(!Fn)return null;try{return JSON.parse(Fn)}catch{return localStorage.removeItem(Qe),null}},Ze=at(fr)??at(vl),mr;if(Ze?.clientSecret){if(Ze.clientSecret!==O)return;mr={...Ze.accountPatch?{accountPatch:Ze.accountPatch}:{},...Ze.sessionId?{sessionId:Ze.sessionId}:{},...Ze.nonce?{nonce:Ze.nonce}:{}}}else if(Ze?.sessionId&&Ze.sessionId!==e)return;ks.current=!0,localStorage.removeItem(fr),localStorage.removeItem(vl);let Ye=new URL(window.location.href);Ye.searchParams.delete("payment_intent"),Ye.searchParams.delete("payment_intent_client_secret"),Ye.searchParams.delete("redirect_status"),window.history.replaceState({},"",Ye.toString());let _t=Ze?.paymentMethodType??Ze?.tokenType??"card",yt="card";(async()=>{if(Ne==="failed"){let Zt="Payment was declined. Please try again.";pe(Zt),ur(yt,Zt);return}let{paymentIntent:Qe,error:Fn}=await j.retrievePaymentIntent(O);if(Fn){let Zt=Fn.message??"Failed to retrieve payment status.";pe(Zt),ur(yt,Zt,{code:Fn.code});return}let ht=Qe?.status,Wn=qo(ht);if(!Qe||!Wn){let Zt=ht==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";pe(Zt),ur(yt,Zt,{code:ht??"missing_payment_intent"});return}let Sn=typeof Qe.payment_method=="string"?Qe.payment_method:Qe.payment_method?.id;xn({id:Sn??Ze?.paymentMethodId??Ze?.tokenId??Qe.id,type:"card",threeDSecureActionResultTokenId:Qe.id,gateway:Ze?.gateway??"stripe",paymentMethodType:_t},mr)})()},[e,xn,mt,pe,ur]);let Ja=Je(a=>{a.preventDefault()},[]);if(!(ze||mt!==null))return c("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let Bo=Re==="buttons",Bn=Z?.variables,ac=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),Xa=Bn?.colorBackground,ic=Xa&&!ac.has(Xa)?Xa:void 0,Fo=b.cardInputBorder??(Bo?"#e5e7eb":"#A4A4FF"),_s=Bn?.colorDanger??"#dc2626",Lt=a=>Gr[a]&&(vr[a]||kn),da=Mn&&(Kt||kn),Vn=a=>a?_s:Fo,ua=(bn.malformed||bn.empty)&&(lr||kn),sc=Vn(ua),Za=b.cardFormContainer?.backgroundColor??ic??(Bo?"white":"#EDEDFF"),to=b.cardInputBackground??Bn?.colorBackground??"white",Qa=oo(ue),Rs=oo(we),no=b.nameInput,Es=b.cardInputFontSize??iu(no?.fontSize)??Bn?.fontSizeBase??"16px",Ts=typeof no?.fontFamily=="string"?no.fontFamily:Bn?.fontFamily??"Poppins, sans-serif",As=Ds(no?.fontWeight)??400,lc=b.cardInputColor??(typeof no?.color=="string"?no.color:void 0)??Bn?.colorText??"#262833",cc=b.cardInputPlaceholderColor??"#9ca3af",jt=Bn?.borderRadius??"8px",Lr=Bn?.borderRadius??b.cardButton?.borderRadius??jt,Or=Bn?.colorPrimary??"#4A49FF",dc=Bn?.colorPrimaryHover??zo(Or,.12),ei=Bn?.colorText??"#262833",ti={fontSize:Es,fontFamily:Ts,fontWeight:As,color:lc,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},Do={marginTop:"0.375rem",...ti,fontSize:"0.75rem",lineHeight:1.4,color:_s},uc={"--flopay-input-placeholder-color":cc,"--flopay-input-font-size":Es,"--flopay-input-font-family":Ts,"--flopay-input-font-weight":String(As)},No=b.cardFormContainer??{},ni=No.padding??(Bo?"0":"1rem"),ri=No.borderRadius??jt,pc=ae&&tr?c(oi,{capture:ae,html:tr.html,messageToken:tr.messageToken,expectedOrigin:tr.expectedOrigin,theme:pt,submitLabel:M,onReady:()=>{if(!kt&&!J||typeof document>"u")return;let a=()=>{let O=(document.querySelector('[data-testid="flopay-vault-identity-fields"]')??document.querySelector('[data-testid="flopay-avs-fields"]'))?.querySelector("input:not([disabled]), select:not([disabled])");if(O){Rn.current=!0;try{O.focus()}finally{Rn.current=!1}}};er.current||a()},onError:a=>pe(a),onValidation:a=>{let P=Ce.current;(P==="idle"||P==="validation-window")&&(pe(a),a&&Ce.current==="validation-window"&&(B.current&&(clearTimeout(B.current),B.current=null),Ce.current="idle",f(null)))}}):c("div",{"data-testid":"flopay-vault-loading",style:{minHeight:120,display:"flex",alignItems:"center",justifyContent:"center",color:"#6b7280",fontSize:14},children:"Loading secure card form\u2026"}),Ms=Ue("div",{onFocusCapture:a=>{["INPUT","SELECT","TEXTAREA","IFRAME"].includes(a.target.tagName)&&dr()},style:{backgroundColor:Za,borderRadius:ri,...No,padding:ni,...uc,display:"flex",flexDirection:"column"},children:[c("style",{children:`
|
|
25
|
+
`,La=44,ta=180,kl=`flopay-card-enter ${ta}ms cubic-bezier(0, 0, 0.2, 1) both`,_l=`flopay-card-exit ${ta}ms cubic-bezier(0.4, 0, 0.2, 1) both`,tu=`flopay-buttons-enter ${ta}ms cubic-bezier(0, 0, 0.2, 1) both`,nu=`flopay-buttons-exit ${ta}ms cubic-bezier(0.4, 0, 0.2, 1) both`;function ru(e){return e.gateway==="stripe"?"stripe":e.gateway==="paypal"||e.isPaypal?"paypal":void 0}function Yi(e){if(!e.themeBundle&&!e.explicitPrimaryColor)return{backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:e.resolvedBorderRadius,boxShadow:"0 1px 2px rgba(0,0,0,0.04)"};let t=e.themeBundle?e.submitButtonStyle??{}:{};return{backgroundColor:e.resolvedPrimaryColor,color:t.color??"white",border:t.border??"none",borderRadius:t.borderRadius??e.resolvedBorderRadius,boxShadow:t.boxShadow}}var ou={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"};function au(e){return e.isPaypal||e.gateway==="paypal"||e.paymentMethodType==="paypal"?"paypal":e.paymentMethodType==="apple_pay"||e.paymentMethodType==="google_pay"?"wallet":e.paymentMethodType&&e.paymentMethodType!=="card"?"apm":"card"}var ji={width:"100%",minHeight:La,margin:"0 0 0.5rem",padding:"0.75rem 0.875rem",border:"1px solid #2563eb",borderRadius:8,background:"#eff6ff",color:"#1d4ed8",fontSize:"0.95rem",fontWeight:700,cursor:"pointer"};function iu(e){switch(e){case"paypal":return"PayPal";case"apple_pay":return"Apple Pay";case"google_pay":return"Google Pay";default:return"Card"}}function Rl(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function $i(e){return e==="paypal"?"PayPal":Jr(e)}function su(e,t){let n=`We couldn't open ${$i(e)}. Try again or choose another payment method.`;return t?`${n} Allow pop-ups for this site, then try again.`:n}function lu(e){let t=Ed(e);return`Enter a valid ${qi(e)}${t?` (e.g. ${t})`:""}`}function cu(e,t,n){let r=xd(e),o=t.trim(),i=n&&r,s=i&&!o,l=i&&!!o&&!Md(e,o);return{visible:n,supported:r,required:i,empty:s,malformed:l}}function du(e,t){let n=e.trim(),r=t&&!n,o=t&&!!n&&!cn(n);return{required:t,empty:r,malformed:o,value:n}}function El(e,t){return t instanceof dr?t:new dr(t instanceof Error?t.message:`${iu(e)} before-click hook failed.`,"validation_error")}function Ui(){return c("style",{children:eu})}function uu(e){return typeof e=="number"?`${e}px`:e}function Ol(e,t){let n=e.availablePaymentMethods;return n&&t.some(r=>n[r])?"ready":"unavailable"}function zl({state:e,placeholderTestId:t,borderRadius:n=8,children:r}){return e==="unavailable"||e==="load_error"?null:ze("div",{style:{position:"relative",minHeight:44},children:[c("div",{"data-testid":t,"aria-hidden":e==="ready",style:{position:"absolute",inset:0,height:44,borderRadius:n,background:"#e5e7eb",animation:e==="ready"?void 0:"flopay-pulse 1.5s ease-in-out infinite",opacity:e==="ready"?0:1,transform:e==="ready"?"scale(0.985)":"scale(1)",transition:"opacity 140ms ease-out, transform 140ms ease-out",pointerEvents:"none"}}),c("div",{style:{minHeight:44,opacity:e==="ready"?1:0,transform:e==="ready"?"translateY(0)":"translateY(2px)",transition:"opacity 140ms ease-out, transform 140ms ease-out",pointerEvents:e==="ready"?"auto":"none"},children:r})]})}function Tl(e){return e!=="unavailable"&&e!=="load_error"}function Ji(e){return c(mu,{...e})}function Al({sessionId:e,nonce:t,email:n,billingApiUrl:r,onTokenizedBody:o,onErrorChange:i,isProcessing:s=!1,onButtonClick:l,onDecline:p,onTechnicalFailure:f,runBeforeButtonClick:C,billingName:h,onBuyerIdentityReady:m,onLoadStateChange:w,placeholderBorderRadius:_}){let ae=Br(),{emitInstrument:Y}=Io(er),Pe=Hi(),S=Vi(),[G,X]=le("loading");gt(()=>{w?.(G)},[G,w]);let[ce,Te]=le(!1),Fe=!cn(n?.trim())||!h?.trim(),{request:ve,collect:Ue,finish:bt}=mo(),ot=me(!1),$e=me(null),De=me(null),[ye,we]=le(0),[Qe,Z]=le(!1),Ie=me(!1),be=me(new Map),{startAttempt:ct,finishAttempt:dt,invalidateAttempt:U,isAttemptInvalidated:V,isAttemptCurrent:de}=Wo((re,Q,L)=>{f?.(re,Q,{...L,popupBlocked:L?.popupBlocked??Ir(Q)}),Z(!0),we(Ae=>Ae+1)});gt(()=>{Qe&&De.current?.focus()},[Qe,ye]);let fe=Ze(()=>{we(re=>re+1)},[]),ut=Ze((re,Q,L)=>{U(L),f?.("paypal",re,{code:Q,popupBlocked:Ir(re)}),Z(!0),fe()},[U,f,fe]),Ne=Ze(()=>{window.setTimeout(()=>{($e.current?.querySelector("iframe")??$e.current)?.focus()},0)},[]);gt(()=>{Ie.current&&(Ie.current=!1,Ne())},[Ne,ye]);let x=Ze(()=>{Z(!1),i?.(null),Ne()},[Ne,i]);gt(()=>{if(!Pe||ot.current)return;let re=new URLSearchParams(window.location.search),Q=re.get("payment_intent"),L=re.get("payment_intent_client_secret"),Ae=re.get("redirect_status");if(!Q||!L)return;ot.current=!0;let xe;try{let qe=localStorage.getItem(ea);if(qe){let ke=JSON.parse(qe);ke.clientSecret===L&&(xe={...ke.accountPatch?{accountPatch:ke.accountPatch}:{},...ke.sessionId?{sessionId:ke.sessionId}:{},...ke.nonce?{nonce:ke.nonce}:{}})}}catch{}try{localStorage.removeItem(ea)}catch{}let Me=new URL(window.location.href);Me.searchParams.delete("payment_intent"),Me.searchParams.delete("payment_intent_client_secret"),Me.searchParams.delete("redirect_status"),window.history.replaceState({},"",Me.toString()),(async()=>{try{if(Te(!0),Ae==="failed"){let Ee="PayPal payment was declined. Please try again.";i?.(Ee),p?.(nn("paypal",Ee));return}let{paymentIntent:qe,error:ke}=await Pe.retrievePaymentIntent(L);if(ke){i?.(ke.message??"Failed to retrieve PayPal payment status.");return}if(qe&&(qe.status==="requires_capture"||qe.status==="succeeded")){let Ee=typeof qe.payment_method=="string"?qe.payment_method:qe.payment_method?.id;o({id:Ee??qe.id,type:"card",threeDSecureActionResultTokenId:qe.id,isPaypal:!0},xe)}else{let Ee="PayPal payment was not completed. Please try again.";i?.(Ee),p?.(nn("paypal",Ee))}}catch(qe){i?.(qe instanceof Error?qe.message:"Failed to complete PayPal payment.")}finally{Te(!1)}})()},[Pe,o,i,p]);let at=Ze(async re=>{if(s||ce){re.reject();return}let Q=C?await C("paypal"):{proceed:!0};if(!Q.proceed){be.current.delete(ye),re.reject();return}let L=ct("paypal");be.current.set(ye,{generation:L,accountPatch:Q.accountPatch,sessionId:Q.sessionId,nonce:Q.nonce}),Z(!1),l?.("paypal"),re.resolve()},[s,l,C,ct,ce,ye]),Ye=Ze(async re=>{if(!Pe||!S)return;let Q=be.current.get(ye);if(Q&&!de(Q.generation)){be.current.delete(ye);return}if(!Q&&V()||Q&&!dt(Q.generation))return;Q||dt();let L=Q??null;if(be.current.delete(ye),!L&&C){let Ee=await C("paypal");if(!Ee.proceed){re.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}L={accountPatch:Ee.accountPatch,sessionId:Ee.sessionId,nonce:Ee.nonce}}let Ae=L?.sessionId??e,xe=L?.nonce??t,Me=await Qd({event:re,prepared:L,email:n,billingName:h,methodLabel:"PayPal",collect:Ue});if(!Me){re.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let qe=Me.email,ke={...L?.accountPatch,...Bn(Me,!0)};try{if(Te(!0),i?.(null),!Ae||!cn(qe))throw new Error("Missing sessionId or email for PayPal payment");await m?.(Me);let Ee=Pe.createPaymentMethod,{error:ee,paymentMethod:dn}=await Ee({type:"paypal"});if(ee){ut(ee,"stripe_paypal_create_payment_method_failed",Q?.generation),re.paymentFailed({reason:"fail"});return}let Yt=await Oa(r,Y,Ae,xe??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:dn?.id??null,intentKind:"payment"});if(Yt.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let H=Yt.clientSecret,Je={return_url:window.location.href};if(dn?.id&&(Je.payment_method=dn.id),typeof window<"u")try{localStorage.setItem(ea,JSON.stringify({clientSecret:H,sessionId:Ae,nonce:xe,accountPatch:ke}))}catch{}let{error:$,paymentIntent:K}=await Pe.confirmPayment({clientSecret:H,confirmParams:Je,redirect:"if_required"});if($){if(typeof window<"u")try{localStorage.removeItem(ea)}catch{}if(Ho($)){let u=$.message??"Your payment was declined.";i?.(u),p?.(nn("paypal",u,{code:wr($),declineCode:fo($)})),await za({billingApiUrl:r,sessionId:Ae,nonce:xe,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:wr($)??"provider_declined"}})}else ut($,"stripe_paypal_confirm_failed",Q?.generation);return}if(typeof window<"u")try{localStorage.removeItem(ea)}catch{}let ie=typeof K?.payment_method=="string"?K.payment_method:K?.payment_method?.id;o({id:ie??K?.id,type:"card",threeDSecureActionResultTokenId:K?.id,isPaypal:!0},{accountPatch:ke,paymentMethodCategory:"paypal",sessionId:Ae,nonce:xe});return}catch(Ee){ut(Ee,"stripe_paypal_failed",Q?.generation)}finally{Te(!1)}},[Pe,S,e,t,n,h,Ue,m,r,Y,o,i,p,C,ut,dt,de,V,ye]);return ze(Yr,{children:[c(zl,{state:G,placeholderTestId:"flopay-paypal-placeholder",borderRadius:_,children:ze("div",{ref:$e,tabIndex:-1,"data-testid":"flopay-paypal-focus-target",role:"group","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[Qe&&c("button",{ref:De,type:"button","data-testid":"flopay-paypal-retry-button",onClick:x,style:ji,children:"Try PayPal again"}),ve&&c(yo,{identity:ve.identity,methodLabel:ve.methodLabel,onComplete:bt,onCancel:()=>bt(null)},ve.id),c("div",{style:{display:ve?"none":void 0},children:c(Bl,{onReady:re=>X(Ol(re,["paypal"])),onLoadError:()=>{X("load_error"),Gi(Qt(ae),"paypal","paypal")},onClick:at,onConfirm:Ye,onCancel:()=>{let re=be.current.get(ye);be.current.delete(ye),Qt(ae)?.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),U(re?.generation),Z(!1),Ie.current=!0,fe()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:Fe,emailRequired:Fe,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},ye)})]})}),ce&&c(fr,{status:"processing"})]})}function xl({sessionId:e,nonce:t,email:n,billingApiUrl:r,intentKind:o,expressMethods:i,onTokenizedBody:s,onErrorChange:l,onButtonClick:p,onDecline:f,onTechnicalFailure:C,runBeforeButtonClick:h,billingName:m,onBuyerIdentityReady:w,onLoadStateChange:_,placeholderBorderRadius:ae}){let Y=Br(),{emitInstrument:Pe}=Io(er),S=Hi(),G=Vi(),[X,ce]=le("loading");gt(()=>{_?.(X)},[X,_]);let[Te,Fe]=le(!1),ve=me(!cn(n?.trim())||!m?.trim()).current,{request:Ue,collect:bt,finish:ot}=mo(),$e=me(null),De=me(null),[ye,we]=le(0),[Qe,Z]=le(!1),[Ie,be]=le(()=>Na(e,t)?"blocked":"idle"),[ct,dt]=le("google_pay"),U=me(null),V=me(!0),de=me(!1),fe=me("google_pay"),ut=me("google_pay"),Ne=me(null),x=me(null),at=me(new Set);gt(()=>(V.current=!0,()=>{V.current=!1;for(let $ of at.current)window.clearTimeout($);at.current.clear()}),[]);let Ye=me(new Map),{startAttempt:re,finishAttempt:Q,invalidateAttempt:L,isAttemptInvalidated:Ae,isAttemptCurrent:xe,generationRef:Me}=Wo(($,K,ie)=>{C?.($,K,{...ie,popupBlocked:ie?.popupBlocked??Ir(K)}),dt($),Z(!0),we(u=>u+1)});gt(()=>{Qe&&De.current?.focus()},[Qe,ye]);let qe=Ze(()=>{we($=>$+1)},[]),ke=Ze(($,K,ie,u)=>{L(u),C?.($,K,{code:ie,popupBlocked:Ir(K)}),dt($),Z(!0),qe()},[L,C,qe]),Ee=Ze(()=>{window.setTimeout(()=>{($e.current?.querySelector("iframe")??$e.current)?.focus()},0)},[]);gt(()=>{de.current&&(de.current=!1,Ee())},[Ee,ye]);let ee=Ze(()=>{Z(!1),l?.(null),Ee()},[Ee,l]),dn=Ze(()=>{U.current?.()},[]);gt(()=>{let $=Na(e,t);if(!$)return;let K=!1,ie=!1,u=async()=>{if(!ie){ie=!0,K||be("checking");try{let B=await wl(S,$.clientSecret,at.current);if(K)return;let _e=Oi(B,$.providerObjectId,Fi($.clientSecret));if(_e.kind==="confirmed"){if(!Sl(e,t,$.clientSecret))return;U.current=null,be("idle"),s({id:_e.paymentMethodId,type:"card",threeDSecureActionResultTokenId:_e.intentId},{...$.accountPatch?{accountPatch:$.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t});return}if(_e.kind==="terminal"){Li(e,t,$.clientSecret),U.current=null,be("idle"),dt($.paymentMethodType),Z(!0),qe();return}be("blocked")}catch{K||be("blocked")}finally{ie=!1}}};return U.current=u,be("blocked"),()=>{K=!0,U.current===u&&(U.current=null)}},[t,s,qe,e,S]);let Yt=Ze(async $=>{let K=!1,ie=je=>{K||(K=!0,$.paymentFailed({reason:"fail",...je?{message:je}:{}}))};if(!S||!G){ie();return}let u=Ye.current.get(ye);if(u&&!xe(u.generation)){Ye.current.delete(ye),ie();return}if(!u&&Ae()){ie();return}if(u&&!Q(u.generation)){ie();return}u||Q();let B=$.expressPaymentType??u?.method??fe.current,_e=u??null,Ke=Rl(B),Re;B==="apple_pay"?Re="apple_pay":B==="google_pay"&&(Re="google_pay");let $t=u?.generation??Me.current,N=Qt(Y),Ct=N?.now()??globalThis.performance?.now()??Date.now(),Et=new AbortController,pt=!1,un=!1,O=null,Ot=e,Cn="processing",pn="other",mn="provider_runtime",_n,Fn=new Promise((je,He)=>{_n=He}),Dn=window.setTimeout(()=>{pt=!0,Et.abort(),_n(Di)},Kd),Jt=async(je,He,St)=>{Cn=je,pn=He,mn=He==="intent_create"||He==="session_claim"?"transport_error":"provider_runtime";let rn=N?.now()??globalThis.performance?.now()??Date.now();try{return await Promise.race([St,Fn])}finally{let wt=N?.now()??globalThis.performance?.now()??Date.now();N?.performance({stage:je,durationMs:Math.max(0,wt-rn),durationMode:"machine",requestCategory:He,paymentMethodCategory:"wallet",provider:"stripe",...pt?{statusClass:"timeout"}:{}})}};try{if(Fe(!0),l?.(null),!_e&&h){let se=await Jt("processing","other",h(Ke));if(!se.proceed){ie();return}_e={accountPatch:se.accountPatch,sessionId:se.sessionId,nonce:se.nonce}}let je=_e?.sessionId??e;Ot=je;let He=_e?.nonce??t,St=Ne.current??_e?.accountPatch,rn=Ll({event:$,fallbackEmail:St?.email??n,fallbackName:[St?.firstName,St?.lastName].join(" ").trim()||m});if(!cn(rn.email)){ie("Buyer details are required."),bt($i(B),rn).then(se=>{se&&(Ne.current=se)});return}Ne.current=null;let wt={..._e?.accountPatch,...Bn(rn,!0)};await Jt("processing","session_claim",Promise.resolve(w?.(rn)));let{error:$n}=await Jt("tokenization","provider_sdk",G.submit());if($n){ie(),ke(B,$n,"stripe_wallet_submit_failed",u?.generation);return}if(!je)throw new Error("Missing sessionId or email for payment.");let mt={provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:B,paymentMethodId:null,intentKind:o},Tt=JSON.stringify({sessionId:je,nonce:He??"",request:mt}),zt=x.current,yn=zt?.retryIdentity===Tt?zt.authorizationAttemptId:Dd();x.current={authorizationAttemptId:yn,retryIdentity:Tt};let Ut=await Jt("processing","intent_create",Oa(r,Pe,je,He??"",{...mt,authorizationAttemptId:yn},{signal:Et.signal}));if(Ut.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let At=Ut.clientSecret,Sn=Wd({createdAt:Date.now(),sessionId:je,...He?{nonce:He}:{},clientSecret:At,providerObjectId:Ut.providerObjectId,paymentMethodType:B,accountPatch:wt});window.clearTimeout(Dn),un=!0,N?.performance({stage:"callback",durationMs:Math.max(0,(N?.now()??globalThis.performance?.now()??Date.now())-Ct),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe"});let wn=N?.now()??globalThis.performance?.now()??Date.now(),It={stage:"provider_confirmation",provider:"stripe",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",...Re?{walletType:Re}:{},attempt:$t},te=!1,on=null;N?.log({name:"payment.provider_confirmation.started",...It}),O=window.setTimeout(()=>{O!==null&&at.current.delete(O),te=!0;let se=N?.now()??globalThis.performance?.now()??Date.now();N?.error({errorCode:"PROVIDER_RUNTIME_FAILED",...It,operationOutcome:"watchdog_expired",durationMs:Math.max(0,se-wn),statusClass:"timeout",failureCategory:"provider_runtime"}),N?.flush?.().catch(()=>{}),on?.()},Vd),at.current.add(O);let Kn=se=>{O!==null&&(window.clearTimeout(O),at.current.delete(O),O=null);let M=N?.now()??globalThis.performance?.now()??Date.now(),Oe=Math.max(0,M-wn),D=se;return te&&(se==="resolved"?D="resolved_late":se==="returned_error"?D="returned_error_late":D="rejected_late"),N?.log({name:"payment.provider_confirmation.returned",...It,operationOutcome:D}),N?.performance({...It,durationMs:Oe,durationMode:"buyer",operationOutcome:D}),{durationMs:Oe,operationOutcome:D}},Ht=!1,Kt=!1,an=se=>{if(!se||typeof se!="object")return null;let M=se;if(M.error)return null;let Oe=M.setupIntent??M.paymentIntent,D=Oi(Oe??null,void 0,!!M.setupIntent);return D.kind==="confirmed"?D:null},nr=se=>{if(Ht||u&&Me.current!==u.generation)return;let M=an(se);if(!M)return;if(Sn&&!Sl(je,He,At)){Ht=!0;return}let{intentId:Oe,paymentMethodId:D}=M;Ht=!0,Kt=!0,x.current=null,U.current=null,V.current&&(be("idle"),Fe(!1));let kt=`${Fl}:${je}`;if(typeof window<"u")try{localStorage.setItem(kt,JSON.stringify({createdAt:Date.now(),sessionId:je,nonce:He,accountPatch:wt,paymentMethodId:D,providerIntentId:Oe,paymentMethodType:B}))}catch{}try{s({id:D,type:"card",threeDSecureActionResultTokenId:Oe},{accountPatch:wt,paymentMethodCategory:"wallet",sessionId:je,nonce:He})}finally{if(typeof window<"u")try{localStorage.removeItem(kt)}catch{}}},Nn=!1;on=async()=>{if(!(Nn||Ht||Kt)){Nn=!0,V.current&&be("checking");try{let se=await wl(S,At,at.current);if(Ht||Kt)return;let M=Fi(At),Oe=Oi(se,Ut.providerObjectId,M);if(Oe.kind==="confirmed"){nr(M?{setupIntent:se}:{paymentIntent:se});return}if(Oe.kind==="terminal"){if(Kt=!0,Li(je,He,At),x.current=null,U.current=null,!V.current)return;be("idle"),ie(),ke(B,new Error("Wallet confirmation did not complete."),"stripe_wallet_confirmation_terminal",u?.generation);return}V.current&&!Kt&&(be("blocked"),Fe(!1))}catch{V.current&&!Kt&&(be("blocked"),Fe(!1))}finally{Nn=!1}}},U.current=on;let Wt,Le;try{let se=await(Fi(At)?S.confirmSetup({elements:G,clientSecret:At,redirect:"if_required"}):S.confirmPayment({elements:G,clientSecret:At,redirect:"if_required"}));if(!se||typeof se!="object"||(Wt=se,!Wt.error&&!an(Wt)))throw Ni;Le=Kn(Wt.error?"returned_error":"resolved")}catch(se){let M=se===Ni,Oe=Kn(M?"returned_error":"rejected");if(N?.error({...M?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response"}:pi(se),...It,operationOutcome:Oe.operationOutcome,durationMs:Oe.durationMs,statusClass:"unknown"}),!V.current||Ht)return;await on?.();return}let fn=Wt.error;if(fn){if(!V.current||Ht)return;if(Ho(fn)){Kt=!0,Li(je,He,At),x.current=null,U.current=null,be("idle");let se=fn.message??"Your payment was declined.";ie(se),l?.(se),f?.(nn(Ke,se,{code:wr(fn),declineCode:fo(fn)})),za({billingApiUrl:r,sessionId:je,nonce:He,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:B,providerDeclineReason:wr(fn)??"provider_declined",...Ut.intentKind==="payment"&&Ut.providerObjectId.startsWith("pi_")?{providerIntentId:Ut.providerObjectId}:{}}})}else N?.error({...pi(fn),...It,operationOutcome:Le.operationOutcome,durationMs:Le.durationMs,statusClass:"unknown"}),await on?.();return}if(nr(Wt),!Ht)throw new Error("Invalid provider returned for APM intent")}catch(je){if(je===Di){let He=N?.now()??globalThis.performance?.now()??Date.now();N?.error({errorCode:Yd(pn),stage:Cn,requestCategory:pn,paymentMethodCategory:"wallet",provider:"stripe",...Re?{walletType:Re}:{},operationOutcome:"watchdog_expired",checkoutSessionId:Ot,durationMs:Math.max(0,He-Ct),statusClass:"timeout",failureCategory:mn,attempt:$t}),N?.flush?.().catch(()=>{})}ie(),ke(B,je,je===Di?"stripe_wallet_authorization_timeout":"stripe_wallet_failed",u?.generation)}finally{if(window.clearTimeout(Dn),O!==null&&(window.clearTimeout(O),at.current.delete(O)),!un){let je=N?.now()??globalThis.performance?.now()??Date.now();N?.performance({stage:"callback",durationMs:Math.max(0,je-Ct),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe",...pt?{statusClass:"timeout"}:{}})}V.current&&Fe(!1)}},[S,G,e,t,n,m,bt,w,r,Pe,o,s,l,f,h,ke,Q,xe,Ae,Me,Y,ye]),H=Ft(()=>{let $=["applePay","googlePay","paypal","link","amazonPay","klarna"],K=new Set(["applePay","googlePay"]),ie=new Set(i.map(bl)),u={};for(let B of $)ie.has(B)?u[B]=K.has(B)?"always":"auto":u[B]="never";return u},[i]),Je=Ft(()=>i.map(bl),[i]);return ze(Yr,{children:[c(zl,{state:X,placeholderTestId:"flopay-wallet-placeholder",borderRadius:ae,children:ze("div",{ref:$e,tabIndex:-1,"data-testid":"flopay-wallet-focus-target",role:"group","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[Qe&&ze("button",{ref:De,type:"button","data-testid":"flopay-wallet-retry-button",onClick:ee,style:ji,children:["Try ",$i(ct)," again"]}),Ie!=="idle"&&ze("div",{role:"status","aria-live":"polite",children:[c("p",{children:"We are still confirming your payment. Check its status before trying again."}),c("button",{type:"button",onClick:dn,disabled:Ie==="checking",style:ji,children:Ie==="checking"?"Checking payment status\u2026":"Check payment status"})]}),Ue&&c(yo,{identity:Ue.identity,methodLabel:Ue.methodLabel,onComplete:ot,onCancel:()=>ot(null)},Ue.id),Ie==="idle"&&c("div",{style:{display:Ue?"none":void 0},children:c(Bl,{onReady:$=>{ce(Ol($,Je))},onLoadError:$=>{ce("load_error"),Gi(Qt(Y),"stripe","wallet")},onClick:async $=>{fe.current=$.expressPaymentType,ut.current=Rl($.expressPaymentType);let K=!0,ie=window.setTimeout(()=>{K=!1,$.reject()},$d),u=h?await h(ut.current):{proceed:!0};if(window.clearTimeout(ie),!K)return;if(!u.proceed){Ye.current.delete(ye),$.reject();return}let B=re($.expressPaymentType);Ye.current.set(ye,{generation:B,method:$.expressPaymentType,accountPatch:u.accountPatch,sessionId:u.sessionId,nonce:u.nonce}),Z(!1),p?.(ut.current),$.resolve()},onConfirm:Yt,onCancel:()=>{let $=Ye.current.get(ye);Ye.current.delete(ye),Qt(Y)?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet"}),L($?.generation),x.current=null,Z(!1),de.current=!0,qe()},options:{buttonType:{applePay:"plain",googlePay:"plain"},paymentMethods:H,emailRequired:ve,billingAddressRequired:ve,layout:{maxColumns:1,overflow:"never"}}},ye)})]})}),Te&&c(fr,{status:"processing"})]})}function Ul(e,t){return{...e,paymentMethodTypes:[t],...t==="revolut_pay"||t==="sepa_debit"||t==="us_bank_account"?{setupFutureUsage:"off_session"}:null}}function pu({method:e,themeId:t,submitting:n=!1,disabled:r=!1,highlighted:o=!1,hasNextStep:i=!1,onClick:s,backgroundColor:l,borderColor:p,textColor:f,borderRadius:C,fontFamily:h}){let m=Od(e,t),w=hl[e],[_,ae]=le(!1),Y=!!w&&!_,Pe=m?.backgroundColor??l??"#ffffff",S=m?.borderColor??p??"#d1d5db",G=m?.textColor??f??"#262833";return c("button",{type:"button","data-testid":`flopay-stripe-method-button-${e}`,"data-method":e,onClick:()=>{!n&&!r&&s()},disabled:n||r,"aria-busy":n||void 0,style:{position:"relative",width:"100%",boxSizing:"border-box",height:La,padding:"0 1rem",backgroundColor:Pe,color:G,border:`1px solid ${S}`,borderRadius:C??8,fontSize:"0.95rem",fontWeight:600,fontFamily:h,cursor:n||r?"not-allowed":"pointer",opacity:r&&!n?.55:1,animation:n?"flopay-pulse 1.5s ease-in-out infinite":void 0,display:"flex",alignItems:"center",justifyContent:"center",gap:8,transition:"transform 0.1s, opacity 140ms ease-out, border-color 140ms ease-out",boxShadow:o?"0 0 0 2px rgba(74, 73, 255, 0.15)":void 0},children:n?c("span",{style:{margin:"0 auto"},children:`Connecting to ${Jr(e)}\u2026`}):ze(Yr,{children:[ze("span",{style:{display:"inline-flex",alignItems:"center",gap:Ad(e)?8:0},children:[Y?c("img",{src:w,alt:"","aria-hidden":"true",onError:()=>ae(!0),loading:"lazy",decoding:"async",width:30,height:20,style:{width:30,height:20,flexShrink:0,borderRadius:3,objectFit:"contain",display:"inline-flex"}}):null,!Y&&m?.logoSvg?c("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:m.logoSvg}}):null,c("span",{children:Jr(e)})]}),i&&c("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:G,strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{position:"absolute",right:"1rem",top:"50%",transform:"translateY(-50%)",flexShrink:0,opacity:.7},"aria-hidden":"true",children:c("path",{d:"M9 18l6-6-6-6"})})]})})}function Ki({method:e,sessionId:t,nonce:n,email:r,billingName:o,onBuyerIdentityReady:i,billingApiUrl:s,onTokenizedBody:l,onErrorChange:p,onDecline:f,onCancel:C,runBeforeButtonClick:h,onButtonClick:m,isProcessing:w,submitButtonColor:_,submitButtonBorderRadius:ae,submitButtonStyle:Y,errorText:Pe}){let S=Br(),{emitInstrument:G}=Io(er),X=Hi(),ce=Vi(),[Te,Fe]=le(!1),ve=me(!1),[Ue,bt]=le(!1),[ot,$e]=le("loading"),[De,ye]=le(""),we=!cn(r?.trim()),Qe=!we||cn(De.trim()),Z=Ze(async()=>{if(!X||!ce||w||ve.current||!Ue)return;ve.current=!0,Fe(!0);let Ie=h?await h("card"):{proceed:!0};if(!Ie.proceed){ve.current=!1,Fe(!1);return}m?.("card");let be=Ie.sessionId??t,ct=Ie.nonce??n,dt=Vr(o?.trim()),U=Bn({email:Ie.accountPatch?.email?.trim()||r?.trim()||De.trim(),firstName:Ie.accountPatch?.firstName?.trim()||dt.firstName,lastName:Ie.accountPatch?.lastName?.trim()||dt.lastName}),V=U.email,de=Bn({...Ie.accountPatch,...U});try{if(p?.(null),!cn(V))throw new Error("A valid email address is required for payment.");await i?.(U);let fe=await ce.submit();if(fe.error){p?.(fe.error.message??"Payment failed.");return}let ut=[U.firstName,U.lastName].filter(Boolean).join(" "),Ne=await X.createPaymentMethod({elements:ce,params:{billing_details:{email:V,...ut?{name:ut}:{}}}});if(Ne.error||!Ne.paymentMethod){p?.(Ne.error?.message??"Failed to create payment method.");return}let x=Ne.paymentMethod;if(!be||!V)throw new Error("Missing sessionId or email for payment.");let at=x.type||e,Ye=await Oa(s,G,be,ct??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:at,paymentMethodId:null,intentKind:"payment"});if(Ye.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let re=Ye.clientSecret;if(typeof window<"u")try{localStorage.setItem(hr,JSON.stringify({clientSecret:re,sessionId:be,nonce:ct,accountPatch:de,paymentMethodId:x.id,paymentMethodType:x.type??e,gateway:"stripe"}))}catch{}let{error:Q,paymentIntent:L}=await X.confirmPayment({clientSecret:re,confirmParams:{return_url:window.location.href,payment_method:x.id},redirect:"if_required"});if(Q){if(typeof window<"u")try{localStorage.removeItem(hr)}catch{}let Me=Q.message??"Payment failed.";p?.(Me),f?.(nn("card",Me,{code:Q.code})),await za({billingApiUrl:s,sessionId:be,nonce:ct,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:Q.code??"provider_declined"}});return}let Ae=L?.status;if(!$o(Ae)){if(typeof window<"u")try{localStorage.removeItem(hr)}catch{}let Me=Ae==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";p?.(Me),f?.(nn("card",Me,{code:Ae??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(hr)}catch{}let xe=typeof L?.payment_method=="string"?L.payment_method:L?.payment_method?.id;l({id:xe??x.id,type:"card",threeDSecureActionResultTokenId:L?.id,gateway:"stripe",paymentMethodType:x.type??e},{accountPatch:de,paymentMethodCategory:"apm",sessionId:be,nonce:ct})}catch(fe){p?.(fe instanceof Error?fe.message:"Payment failed. Please try again.")}finally{ve.current=!1,Fe(!1)}},[X,ce,w,Ue,h,m,t,n,r,o,De,i,s,G,e,l,p,f]);return ze("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[we&&c("div",{"data-testid":"flopay-apm-identity-fields",style:{display:"flex",flexDirection:"column",gap:"0.75rem",marginBottom:"0.75rem"},children:we&&ze("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",c("input",{type:"email",autoComplete:"email",required:!0,value:De,onChange:Ie=>ye(Ie.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]})}),c(Ud,{onReady:()=>$e("ready"),onLoadError:()=>{$e("load_error"),Gi(Qt(S),"stripe","apm")},onChange:Ie=>{bt(!!Ie.complete)},options:{layout:{type:"accordion",defaultCollapsed:!1,radios:"never"},fields:{billingDetails:{email:"never"}},defaultValues:{billingDetails:{...o?.trim()?{name:o.trim()}:{},...cn(r?.trim())?{email:r?.trim()}:{}}}}}),c("button",{type:"button","data-testid":`flopay-stripe-method-pay-${e}`,onClick:()=>{Z()},disabled:!Ue||!Qe||Te||w||ot!=="ready",style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:_,color:"white",border:"none",borderRadius:ae,fontSize:"1rem",fontWeight:600,cursor:!Ue||!Qe||Te||w||ot!=="ready"?"not-allowed":"pointer",opacity:!Ue||!Qe||Te||w||ot!=="ready"?.5:1,transition:"opacity 120ms ease-out",...Y??{}},children:Te?"Processing\u2026":`Pay with ${Jr(e)}`}),Pe&&c(ho,{margin:"0.75rem 0 0",children:Pe})]})}function Ml({sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:i,paymentElementMethods:s,stripeInstance:l,paymentElementBaseOptions:p,onTokenizedBody:f,onErrorChange:C,onButtonClick:h,onDecline:m,runBeforeButtonClick:w,onLoadStateChange:_,isProcessing:ae=!1,submitButtonColor:Y="#4A49FF",submitButtonBorderRadius:Pe=8,submitButtonStyle:S,buttonAppearance:G,themeId:X,onExpandApm:ce,expandedApmMethod:Te}){let{emitInstrument:Fe}=Io(er),[ve,Ue]=le(null),[bt,ot]=le(null),$e=me(!1),{request:De,collect:ye,finish:we}=mo();gt(()=>{s.length>0&&l?_?.("ready"):l||_?.("loading")},[s.length,l,_]);let Qe=Ze(async U=>{if(!l||$e.current||ae)return;$e.current=!0,ot(U);let V=w?await w("card"):{proceed:!0};if(!V.proceed){$e.current=!1,ot(null);return}h?.("card");let de=V.sessionId??e,fe=V.nonce??t,ut=Vr([V.accountPatch?.firstName,V.accountPatch?.lastName].filter(Boolean).join(" ")||r),Ne=Bn({email:V.accountPatch?.email?.trim()||n?.trim(),firstName:V.accountPatch?.firstName?.trim()||ut.firstName,lastName:V.accountPatch?.lastName?.trim()||ut.lastName});if(!cn(Ne.email)){ot(null);let Ye=await ye(Jr(U),Ne);if(!Ye){$e.current=!1;return}Ne=Ye,ot(U)}let x=Ne.email,at=Bn({...V.accountPatch,...Ne});try{if(C?.(null),!de||!cn(x))throw new Error("Missing sessionId or email for payment.");await o?.(Ne);let Ye=await Oa(i,Fe,de,fe??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:U,paymentMethodId:null,intentKind:"payment"});if(Ye.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let re=Ye.clientSecret;if(typeof window<"u")try{localStorage.setItem(hr,JSON.stringify({clientSecret:re,sessionId:de,nonce:fe,accountPatch:at,paymentMethodType:U,gateway:"stripe"}))}catch{}let{error:Q,paymentIntent:L}=await l.confirmPayment({clientSecret:re,confirmParams:{return_url:window.location.href,payment_method_data:{type:U,billing_details:{name:[Ne.firstName,Ne.lastName].filter(Boolean).join(" "),...x?{email:x}:{}}}},redirect:"if_required"});if(Q){if(typeof window<"u")try{localStorage.removeItem(hr)}catch{}let Me=Q.message??"Payment failed.";C?.(Me),m?.(nn("card",Me,{code:Q.code})),await za({billingApiUrl:i,sessionId:de,nonce:fe,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:U,providerDeclineReason:Q.code??"provider_declined"}});return}let Ae=L?.status;if(!$o(Ae)){if(typeof window<"u")try{localStorage.removeItem(hr)}catch{}let Me=Ae==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";C?.(Me),m?.(nn("card",Me,{code:Ae??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(hr)}catch{}let xe=typeof L?.payment_method=="string"?L.payment_method:L?.payment_method?.id;f({id:xe??L?.id,type:"card",threeDSecureActionResultTokenId:L?.id,gateway:"stripe",paymentMethodType:U},{accountPatch:at,paymentMethodCategory:"apm",sessionId:de,nonce:fe})}catch(Ye){C?.(Ye instanceof Error?Ye.message:"Payment failed. Please try again.")}finally{$e.current=!1,ot(null)}},[l,ae,w,h,e,t,n,ye,i,Fe,r,o,f,C,m]),[Z,Ie]=le(null),be=ce?Te??null:Z,ct=Ze(U=>{$e.current||ae||be&&be!==U||(Pl(U)?ce?ce(U):Ie(U):Qe(U))},[be,ae,Qe,ce]),dt=Ft(()=>Z?Ul(p,Z):null,[Z,p]);return c("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:De?c(yo,{identity:De.identity,methodLabel:De.methodLabel,onComplete:we,onCancel:()=>we(null)},De.id):s.map(U=>{let V=Te===U,de=bt===U,fe=bt!==null&&bt!==U||Te!=null&&Te!==U;return ze(qd.Fragment,{children:[c(pu,{method:U,themeId:X,submitting:de,disabled:fe,highlighted:V,hasNextStep:Pl(U),onClick:()=>ct(U),backgroundColor:G?.backgroundColor,borderColor:G?.borderColor,textColor:G?.textColor,borderRadius:G?.borderRadius,fontFamily:G?.fontFamily}),!ce&&Z===U&&dt&&l&&c(Gr,{stripe:l,options:dt,children:c(Ki,{method:U,sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:i,onTokenizedBody:f,onErrorChange:C,onDecline:m,onCancel:()=>Ie(null),runBeforeButtonClick:w,onButtonClick:h,isProcessing:ae,submitButtonColor:Y,submitButtonBorderRadius:Pe,submitButtonStyle:S})},U)]},U)})})}function mu({sessionId:e,nonce:t,billingApiUrl:n,telemetry:r,email:o,userId:i,onComplete:s,onError:l,onDecline:p,onTokenizedBody:f,firstName:C,lastName:h,chv:m,className:w,submitLabel:_,isProcessing:ae,error:Y,onErrorChange:Pe,showPayPal:S=!0,showStripe:G=!0,enabledPaymentMethods:X,enabledPaymentMethodCountries:ce,showApplePay:Te=!0,showGooglePay:Fe=!0,layout:ve="default",theme:Ue,buttonsTheme:bt,buttonsStyles:ot,appearance:$e,cardButtonContent:De,cardBackButtonContent:ye,cardTitleContent:we,showSecurityFooter:Qe,onButtonClick:Z,onBeforeButtonClick:Ie,onBuyerIdentityReady:be,enableAVS:ct,cardFieldOrder:dt,cardPreFormSlot:U,avsLayout:V="row",country:de,zip:fe,addressLine1:ut,addressLine2:Ne,city:x,state:at,onCountryChange:Ye,onZipChange:re,avsCheck:Q,checkoutType:L,checkoutLayout:Ae,totalAmount:xe=0,currency:Me="usd",initialCardOpen:qe=!1,directPaypal:ke,isSubscription:Ee=!1,session:ee,dataAttachmentPending:dn=!1,dataAttachmentRequiresIdentity:Yt=!1,debug:H=!1}){let Je=Br(),$=mi(),K=Io(cr),{emitInstrument:ie}=Io(er),u=ee??K.session,B=u?.gateways?.paypal?.providerObjectType??ke?.providerObjectType,_e=dn||K.claimPending===!0,Ke=Yt||K.claimRequiresIdentity===!0,Re=_e&&!Ke,$t=rl(),N=n||$t,[Ct,Et]=le(!1),[pt,un]=le(null),[O,Ot]=le(de??"US"),[Cn,pn]=le(fe??""),[mn,_n]=le(ut??""),[Fn,Dn]=le(Ne??""),[Jt,je]=le(x??""),[He,St]=le(at??""),[rn,wt]=le(""),[$n,mt]=le({}),Tt=me(fe??""),zt=me(de??"US"),yn=me(ut??""),Ut=me(Ne??""),At=me(x??""),Sn=me(at??""),wn=me(""),It=me({});gt(()=>{let a=(b,j,Be,W,st)=>{if(It.current[b])return;let tt=j?.trim();!tt||tt===Be.current||(Be.current=tt,W(tt),st?.(tt))};a("country",de,zt,Ot,Ye),a("zip",fe,Tt,pn,re),a("addressLine1",ut,yn,_n),a("addressLine2",Ne,Ut,Dn),a("city",x,At,je),a("state",at,Sn,St)},[de,fe,ut,Ne,x,at,Ye,re]);let te=Ft(()=>Nd(ct),[ct]),on=te!==null,Kn=Ft(()=>Bi(ee),[ee]),Ht=!!ee?.vault?.html,Kt=!!ee?.gateways?.pcivault,an=ci(ee),Nn=!!(ee?.gateways?.stripe?.enabledPaymentMethods??X)?.includes("card")||Ar(ee),Wt=Ht||Nn||Kt,Le=!!(G&&Wt&&e),[fn,se]=le(()=>ve!=="buttons"||qe?e??null:null),[M,Oe]=le(0),D=ve!=="buttons"||qe||!!e&&fn===e,kt=ee?.captureMethod,xt=me(Je);gt(()=>{xt.current=Je},[Je]);let[Gt,Vn]=le(null);gt(()=>{if(!Le||!e||!D){Vn(null);return}let a=xt.current?xt.current.cardCapture({sessionId:e,captureMethod:kt}):new wd({sessionId:e,captureMethod:kt,billingApiUrl:N,telemetry:r});return Vn({sessionId:e,captureMethod:kt,billingApiUrl:N,telemetry:r,capture:a}),()=>{a.unmount()}},[Le,e,D,kt,N,r]);let ge=Le&&e&&D&&Gt?.sessionId===e&&Gt.captureMethod===kt&&Gt.billingApiUrl===N&&Gt.telemetry===r?Gt.capture:null,sn=Ft(()=>{let a=O,b=te?rt(te.postal_code,a):!1;return cu(a,Cn,b)},[te,O,Cn]),{avsInvalid:Hn,invalidAvsFields:Pr}=Ft(()=>{let a={line1:!1,city:!1,state:!1,zip:!1};if(!Le||!te)return{avsInvalid:!1,invalidAvsFields:a};let b=O,j=(st,tt)=>rt(st,b)&&!tt.trim(),Be={line1:j(te.address_line_1,mn),city:j(te.city,Jt),state:j(te.state,He),zip:sn.empty||sn.malformed};return{avsInvalid:Be.line1||Be.city||Be.state||Be.zip,invalidAvsFields:Be}},[Le,te,O,mn,Jt,He,sn]),[rr,zr]=le(!1),[Ur,or]=le(!1),[Er,Rn]=le(!1),[ar,Dt]=le({line1:!1,city:!1,state:!1}),Ln=me(!1),Wn=me({email:!1,line1:!1,city:!1,state:!1,zip:!1}),Gn=me(!1),yt=Ze(a=>{Wn.current[a]=!0,Gn.current=!0},[]),En=Ze(a=>!Ln.current&&Wn.current[a],[]),Yn=Ze(a=>{En(a)&&Dt(b=>b[a]?b:{...b,[a]:!0})},[En]),[ir,gn]=le(()=>zi(ee?.vault)),[We,hn]=le(qe&&Wt?"card":"buttons"),[ln,On]=le(null),br=We==="expanding"||We==="card",qr=ee?.gateways?.stripe&&!an?"stripe":void 0,Cr=Ze(()=>{ie?.({class:"card_surface",provider:qr})},[qr,ie]),zn=me(null),vn=Ze(a=>{zn.current&&clearTimeout(zn.current),zn.current=setTimeout(()=>{zn.current=null,a()},ta)},[]);gt(()=>()=>{zn.current&&clearTimeout(zn.current)},[]);let Xr=Ze(()=>{Cr(),se(e??null),Oe(a=>a+1),hn("expanding"),vn(()=>hn("card"))},[vn,Cr,e]),Tn=Ze(()=>{hn("collapsing"),vn(()=>hn("buttons"))},[vn]),Tr=Ze(a=>{On(a),hn("apm-expanding"),vn(()=>hn("apm-form"))},[vn]),In=Ze(()=>{hn("apm-collapsing"),vn(()=>{hn("buttons"),On(null)})},[vn]);gt(()=>{ve==="buttons"&&qe&&Wt&&(se(e??null),hn("card"))},[ve,qe,Wt,e]);let[Un,et]=le(null),Jn=me(!1),Xt=me(null),_t=me("idle"),[T,E]=le(!1),F=me(T);F.current=T;let[z,it]=le(()=>ke?.existingOrderId?{orderId:ke.existingOrderId,attempts:1}:null),R=me(z);gt(()=>{R.current=z},[z]);let d=me(null),A=Ft(()=>{if(be||K.claimBuyerIdentity||ee?.buyerIdentified!==!1||!e||!t)return;let a=`${N}|${e}|${t}`;d.current?.key!==a&&(d.current={key:a,claim:uo(new wo(N,{telemetry:!1}),e,t,{...i?{userId:i}:{},...C?{firstName:C}:{},...h?{lastName:h}:{}})});let b=d.current.claim;return async j=>{await b(j)}},[be,K.claimBuyerIdentity,ee?.buyerIdentified,e,t,N,i,C,h]),g=be??K.claimBuyerIdentity??A,P=Y??pt,I=Ft(()=>zd(Ue),[Ue]),v=Ft(()=>{let a=I?.buttonsLayout??Ld(bt);return ot?{...a,...ot,cardButton:{...a.cardButton,...ot.cardButton},cardFormContainer:{...a.cardFormContainer,...ot.cardFormContainer},backButton:{...a.backButton,...ot.backButton},backButtonIcon:{...a.backButtonIcon,...ot.backButtonIcon},submitButton:{...a.submitButton,...ot.submitButton},title:{...a.title,...ot.title}}:a},[I,bt,ot]),q=$e??I?.appearance,Ve=Ft(()=>Us({appearance:q,buttonsStyles:v,layout:ve}),[q,v,ve]),Nt=K.inlineSessionPatchProcessing??!1,Ce=(ae??Ct)||Nt,ne=N.replace(/\/+$/,""),y=Ft(()=>ui({userId:i,email:o,firstName:C,lastName:h,country:de,zip:fe},$n),[i,o,C,h,de,fe,$n]),k=[y.firstName,y.lastName].filter(a=>!!a?.trim()).join(" "),J=!cn(y.email?.trim()),ue=me(null);Le&&ue.current===null&&(ue.current=J);let Se=Le&&(ue.current??J),pe=Ft(()=>du(rn,Se),[rn,Se]),Ge=pe.empty||pe.malformed,ht=Ft(()=>Je?Je.getRawProvider():null,[Je]),tn=Ft(()=>$?$.getRawProvider():null,[$]),qn=xe||100,Zr=Me.toLowerCase(),Ka=Ft(()=>q?Id(q):null,[q]),Qr=Ka,ss=Ft(()=>{let a=Ka??{},b=a.rules??{};return{...a,rules:{...b,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...b[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...b[".AccordionItemContents"]??{}}}}},[Ka]),ls=Ft(()=>({...Xs(xe,ee?.captureMethod),currency:Zr,...Qr?{appearance:Qr}:null}),[xe,Zr,ee?.captureMethod,Qr]),cs=Ft(()=>({mode:"payment",amount:qn,currency:Zr,captureMethod:"manual",setupFutureUsage:"off_session",...Qr?{appearance:Qr}:null}),[qn,Zr,Qr]),he=Ze(a=>{un(a),Pe?.(a)},[Pe]),Va=me(""),[ds,Ql]=le(!1),Ha=Ze(()=>{Ql(!0)},[]);gt(()=>{if(!Le||!Se||!g||!ds||Ge||Va.current)return;let a=Bn({email:cn(y.email?.trim())?y.email?.trim():wn.current.trim(),firstName:y.firstName?.trim(),lastName:y.lastName?.trim()});Va.current=JSON.stringify(a),mt(b=>({...b,...a})),Promise.resolve(g(a)).catch(b=>{Va.current="",he(b instanceof Error?b.message:"Failed to attach buyer details.")})},[Le,Se,g,ds,Ge,y.email,y.firstName,y.lastName,he]),gt(()=>{!Le||!ge||ge.setCardFieldOrder?.(dt??null,te==null&&!Se)},[Le,ge,dt,te,Se]),gt(()=>{(We==="expanding"||We==="collapsing"||We==="apm-expanding"||We==="apm-collapsing")&&he(null)},[We,he]);let pr=Ze((a,b,j)=>{p?.(nn(a,b,j))},[p]),eo=Ze((a,b,j)=>{let Be=j?.popupBlocked??Ir(b),W=su(a,Be),st=Hr(j?.code)??wr(b)??"external_payment_method_failed",tt=new dr(W,"api_error",{code:"external_payment_method_failed",param:a});et(null),ve==="buttons"&&(hn("buttons"),On(null)),he(W),l?.(tt),console.error("[FloPay] External payment method failed:",{method:a,code:st,popupBlocked:Be})},[ve,l,he]);gt(()=>{if(!Le||!e){gn(null);return}let a=zi(ee?.vault);if(a){gn(a);return}if(!D){gn(null);return}gn(null);let b=!0;return new wo(ne).getVaultCapture(e,t).then(j=>{if(!b)return;let Be=zi(j);Be?gn(Be):he("Failed to load the secure card form.")}).catch(j=>{b&&he(j instanceof Error?j.message:"Failed to load the secure card form.")}),()=>{b=!1}},[Le,D,M,e,ee?.vault,ne,t,he]);let sr=me({onComplete:s,onError:l,updateError:he,emitDecline:pr,resolvedAccount:y,avsConfig:te,avsCheckProp:Q,sessionId:e,nonce:t,baseUrl:ne,captureMethod:ee?.captureMethod,paymentId:ee?.paymentId,authorizationExpiresAt:ee?.authorizationExpiresAt,serverSideCardGateway:an});sr.current={onComplete:s,onError:l,updateError:he,emitDecline:pr,resolvedAccount:y,avsConfig:te,avsCheckProp:Q,sessionId:e,nonce:t,baseUrl:ne,captureMethod:ee?.captureMethod,paymentId:ee?.paymentId,authorizationExpiresAt:ee?.authorizationExpiresAt,serverSideCardGateway:an};let Wa=me(!1),us=Ze(()=>{let a=sr.current,b=a.resolvedAccount.email?.trim(),j=cn(b)?b:wn.current.trim();if(!cn(j))return null;let Be=a.resolvedAccount.firstName?.trim(),W=a.resolvedAccount.lastName?.trim(),st=zt.current||a.resolvedAccount.country||"US",tt=a.avsConfig?rt(a.avsConfig.state,st):!1,yr=a.avsConfig?rt(a.avsConfig.address_line_1,st):!1,Xe=a.avsConfig?rt(a.avsConfig.postal_code,st):!1,Mt=a.avsConfig?rt(a.avsConfig.city,st):!1,ft=a.avsConfig?rt(a.avsConfig.address_line_2,st):!1,nt=yr&&!tt&&Xe?vl(st,(Tt.current??"").trim()):null,Mn=tt?Sn.current:nt;return{accountData:{userId:a.resolvedAccount.userId??"",email:j,...Be?{firstName:Be}:{},...W?{lastName:W}:{},...Xe&&Tt.current?{zip:Tt.current}:{},...Mt&&At.current?{city:At.current}:{},...Mn?{state:Mn}:{},...yr&&yn.current?{addressLine1:yn.current}:{},...ft&&Ut.current?{addressLine2:Ut.current}:{},country:st},...a.avsCheckProp===void 0?{}:{avsCheck:a.avsCheckProp},...a.avsConfig?{avsConfig:{country:rt(a.avsConfig.country,st),postal_code:Xe,address_line_1:yr,address_line_2:ft,city:Mt,state:tt}}:{}}},[]),ps=me(_e);ps.current=_e,gt(()=>{_e||P!==Il||sr.current.updateError(null)},[_e,P]),gt(()=>{!Le||!ge||ge.setSubmitGate?.(Hn||_e||Ge||T)},[Le,ge,Hn,_e,Ge,T]),gt(()=>{if(!Le||!ge)return;Wa.current=!1;let a=null,b=()=>{a&&clearTimeout(a),a=setTimeout(()=>{a=null,_t.current="idle",et(null)},400)},j=ge.on("submitting",()=>{zr(!0),Xt.current&&clearTimeout(Xt.current),_t.current="validation-window",Xt.current=setTimeout(()=>{Xt.current=null,_t.current==="validation-window"&&(_t.current="processing")},Jd),et("processing");let Xe=sr.current;if(!Xe.sessionId||!Xe.nonce)return;let Mt=us();if(!Mt){Xe.updateError("Enter a valid email address."),_t.current="idle",et(null);return}new wo(Xe.baseUrl).patchAccountSnapshot(Xe.sessionId,Xe.nonce,Mt,{telemetryMode:"best_effort"}).catch(ft=>{if(!Zd(ft))return;let nt=ft instanceof Error?ft.message:"Please check your billing address and try again.";Xe.updateError(nt),_t.current="idle",et(null),Xe.onError?.(ft instanceof dr?ft:new dr(nt,"api_error"))})}),Be=ge.on("complete",async Xe=>{if(bo(Xe.sessionId??sr.current.sessionId),_t.current="terminal",E(!1),et("success"),await new Promise(Mn=>setTimeout(Mn,600)),Wa.current)return;Wa.current=!0;let Mt=sr.current,ft=Bi(Mt)||Xe.outcome==="authorized",nt=Mt.serverSideCardGateway?{}:{paymentIntentId:Xe.intentId};sr.current.onComplete?.(ft?{status:"authorized",...nt,paymentId:Xe.paymentId??Mt.paymentId,sessionId:Xe.sessionId??Mt.sessionId,authorizationExpiresAt:Xe.authorizationExpiresAt??Mt.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",...nt,checkoutMethod:"card"})}),W=ge.on("decline",Xe=>{let Mt=sr.current,ft=Xe.message??"Your payment was declined. Please try another card or contact your bank.";_t.current="terminal",E(!1),Mt.updateError(ft),et("error");let nt=Xe.failureOutcome??Bd(Xe.declineReason)??"authorization_declined";Mt.emitDecline("card",ft,{code:nt,declineCode:nt}),b()}),st=ge.on("error",Xe=>{let Mt=sr.current,ft=Xe.message??"There was a problem processing your payment. Please try again.";_t.current="terminal",E(!1),Mt.updateError(ft),et("error"),Mt.onError?.(new dr(ft,"api_error",{code:Xe.failureOutcome??"capture_failed"})),b()}),tt=ge.on("challenge_dismissed",()=>{Xt.current&&(clearTimeout(Xt.current),Xt.current=null),_t.current="processing",E(!0),et(null)}),yr=ge.on("blocked",()=>{if(F.current){sr.current.updateError(Xd);return}if(!ps.current){zr(!0);return}Ha(),sr.current.updateError(Il)});return()=>{a&&(clearTimeout(a),a=null),Xt.current&&(clearTimeout(Xt.current),Xt.current=null),_t.current="idle",E(!1),et(null),j(),Be(),W(),st(),tt(),yr()}},[Le,ge,Ha,us]);let mr=!!ke?.clientId,To=Array.isArray(X),sa=To&&X.length>0,ec=To&&X.includes("paypal"),{expressMethods:la,paymentElementMethods:Ao}=Ft(()=>Fd(X,{excludePaypal:mr}),[X,mr]),ms=mr||!!$,tc=Ft(()=>ms?la.filter(a=>a!=="paypal"):la,[la,ms]),nc=Ft(()=>{let a=[];return Te&&a.push("apple_pay"),Fe&&a.push("google_pay"),a},[Te,Fe]),to=To?tc:nc,rc=G&&to.length>0,Ga=on?O:de,ca=Ft(()=>{let a=Ga?.trim().toUpperCase();return a?ce?Ao.filter(b=>{let j=ce[b];return!j||j.length===0||j.includes(a)}):Rd(Ao,Ga):Ao},[Ao,Ga,ce]),Ya=Ft(()=>({mode:"payment",amount:qn,currency:Zr,paymentMethodCreation:"manual",appearance:ss}),[qn,Zr,ss]),[ys,fs]=le("loading"),[gs,hs]=le("loading"),[vs,Ps]=le("loading"),[oc,Ja]=le(!1),[bs,Xa]=le("loading"),[Za,ac]=le();gt(()=>{ac(ba())},[]);let da=Za?.inAppBrowser,ua=Za?Ca(Za,ke?.approvalPresentation,B??(Ee?"subscription":"order")):"popup",Cs=S&&(mr||(To?ec:da===!1)),Ss=G&&rc,xo=(!Re||!!K.waitForDataAttachment)&&Cs&&mr,ws=bs==="retrying"||bs==="exhausted",Mo=!Re&&Cs&&!!tn&&(!mr||ws),no=!Re&&Ss&&!!ht,Bo=!Re&&G&&sa&&ca.length>0&&!!ht,ic=xo&&!ws?oc:Mo&&Tl(ys),sc=no&&Tl(gs),lc=Bo&&vs!=="load_error",Is=a=>a==="loading"||a==="ready",ks=xo||Mo&&Is(ys)||no&&Is(gs)||Bo&&vs!=="load_error",pa=me(!1);gt(()=>{if(!pa.current){if(!G&&!S){pa.current=!0;let a=new dr("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");l?.(a),he(a.message)}else if(!G&&S&&!mr&&!tn){pa.current=!0;let a=new dr("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");l?.(a),he(a.message)}else if(da!==void 0&&!Re&&!Wt&&!ks){pa.current=!0;let a=new dr("FloPay: this checkout session has no vault card capability and no usable supported non-card payment methods. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});l?.(a),he(a.message)}}},[G,S,mr,tn,da,Re,Wt,ks,l,he]);let _s=me(!1);gt(()=>{if(_s.current||!sa)return;let a=[];Te!==!0&&a.push("showApplePay"),Fe!==!0&&a.push("showGooglePay"),a.length!==0&&(_s.current=!0,console.warn(`[FloPay] ${a.join(" / ")} ${a.length===1?"is":"are"} deprecated: the Apple Pay / Google Pay surface is now driven by \`gateways.stripe.enabledPaymentMethods\` on the session response. Remove the legacy prop(s) to silence this warning.`))},[sa,Te,Fe]);let Rs=Ze((a,b)=>K.applyInlineSessionPatch?K.applyInlineSessionPatch(a).then(j=>({error:null,sessionId:j.sessionId||e,nonce:j.session?.clientSecret||t})).catch(j=>{let Be=El(b,j);return he(Be.message),l?.(Be),{error:Be,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[K.applyInlineSessionPatch,t,l,e,he]),lr=Ze(async a=>{if(a!=="card"&&Re&&await K.waitForDataAttachment?.(),!Ie)return{proceed:!0};try{let b=await Ie({method:a,sessionId:e||void 0,createSession:K.inlineSessionDraft});if(b===!1)return{proceed:!1};if(b&&typeof b=="object"){b.account&&mt(Be=>({...Be??{},...b.account}));let j=await Rs(b,a);return j.error?{proceed:!1,accountPatch:b.account}:{proceed:!0,accountPatch:b.account,sessionId:j.sessionId,nonce:j.nonce}}return{proceed:!0}}catch(b){let j=El(a,b);return he(j.message),l?.(j),{proceed:!1}}},[Rs,K.inlineSessionDraft,K.waitForDataAttachment,Re,Ie,l,e,he]),Es=Ze(async(a,b)=>{if(Jn.current)return;Jn.current=!0,Et(!0),et("processing"),he(null);let j=b?.sessionId??e,Be=b?.nonce??t,W=ui(y,b?.accountPatch),st=b?.completionPaymentMethodId??Ko(a),tt=a.originalPaymentMethodId?{...a,originalPaymentMethodId:void 0}:a,yr=ru(a),Xe=()=>{ie?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"process_payment",provider:yr})};try{let ft=await new wo(ne).processPayment(W.userId??"",{sessionId:j,nonce:Be,paymentMethodCategory:b?.paymentMethodCategory??au(a),tokenizedData:tt,accountData:{...b?.accountPatch,userId:W.userId??"",email:W.email??"",firstName:W.firstName||void 0,lastName:W.lastName||void 0,...te?(()=>{let vt=zt.current,Zn=rt(te.state,vt),kn=rt(te.address_line_1,vt),Zt=rt(te.postal_code,vt),Kr=kn&&!Zn&&Zt?vl(vt,(Tt.current??"").trim()):null,zo=Zn?Sn.current:Kr;return{country:vt,...Zt&&Tt.current?{zip:Tt.current}:{},...rt(te.city,vt)&&At.current?{city:At.current}:{},...zo?{state:zo}:{},...kn&&yn.current?{addressLine1:yn.current}:{},...rt(te.address_line_2,vt)&&Ut.current?{addressLine2:Ut.current}:{}}})():{}},chv:m,avsCheck:Q??!1,checkoutType:L,checkoutLayout:Ae,avsConfig:te?{country:rt(te.country,zt.current),postal_code:rt(te.postal_code,zt.current),address_line_1:rt(te.address_line_1,zt.current),address_line_2:rt(te.address_line_2,zt.current),city:rt(te.city,zt.current),state:rt(te.state,zt.current)}:void 0});if(ft.ok){let vt=ft.status===204?null:await ft.json().catch(()=>null),Zn=Bi(ee)||vt?.status==="authorized";bo(j),et("success"),it(null),await new Promise(Kr=>setTimeout(Kr,600));let kn;typeof vt?.paymentId=="string"?kn=vt.paymentId:ee?.paymentId&&(kn=ee.paymentId);let Zt;typeof vt?.authorizationExpiresAt=="string"?Zt=vt.authorizationExpiresAt:ee?.authorizationExpiresAt&&(Zt=ee.authorizationExpiresAt),s?.(Zn?{status:"authorized",...kn===void 0?{}:{paymentId:kn},sessionId:typeof vt?.sessionId=="string"?vt.sessionId:j,...Zt===void 0?{}:{authorizationExpiresAt:Zt},paymentIntentId:a.threeDSecureActionResultTokenId,paymentMethodId:st,checkoutMethod:a.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:a.threeDSecureActionResultTokenId,paymentMethodId:st,checkoutMethod:a.isPaypal?"paypal":"card"});return}let nt=await ft.json().catch(()=>null);if(nt?.type==="paypal_redirect_required"){let vt=nt.threeDSecureToken,Zn=nt.paymentMethodId||a.id||"";if(!Je||!vt){et("error"),he("PayPal authorization required but no token provided.");return}try{let kn=$?.getRawProvider();if(!kn){he("PayPal is not available.");return}let Zt={return_url:window.location.href};Zn&&(Zt.payment_method=Zn);let{error:Kr}=await kn.confirmPayment({clientSecret:vt,confirmParams:Zt,redirect:"if_required"});if(Kr){et("error");let zo=Kr.message??"PayPal payment failed.";he(zo),pr("paypal",zo,{code:Kr.code})}}catch(kn){et("error"),he(kn instanceof Error?kn.message:"PayPal authorization failed.")}return}if(nt?.type==="paypal_direct_required"){let vt=nt.orderId;if(!vt){et("error"),he("PayPal retry required but no order id provided.");return}let Zn=R.current?.attempts??0;if(Zn>=2){et("error"),he("PayPal payment could not be completed after multiple attempts."),pr("paypal","paypal_direct_required retry limit exceeded");return}Ja(!1),Xa("loading"),it({orderId:vt,attempts:Zn+1}),et(null);return}_d(ft.status,nt)||Xe(),et("error");let Mn=nt?.message??"Payment failed. Please try again.";he(Mn),pr(a.isPaypal?"paypal":"card",Mn,{code:nt?.code??nt?.gatewayErrorCode,declineCode:nt?.declineCode??nt?.gatewayDeclineReason}),await new Promise(vt=>setTimeout(vt,400))}catch(Mt){Nl(Mt)||Xe(),et("error"),he(Mt instanceof Error?Mt.message:"An unexpected error occurred"),await new Promise(ft=>setTimeout(ft,400))}finally{Et(!1),et(null),Jn.current=!1}},[ne,e,t,y,te,Q,L,Ae,m,Je,$,ee,s,he,pr,ie]),An=Ze((a,b)=>{f?f(a):Es(a,b)},[f,Es]),Fo=`${Fl}:${e}`;gt(()=>{if(typeof window>"u")return;let a=localStorage.getItem(Fo);if(!a)return;let b;try{b=JSON.parse(a)}catch{localStorage.removeItem(Fo);return}if(!b||typeof b.createdAt!="number"||Date.now()-b.createdAt<0||Date.now()-b.createdAt>Dl||typeof b.paymentMethodId!="string"||typeof b.providerIntentId!="string"||typeof b.paymentMethodType!="string"||b.sessionId!==e||!t||b.nonce!==t||!to.includes(b.paymentMethodType)){localStorage.removeItem(Fo);return}localStorage.removeItem(Fo),An({id:b.paymentMethodId,type:"card",threeDSecureActionResultTokenId:b.providerIntentId,gateway:"stripe",paymentMethodType:b.paymentMethodType},{...b.accountPatch?{accountPatch:b.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t})},[An,t,e,Fo,to]);let Ts=me(!1);gt(()=>{if(typeof window>"u"||Ts.current)return;let a=new URLSearchParams(window.location.search),b=a.get("payment_intent"),j=a.get("payment_intent_client_secret"),Be=a.get("redirect_status");if(!b||!j||!Je)return;let W=Je.getRawProvider();if(!W)return;let st=nt=>{let Mn=localStorage.getItem(nt);if(!Mn)return null;try{return JSON.parse(Mn)}catch{return localStorage.removeItem(nt),null}},tt=st(hr)??st(Cl),yr;if(tt?.clientSecret){if(tt.clientSecret!==j)return;yr={...tt.accountPatch?{accountPatch:tt.accountPatch}:{},...tt.sessionId?{sessionId:tt.sessionId}:{},...tt.nonce?{nonce:tt.nonce}:{}}}else if(tt?.sessionId&&tt.sessionId!==e)return;Ts.current=!0,localStorage.removeItem(hr),localStorage.removeItem(Cl);let Xe=new URL(window.location.href);Xe.searchParams.delete("payment_intent"),Xe.searchParams.delete("payment_intent_client_secret"),Xe.searchParams.delete("redirect_status"),window.history.replaceState({},"",Xe.toString());let Mt=tt?.paymentMethodType??tt?.tokenType??"card",ft="card";(async()=>{if(Be==="failed"){let Zt="Payment was declined. Please try again.";he(Zt),pr(ft,Zt);return}let{paymentIntent:nt,error:Mn}=await W.retrievePaymentIntent(j);if(Mn){let Zt=Mn.message??"Failed to retrieve payment status.";he(Zt),pr(ft,Zt,{code:Mn.code});return}let vt=nt?.status,Zn=$o(vt);if(!nt||!Zn){let Zt=vt==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";he(Zt),pr(ft,Zt,{code:vt??"missing_payment_intent"});return}let kn=typeof nt.payment_method=="string"?nt.payment_method:nt.payment_method?.id;An({id:kn??tt?.paymentMethodId??tt?.tokenId??nt.id,type:"card",threeDSecureActionResultTokenId:nt.id,gateway:tt?.gateway??"stripe",paymentMethodType:Mt},yr)})()},[e,An,Je,he,pr]);let Qa=Ze(a=>{a.preventDefault()},[]);if(!(Le||Je!==null))return c("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let Do=ve==="buttons",xn=q?.variables,cc=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),ei=xn?.colorBackground,dc=ei&&!cc.has(ei)?ei:void 0,No=v.cardInputBorder??(Do?"#e5e7eb":"#A4A4FF"),As=xn?.colorDanger??"#dc2626",qt=a=>Pr[a]&&(ar[a]||rr),ma=Ge&&(Er||rr),Xn=a=>a?As:No,ya=(sn.malformed||sn.empty)&&(Ur||rr),uc=Xn(ya),ti=v.cardFormContainer?.backgroundColor??dc??(Do?"white":"#EDEDFF"),ro=v.cardInputBackground??xn?.colorBackground??"white",ni=io(ye),xs=io(we),oo=v.nameInput,Ms=v.cardInputFontSize??uu(oo?.fontSize)??xn?.fontSizeBase??"16px",Bs=typeof oo?.fontFamily=="string"?oo.fontFamily:xn?.fontFamily??"Poppins, sans-serif",Fs=zs(oo?.fontWeight)??400,pc=v.cardInputColor??(typeof oo?.color=="string"?oo.color:void 0)??xn?.colorText??"#262833",mc=v.cardInputPlaceholderColor??"#9ca3af",Vt=xn?.borderRadius??"8px",jr=xn?.borderRadius??v.cardButton?.borderRadius??Vt,$r=xn?.colorPrimary??"#4A49FF",yc=xn?.colorPrimaryHover??qo($r,.12),ri=xn?.colorText??"#262833",oi={fontSize:Ms,fontFamily:Bs,fontWeight:Fs,color:pc,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},Lo={marginTop:"0.375rem",...oi,fontSize:"0.75rem",lineHeight:1.4,color:As},fc={"--flopay-input-placeholder-color":mc,"--flopay-input-font-size":Ms,"--flopay-input-font-family":Bs,"--flopay-input-font-weight":String(Fs)},Oo=v.cardFormContainer??{},ai=Oo.padding??(Do?"0":"1rem"),ii=Oo.borderRadius??Vt,gc=ge&&ir?c(si,{capture:ge,html:ir.html,messageToken:ir.messageToken,expectedOrigin:ir.expectedOrigin,theme:Ve,submitLabel:_,onReady:()=>{if(!Se&&!te||typeof document>"u")return;let a=()=>{let j=(document.querySelector('[data-testid="flopay-vault-identity-fields"]')??document.querySelector('[data-testid="flopay-avs-fields"]'))?.querySelector("input:not([disabled]), select:not([disabled])");if(j){Ln.current=!0;try{j.focus()}finally{Ln.current=!1}}};Gn.current||a()},onError:a=>he(a),onValidation:a=>{let b=_t.current;(b==="idle"||b==="validation-window")&&(he(a),a&&_t.current==="validation-window"&&(Xt.current&&(clearTimeout(Xt.current),Xt.current=null),_t.current="idle",et(null)))}}):c("div",{"data-testid":"flopay-vault-loading",style:{minHeight:120,display:"flex",alignItems:"center",justifyContent:"center",color:"#6b7280",fontSize:14},children:"Loading secure card form\u2026"}),Ds=ze("div",{onFocusCapture:a=>{["INPUT","SELECT","TEXTAREA","IFRAME"].includes(a.target.tagName)&&Cr()},style:{backgroundColor:ti,borderRadius:ii,...Oo,padding:ai,...fc,display:"flex",flexDirection:"column"},children:[c("style",{children:`
|
|
26
26
|
.flopay-shared-input::placeholder {
|
|
27
27
|
color: var(--flopay-input-placeholder-color);
|
|
28
28
|
opacity: 1;
|
|
@@ -30,13 +30,13 @@ ${yn.join(`
|
|
|
30
30
|
font-family: var(--flopay-input-font-family);
|
|
31
31
|
font-weight: var(--flopay-input-font-weight);
|
|
32
32
|
}
|
|
33
|
-
`}),
|
|
34
|
-
`)}):null,
|
|
35
|
-
`)}):null,Fs=Ve==="apm-expanding"||Ve==="apm-form"||Ve==="apm-collapsing",ro;Ve==="apm-expanding"?ro=Sl:Ve==="apm-collapsing"&&(ro=wl);let ma=pn?Ll(Wa,pn):null;if(Re==="buttons"){let a=Ve==="buttons"||Ve==="expanding"||Ve==="apm-expanding",P=Ve==="expanding"||Ve==="card"||Ve==="collapsing",O=$e===void 0?{boxSizing:"border-box",height:Fa,padding:"0 1rem"}:{padding:"0.9rem 1rem"},Ne;Ve==="expanding"||Ve==="apm-expanding"?Ne=Xd:(Ve==="collapsing"||Ve==="apm-collapsing")&&(Ne=Jd);let j;return Ve==="expanding"?j=Sl:Ve==="collapsing"&&(j=wl),Ue("form",{onSubmit:Ja,className:_,noValidate:!0,style:{position:"relative"},children:[c(Di,{}),k&&c(yr,{status:k,errorMessage:te,authorized:vn}),Ue("div",{style:{display:"grid"},children:[Ue("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!a&&!Ne?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!a&&!Ne?Qd:{},...Ne?{animation:Ne,pointerEvents:"none"}:{}},children:[xs("flopay-direct-paypal-gate-debug"),Bs("flopay-stripe-gate-debug"),To&&_e&&Ue(Wr,{children:[X&&c("div",{"data-testid":"flopay-paypal-direct-retry-notice",style:{padding:"8px 10px",background:"#fef3c7",border:"1px solid #fcd34d",borderRadius:6,color:"#78350f",fontSize:13,lineHeight:1.4},children:"Please confirm your PayPal payment to complete checkout."}),c(wa,{sessionId:e,nonce:t,billingApiUrl:K,email:D.email,billingName:q||void 0,onBuyerIdentityReady:L,clientId:_e.clientId,environment:_e.environment,currency:ke.toUpperCase(),isSubscription:le,providerObjectType:xe,approvalPresentation:la==="popup"?void 0:la,onTokenizedBody:xn,onComplete:s,onErrorChange:pe,onDecline:p,onTechnicalFailure:Zr,onButtonClick:ee,runBeforeButtonClick:or,isProcessing:Be,onLoadStateChange:Ha,onInitializationStateChange:Ga,session:w,existingOrderId:X?.orderId,debug:Mt},X?.orderId??"fresh")]}),Ao&&c(Vr,{stripe:Yr,options:as,children:c(Rl,{sessionId:e,nonce:t,email:D.email,billingName:q||void 0,onBuyerIdentityReady:L,billingApiUrl:K,onTokenizedBody:xn,onErrorChange:pe,isProcessing:Be,onButtonClick:ee,onDecline:p,onTechnicalFailure:Zr,runBeforeButtonClick:or,onLoadStateChange:us,placeholderBorderRadius:Lr})}),eo?c(Vr,{stripe:Xt,options:os,children:c(El,{sessionId:e,nonce:t,email:D.email,billingName:q||void 0,onBuyerIdentityReady:L,billingApiUrl:K,intentKind:ot>0?"payment":"setup",expressMethods:Qr,onTokenizedBody:xn,onErrorChange:pe,onButtonClick:ee,onDecline:p,onTechnicalFailure:Zr,runBeforeButtonClick:or,onLoadStateChange:ms,placeholderBorderRadius:Lr})}):null,!eo&&vs?c("div",{style:{height:Fa,borderRadius:Lr,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,Mo&&c(Tl,{sessionId:e,nonce:t,email:D.email,billingName:[D.firstName,D.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:L,billingApiUrl:K,paymentElementMethods:ia,stripeInstance:Xt,paymentElementBaseOptions:Wa,onTokenizedBody:xn,onErrorChange:pe,onButtonClick:ee,onDecline:p,runBeforeButtonClick:or,onLoadStateChange:fs,isProcessing:Be,submitButtonColor:Or,submitButtonBorderRadius:jt,submitButtonStyle:b.submitButton,onExpandApm:Nr,expandedApmMethod:pn,themeId:Ge,buttonAppearance:{backgroundColor:b.cardButton?.backgroundColor,borderColor:b.cardInputBorder,textColor:b.cardButton?.color,borderRadius:Lr}}),ze&&c("button",{type:"button",onClick:async()=>{Be||!(await or("card")).proceed||(ee?.("card"),Dr())},disabled:Be,style:{width:"100%",...O,...b.cardButton,...Ki({themeBundle:V,resolvedPrimaryColor:Or,resolvedBorderRadius:jt,submitButtonStyle:b.submitButton,explicitPrimaryColor:Bn?.colorPrimary}),fontSize:b.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:Be?"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?.6:1},onMouseEnter:at=>{!Be&&(V||Bn?.colorPrimary)&&(at.currentTarget.style.backgroundColor=dc)},onMouseLeave:at=>{(V||Bn?.colorPrimary)&&(at.currentTarget.style.backgroundColor=Or)},onMouseDown:at=>{at.currentTarget.style.transform="scale(0.985)"},onMouseUp:at=>{at.currentTarget.style.transform="scale(1)"},children:c(ao,{content:$e})}),te&&Ve==="buttons"&&c(fo,{margin:"0.25rem 0",styleOverride:b.errorBanner,children:te})]}),ze&&P&&c("div",{style:{gridArea:"1 / 1",...j?{animation:j}:{},...Ve==="collapsing"?{pointerEvents:"none"}:{}},children:Ms}),W&&Fs&&pn&&ma&&Xt&&c("div",{style:{gridArea:"1 / 1",...ro?{animation:ro}:{},...Ve==="apm-collapsing"?{pointerEvents:"none"}:{}},children:Ue("div",{style:{backgroundColor:Za,borderRadius:ri,...No,padding:ni},children:[Ue("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[Ue("button",{type:"button","data-testid":"flopay-apm-back-button",onClick:Jt,style:{display:"inline-flex",alignItems:"center",gap:Qa?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:b.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...b.backButton},"aria-label":"Back to payment methods",children:[c("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...b.backButtonIcon},children:c("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:c("path",{d:"M15 18l-6-6 6-6"})})}),c(io,{content:ue})]}),c("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:b.titleFontSize??"1.05rem",color:ei,paddingRight:80,...b.title},children:`Pay with ${Hr(pn)}`})]}),c(Vr,{stripe:Xt,options:ma,children:c(zi,{method:pn,sessionId:e,nonce:t,email:D.email,billingName:[D.firstName,D.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:L,billingApiUrl:K,onTokenizedBody:xn,onErrorChange:pe,onDecline:p,onCancel:Jt,runBeforeButtonClick:or,onButtonClick:ee,isProcessing:Be,submitButtonColor:Or,submitButtonBorderRadius:jt,submitButtonStyle:b.submitButton,errorText:te})},pn)]})})]})]})}return Fs&&pn&&ma&&Xt&&W?Ue("form",{onSubmit:Ja,className:_,noValidate:!0,style:{position:"relative"},children:[c(Di,{}),k&&c(yr,{status:k,errorMessage:te,authorized:vn}),c("div",{style:{...ro?{animation:ro}:{},...Ve==="apm-collapsing"?{pointerEvents:"none"}:{}},children:Ue("div",{style:{backgroundColor:Za,borderRadius:ri,...No,padding:ni},children:[Ue("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[Ue("button",{type:"button","data-testid":"flopay-apm-back-button-default",onClick:Jt,style:{display:"inline-flex",alignItems:"center",gap:Qa?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:b.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...b.backButton},"aria-label":"Back to payment methods",children:[c("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...b.backButtonIcon},children:c("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:c("path",{d:"M15 18l-6-6 6-6"})})}),c(io,{content:ue})]}),c("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:b.titleFontSize??"1.05rem",color:ei,paddingRight:80,...b.title},children:`Pay with ${Hr(pn)}`})]}),c(Vr,{stripe:Xt,options:ma,children:c(zi,{method:pn,sessionId:e,nonce:t,email:D.email,billingName:[D.firstName,D.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:L,billingApiUrl:K,onTokenizedBody:xn,onErrorChange:pe,onDecline:p,onCancel:Jt,runBeforeButtonClick:or,onButtonClick:ee,isProcessing:Be,submitButtonColor:Or,submitButtonBorderRadius:jt,submitButtonStyle:b.submitButton,errorText:te})},pn)]})})]}):Ue("form",{onSubmit:Ja,className:_,noValidate:!0,style:{position:"relative"},children:[c(Di,{}),k&&c(yr,{status:k,errorMessage:te,authorized:vn}),Ue("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[xs("flopay-direct-paypal-gate-debug-default"),Bs("flopay-stripe-gate-debug-default"),To&&_e&&Ue(Wr,{children:[X&&c("div",{"data-testid":"flopay-paypal-direct-retry-notice-default",style:{padding:"8px 10px",background:"#fef3c7",border:"1px solid #fcd34d",borderRadius:6,color:"#78350f",fontSize:13,lineHeight:1.4},children:"Please confirm your PayPal payment to complete checkout."}),c(wa,{sessionId:e,nonce:t,billingApiUrl:K,email:D.email,billingName:q||void 0,onBuyerIdentityReady:L,clientId:_e.clientId,environment:_e.environment,currency:ke.toUpperCase(),isSubscription:le,providerObjectType:xe,approvalPresentation:la==="popup"?void 0:la,onTokenizedBody:xn,onComplete:s,onErrorChange:pe,onDecline:p,onTechnicalFailure:Zr,onButtonClick:ee,runBeforeButtonClick:or,isProcessing:Be,onLoadStateChange:Ha,onInitializationStateChange:Ga,session:w,existingOrderId:X?.orderId,debug:Mt},X?.orderId??"fresh")]}),Ao&&c(Vr,{stripe:Yr,options:as,children:c(Rl,{sessionId:e,nonce:t,email:D.email,billingName:q||void 0,onBuyerIdentityReady:L,billingApiUrl:K,onTokenizedBody:xn,onErrorChange:pe,isProcessing:Be,onButtonClick:ee,onDecline:p,onTechnicalFailure:Zr,runBeforeButtonClick:or,onLoadStateChange:us,placeholderBorderRadius:Lr})}),eo&&c(Vr,{stripe:Xt,options:os,children:c(El,{sessionId:e,nonce:t,email:D.email,billingName:q||void 0,onBuyerIdentityReady:L,billingApiUrl:K,intentKind:ot>0?"payment":"setup",expressMethods:Qr,onTokenizedBody:xn,onErrorChange:pe,onButtonClick:ee,onDecline:p,onTechnicalFailure:Zr,runBeforeButtonClick:or,onLoadStateChange:ms,placeholderBorderRadius:Lr})}),Mo&&c(Tl,{sessionId:e,nonce:t,email:D.email,billingName:[D.firstName,D.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:K,paymentElementMethods:ia,stripeInstance:Xt,paymentElementBaseOptions:Wa,onTokenizedBody:xn,onErrorChange:pe,onButtonClick:ee,onDecline:p,runBeforeButtonClick:or,onLoadStateChange:fs,isProcessing:Be,submitButtonColor:Or,submitButtonBorderRadius:jt,submitButtonStyle:b.submitButton,themeId:Ge,onExpandApm:Nr,expandedApmMethod:pn,buttonAppearance:{backgroundColor:b.cardButton?.backgroundColor,borderColor:b.cardInputBorder,textColor:b.cardButton?.color,borderRadius:Lr}})]}),ze&&(rc||nc||oc)&&Ue("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem",margin:"0.5rem 0 0.75rem",color:"#999",fontSize:"0.85rem"},children:[c("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}}),c("span",{children:"or pay with card"}),c("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}})]}),ze&&Ms]})}import{Fragment as hr,jsx as re,jsxs as en}from"react/jsx-runtime";var So=44,Qi="flopay_checkout_saved_payment_resume",Ua=new Map,Oa=new Map;function zl(e,t){t.settled&&t.consumers===0&&Ua.get(e)===t&&Ua.delete(e)}function gu(e,t,n){let r=Oa.get(e);if(r&&(!r.sdkGeneratedIdempotencyKey||!t||r.sdkGeneratedIdempotencyKey===t))return r.attempt;let o=n(),i={attempt:o,sdkGeneratedIdempotencyKey:t};Oa.set(e,i);let s=()=>{Oa.get(e)===i&&Oa.delete(e)};return o.then(s,s),o}function Qo(e){return new Promise(t=>setTimeout(t,e))}function za(e,t,n){let r=Ca({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:Hl,enabled:t!==!1});return r.beginCheckout(n),r}function ea(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function Hi(e,t,n,r,o,i){let s=za(e,t,n);s.error({errorCode:r,stage:o,paymentMethodCategory:"unknown",...i,...o==="session_read"?{requestCategory:"session_read"}:{}}),ea(s)}function Ul(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 ql(e,t,n,r,o){let i=Vl(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 mn&&t.code==="session_auto_completed"?!1:t instanceof mn&&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 Zi(e){let t=e?.data.paypal?.publishableKey;if(t)return{clientId:t,environment:e?.data.paypal?.environment,providerObjectType:e?.data.paypal?.providerObjectType,approvalPresentation:e?.data.paypal?.approvalPresentation}}function Gi(e){return!e||e.data.stripe?.publishableKey?!1:!!Zi(e)?.clientId}var hu={name:"provider_unavailable",initialize:()=>Promise.resolve(),getRawProvider:()=>null,destroy:()=>{}};function vu(e){return new cu(hu,{publishableKey:"provider_unavailable",...e})}async function Yi(e,t){let{publishableKey:n,paypalPublishableKey:r}=ki(e);return{...await _i({publishableKey:n,paypalPublishableKey:r,...t}),publishableKey:n,paypalPublishableKey:r}}function es(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function Pu(){if(!es())return null;try{let e=window.sessionStorage.getItem(Qi);return e?JSON.parse(e):null}catch{return null}}function jl(e){if(es())try{window.sessionStorage.setItem(Qi,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function Ji(){if(es())try{window.sessionStorage.removeItem(Qi)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}function bu(){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 $l(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 Xi(e,t){return e?"custom_layout":t==="buttons"?"buttons_layout":"default_layout"}function Cu(e,t){return e?"unknown":t==="buttons"?"buttons":"embedded"}function Kl(e){return e?.gateways?.stripe?"stripe":e?.gateways?.paypal?"paypal":void 0}function Su(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 ts({sessionId:e,nonce:t,createSession:n,billingApiUrl:r,telemetry:o,appearance:i,locale:s,loading:l,error:p,onComplete:v,onError:g,onInstrument:h,onDecline:y,onCountryChange:_,onZipChange:M,showPayPal:U=!0,showStripe:qe=!0,enabledPaymentMethods:ge,showApplePay:S=!0,showGooglePay:W=!0,debug:Y=!1,layout:de,theme:Le,buttonsTheme:Se,buttonsStyles:Re,cardButtonContent:Ge,cardBackButtonContent:St,cardTitleContent:tt,showSecurityFooter:je,onButtonClick:$e,onBeforeButtonClick:ue,enableAVS:we,cardFieldOrder:Xe,cardPreFormSlot:ee,avsLayout:Ie,submitLabel:he,className:st,initialErrorMessage:lt=null,children:T,checkoutMode:$,confirmLabel:Ee,renderConfirmButton:ie,onSessionCompleted:rt}){let A=mu(r),Te=Yn(()=>Wl(Le),[Le]),dt=i??Te?.appearance,We=n?"embedded_checkout":"standard_checkout",se=Xi(T,de),[x,Q]=Ot(null),[Me,ot]=Ot(null),ke=Tt(null),Ke=Tt(null),_e=Tt(0),[le,ve]=Ot(null),Vt=Tt(null),[H,Mt]=Ot(null),mt=Yn(()=>n?ho(n):"",[n]),R=n?`create:${mt}`:`session:${e??""}`,ne=Kl(H),u=Tt(new Set),w=Tt(R),xe=Tt(R);Oo(()=>{xe.current=R,w.current!==R&&(w.current=R,u.current.clear())},[R]);let me=wn(k=>{if(xe.current===R){if(ui.has(k.name)){if(u.current.has(k.name))return;u.current.add(k.name)}Rt(()=>h?.(k))}},[R,h]),Ct=yo(me,R),nt=Tt(!1),xt=wn(k=>{if(nt.current)return;let f=k.gateway||!ne?k:{...k,gateway:ne};me(f)},[me,ne]);gr(()=>{Ct({class:"lifecycle",name:"checkout.mount"})},[Ct]);let[K,Wt]=Ot(e??""),wt=e??K,yn=n?"":wt,[sr,N]=Ot(!0),[fn,In]=Ot(null),[cn,rn]=Ot(0),[gn,Jn]=Ot("full"),[dn,Ht]=Ot(!1),[Ae,Oe]=Ot(lt),[on,ut]=Ot(null),[jn,Bt]=Ot(null),[Gt,gt]=Ot(!1),[$t,un]=Ot(void 0),[Ft,It]=Ot(""),[an,Nn]=Ot(!1),[vt,J]=Ot(!1),[hn,vn]=Ot(!1),Dt=Tt(null),zt=Tt(0),Ln=Tt(void 0),[$n,Xn]=Ot("loading"),[Yt,ze]=Ot(0),Ut=Tt(!1),Pe=Tt(!1),E=Tt(!1),be=Tt(null),I=Yn(()=>({checkoutMode:$??gn,layout:Cu(T,de)}),[$,T,gn,de]),Nt=Tt(v);Nt.current=v;let Pn=Tt(g);Pn.current=g;let sn=Tt(y);sn.current=y;let On=wn((k,f)=>{ke.current=k,ot(k),Vt.current=f,ve(f)},[]),ae=wn(()=>{let k=Ke.current;k&&(Ke.current=null,k.destroy())},[]);gr(()=>{Qt(Me)?.setCheckoutContext(I),le&&le!==Me&&Qt(le)?.setCheckoutContext(I)},[Me,le,I]);let bn=Tt(rt);bn.current=rt;let Br=wn(k=>{Xn(k),!(k!=="exhausted"||E.current)&&(E.current=!0,Pn.current?.(new mn("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),Gr=wn(()=>{Xn("retrying"),ze(k=>k+1)},[]);gr(()=>{Xn("loading"),ze(0),E.current=!1},[wt]),gr(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:Hl,checkout_type:We,checkout_layout:se,billing_api_url:A})},[se,We,A]);let kn=Yn(()=>n?ho(n,!0):"",[n]),wr=Yn(()=>Ft===kn?$t:void 0,[$t,Ft,kn]),lr=Yn(()=>n?si(n,wr):void 0,[n,wr]),Zn=$??lr?.checkoutMode??"full",Kt=Yn(()=>lr?{...lr,checkoutMode:Zn}:void 0,[lr,Zn]);gr(()=>{un(void 0),It(kn),Ln.current=void 0,Dt.current=null,vn(!1)},[kn]),gr(()=>{Oe(lt)},[lt]);let _n=wn((k,f,G)=>{Rt(()=>{sn.current?.(nn(k,f,G))})},[]),vr=wn(async(k,f)=>{Oe(null),Bt(null),gt(!1),ut("processing");let G=f?.sessionId??k.id,B=Kl(k),Ce=ke.current??Vt.current,ct=Qt(Ce),ye=Ce?null:za(A,o,I),z={log:b=>{ct?ct.log(b):ye?.log(b)},error:b=>{ct?ct.error(b):ye?.error(b)},terminal:b=>{ct?ct.terminal(b):ye?.terminal(b)},performance:b=>{ct?ct.performance(b):ye?.performance(b)},now:()=>ct?.now()??ye?.now()??0,elapsed:b=>ct?.elapsed(b)??Math.max(0,(ye?.now()??b)-b)},X=z.now(),F=!!(f?.initialAutoProcessingError||f?.initialAutoProcessingPending),m=!1,d,C=()=>{m||(m=!0,F=!0,d=z.now(),z.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),z.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},L=!1,te=()=>{L||(L=!0,z.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),z.performance({stage:"processing",durationMs:z.elapsed(X),durationMode:"machine",paymentMethodCategory:"saved",requestCategory:"process_payment"}),d!==void 0&&z.performance({stage:"recovery",durationMs:z.elapsed(d),durationMode:"machine",paymentMethodCategory:"saved"}))};z.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),nt.current=!0;try{z.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"})}finally{nt.current=!1}Ct({class:"lifecycle",name:"payment.processing.started",provider:B}),F&&C();let V;try{let b=ul(f?.initialAutoProcessingError),Z;if(b)C(),b.type==="paypal_redirect_required"&&be.current?.publishableKey&&jl({sessionId:G,publishableKey:be.current.publishableKey,paypalPublishableKey:be.current.paypalPublishableKey}),Z=await Ma(b,{flopay:ke.current,paypalFlopay:Vt.current,attempt3DS:f?.attempt3DS,billingApiUrl:A,sessionId:G,session:k,telemetry:!1}),b.type==="paypal_redirect_required"&&Ji();else if(f?.initialAutoProcessingPending){let Be=(await new La(A,{telemetry:!1}).waitForCheckoutSessionCompletion(f.initialAutoProcessingPending.sessionId,{initialDelayMs:f.initialAutoProcessingPending.retryAfterMs})).data.session;if(!co(Be))throw ga(Be);Z=jr(Be,G)}else{if(f?.initialAutoProcessingError)throw Tr(f.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:f.initialAutoProcessingError.checkoutMethod});if(f?.fromCreateSession)return f?.fallbackToFull&&(Jn("full"),$l("full")),!1;{let pt=await Po({billingApiUrl:A,sessionId:G,session:k,telemetry:!1});pt.type==="success"?Z=pt.result:(C(),pt.type==="paypal_redirect_required"&&be.current?.publishableKey&&jl({sessionId:G,publishableKey:be.current.publishableKey,paypalPublishableKey:be.current.paypalPublishableKey}),Z=await Ma(pt,{flopay:ke.current,paypalFlopay:Vt.current,attempt3DS:f?.attempt3DS,billingApiUrl:A,sessionId:G,session:k,telemetry:!1}),pt.type==="paypal_redirect_required"&&Ji())}}G&&vo(G),te(),F&&(z.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),z.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),z.terminal({outcome:Z.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),gt(Z.status==="authorized"),ut("success"),await Qo(600),V=()=>Nt.current?.(Z)}catch(b){let Z=Jo(b),pt=Z.checkoutMethod??Yo;Oe(Z.message),Bt(Z.message),gt(!1),f?.fallbackToFull&&(z.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),Jn("full"),$l("full")),te();let qt=Z.statusCode===void 0?void 0:fu(Z.statusCode,"unknown"),Be=qt==="4xx"?{requestCategory:"process_payment",statusClass:qt}:{},fe=qt===void 0||qt==="4xx";if(fe&&(Z.telemetryOutcome==="payment_declined"||!!(Z.declineCode||Z.code?.toLowerCase().includes("declin"))))z.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...Be});else if(fe&&(Z.telemetryOutcome==="validation_rejected"||Z.type==="validation_error"))z.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...Be});else{let Fe=Vl(b,F?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown"),De=Z.telemetryRequestCategory??"process_payment";nt.current=!0;try{z.error({...Fe,...Z.telemetryFailureCategory?{failureCategory:Z.telemetryFailureCategory}:{},stage:F?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:De})}finally{nt.current=!1}Ct({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:De,provider:B})}return Rt(()=>Pn.current?.(Z)),_n(pt,Z,{code:Z.code,declineCode:Z.declineCode}),ut("error"),await Promise.allSettled([Qo(400),f?.ensureProvidersReady?f.ensureProvidersReady():Promise.resolve()]),F&&(z.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),z.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{te(),ye&&ea(ye),ut(null),Bt(null)}return Rt(V),!0},[_n,Ct,A,o,I]);gr(()=>{if(typeof window>"u"||Pe.current)return;let k=new URLSearchParams(window.location.search),f=k.get("payment_intent_client_secret");if(!f)return;let G=Pu();G&&(Pe.current=!0,(async()=>{let B,Ce=0;Oe(null),Bt(null),ut("processing"),Ht(!0);try{if(k.get("redirect_status")==="failed")throw Object.assign(new mn("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:ct,paypalFlopay:ye}=await _i({publishableKey:G.publishableKey,paypalPublishableKey:G.paypalPublishableKey,billingApiUrl:A,locale:s,telemetry:o});B=Qt(ye??ct),B?.setCheckoutContext(I),Ce=B?.now()??0,B?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),B?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let z=(ye??ct)?.getRawProvider();if(!z)throw Object.assign(new mn("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:X,error:F}=await z.retrievePaymentIntent(f);if(F)throw Object.assign(new mn(F.message??"Failed to retrieve PayPal payment status.","api_error",{code:F.code}),{checkoutMethod:"paypal"});let m=Vs(X?.status);if(!X||m==="failed")throw Object.assign(new mn("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let d=typeof X.payment_method=="string"?X.payment_method:X.payment_method?.id,C=m;if(G.sessionId){let V=(await new La(A,{telemetry:!1}).getUnifiedCheckoutSession(G.sessionId)).data.session;if(V&&V.status!=="complete"){let b=await Po({billingApiUrl:A,sessionId:G.sessionId,session:V,telemetry:!1,tokenizedData:{id:d??X.id,type:"card",threeDSecureActionResultTokenId:X.id,isPaypal:!0}});if(b.type!=="success")throw Object.assign(new mn("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});C=b.result.status}}G.sessionId&&vo(G.sessionId),B?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),B?.performance({stage:"redirect_resume",durationMs:B.elapsed(Ce),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),B?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),ut("success"),await Qo(600),Rt(()=>Nt.current?.({status:C,paymentIntentId:X.id,paymentMethodId:d,checkoutMethod:"paypal"}))}catch(ct){let ye=Jo(ct),z=ye.checkoutMethod??"paypal",X=!!(ye.declineCode||ye.code?.toLowerCase().includes("declin"));if(B)B.performance({stage:"redirect_resume",durationMs:B.elapsed(Ce),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),X?B.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):B.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(X){let F=za(A,o,I);F.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),ea(F)}else Hi(A,o,I,"REDIRECT_RESUME_FAILED","redirect_resume");Oe(ye.message),Bt(ye.message),Rt(()=>Pn.current?.(ye)),_n(z,ye,{code:ye.code,declineCode:ye.declineCode}),ut("error"),await Qo(400)}finally{Ji(),bu(),ut(null),Bt(null),Ht(!1)}})())},[_n,s,A,o,I]);let zn=Tt(null),Rn=Yn(()=>Kt?ho(Kt):"",[Kt]),Qn=Tt(Kt);Qn.current=Kt,gr(()=>{Wt(e??"")},[e]),gr(()=>{Ut.current=!1,Oe(lt),Bt(null),gt(!1),ut(null)},[Rn,lt,e]);async function er(k,f,G){let B=za(A,o,I),Ce=new La(A,{telemetry:!1}),ct=!1;try{let ye=k.idempotencyKey===void 0?void 0:Ol(k.idempotencyKey),z=bi(f,G),X=Ci(f,G);z?.canonicalIdentity===G&&X&&X.canonicalIdentity===void 0&&(Ra(f,G,X.idempotencyKey),X={...X,canonicalIdentity:G});let F=ye??(X?.canonicalIdentity===G?X.idempotencyKey:void 0),m,d=!1;B.log({name:z?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let C=z?.sid??null,L=null,te,V,b=!1;if(C)try{L=await Ce.getUnifiedCheckoutSession(C,z?.nonce),z&&z.canonicalIdentity===void 0&&(ol(L.data.session,k)?(_a(f,G,C,z.nonce??L.data.session?.clientSecret),X&&X.canonicalIdentity===void 0&&(Ra(f,G,X.idempotencyKey),F??(F=X.idempotencyKey))):(ka(f,G),X=null,F=ye,C=null,L=null));let pt=L?.data.session?.status,qt=L?.data.session,Be=qt?.clientSecret||z?.nonce;if(C&&qt?.buyerIdentified===!1&&Be&&(V=lo(Ce,C,Be,k.account)),C&&L&&pt==="complete"){if(Si(C))return{sid:C,result:L};ka(f,G),C=null,L=null,d=!0}}catch{B.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),z?.canonicalIdentity===void 0?(ka(f,G),F=ye):Ia(f,G),C=null}if(!C){!ye&&(d||!F)&&(F=Ol(),m=F),F&&Ra(f,G,F);let pt=B.now(),qt=0;B.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let Be={...k,idempotencyKey:F,avsCheck:!!we,avsConfig:typeof we=="object"?we:void 0,checkoutType:"embedded_checkout",checkoutLayout:Xi(T,de)};Object.defineProperty(Be,du,{configurable:!1,enumerable:!1,value:{onAttempt:q=>{qt=Math.max(qt,q)}}});let fe=()=>{Ul(B,"session_create",pt,qt)},D=q=>{ql(B,q,"session_create",pt,qt)&&Ct({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_create"})};try{if(pu(Be)){let q=await Ce.createDetachedSession(Be);q.claimed.catch(()=>{}),L=q.shell,C=q.sessionId,V=q.claim;let Fe=B.now();B.log({name:"session.claim.started",stage:"session_claim",requestCategory:"session_claim"}),te=q.claimed.then(De=>{let kt=De.data.session?.id??q.sessionId;return kt&&_a(f,G,kt,De.data.session?.clientSecret??q.nonce),Ul(B,"session_claim",Fe),fe(),De},De=>{throw Ia(f,G),ql(B,De,"session_claim",Fe,0)&&Ct({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_claim"}),De}).finally(()=>ea(B)),te.catch(()=>{}),ct=!0,B.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),B.performance({stage:"session_shell",durationMs:B.now()-pt,durationMode:"machine",requestCategory:"session_create",attempt:qt,statusClass:"2xx",paymentMethodCategory:"card"})}else L=await Ce.createAndFetchSession(Be),fe()}catch(q){throw D(q),q}C=L.data.session?.id??C??"",C&&!te&&_a(f,G,C,L.data.session?.clientSecret)}let Z=L?.data.session;return!V&&C&&Z?.buyerIdentified===!1&&Z.clientSecret&&(V=lo(Ce,C,Z.clientSecret,k.account)),{sid:C??"",result:L,sdkGeneratedIdempotencyKey:m,...te?{claimed:te}:{},...V?{claim:V}:{},...b?{claimRequiresIdentity:!0}:{}}}finally{ct||ea(B)}}let Pt=Tt(er);Oo(()=>{Pt.current=er},[er]);let Cn=wn(async(k,f)=>{let G=Qn.current;if(!G)throw new mn("createSession is required to bootstrap checkout.","validation_error");let B=si(G,k),Ce=ho(B),ct=rl(B),ye=Ua.get(Ce);if(!ye){let F={canonicalIdentity:Ce,promise:Pt.current(B,ct,Ce),consumers:0,settled:!1};ye=F,Ua.set(Ce,F);let m=()=>{F.settled=!0,zl(Ce,F)};F.promise.then(m,m)}ye.consumers+=1;let z=!1,X=()=>{z||(z=!0,ye.consumers-=1,zl(Ce,ye))};f?.(X);try{let F=await ye.promise;zn.current=Ce,k&&(It(kn),un(Z=>js(Z,k)));let{sid:m,result:d,claimed:C,claim:L,claimRequiresIdentity:te}=F;if(Ln.current=L,vn(te===!0),Q(d),d.data.session&&Mt(d.data.session),m&&Wt(m),C){zt.current+=1;let Z=zt.current;Dt.current=C,J(!0),C.then(pt=>{zt.current===Z&&(Dt.current===C&&(Dt.current=null),Q(pt),pt.data.session&&Mt(pt.data.session),J(!1),vn(!1))},pt=>{zt.current===Z&&(Dt.current===C&&(Dt.current=null),J(!1),vn(!1),In(pt instanceof mn?pt:new mn(pt instanceof Error?pt.message:"Failed to create session","api_error")))})}else zt.current+=1,Dt.current=null,J(!1),vn(!1);let{flopay:V,paypalFlopay:b}=await Yi(d,{billingApiUrl:A,locale:s,telemetry:o});return On(V,b),N(!1),F}catch(F){throw zn.current===Ce&&(zn.current=null),F}finally{f||X()}},[kn,On,s,A,o]),Kn=Tt(vr);Kn.current=vr;let tr=Tt(Cn);tr.current=Cn;let En=wn(async k=>{if(!Su(k)||an)return{sessionId:K,session:H};Nn(!0);try{let f=await Cn(k);return{sessionId:f.sid,session:f.result.data.session??null}}finally{Nn(!1)}},[Cn,an,K,H]),Ve=wn(async k=>{let f=Ln.current;if(!f)return;let G=zt.current,B=await f(k);zt.current===G&&(Q(B),B.data.session&&Mt(B.data.session))},[]),tn=wn(async()=>{await Dt.current},[]),pn=wn(async()=>(await tn(),{proceed:!0}),[tn]);gr(()=>{let k=!1,f,G=++_e.current;ae(),In(null),rn(0);let B=()=>{k=!0,_e.current===G&&(_e.current+=1,ae())},Ce=Qn.current;if(Rn&&Ce)return Jn(Zn),N(!1),zn.current===Rn?B:(Mt($s(Ce,$)),(async()=>{let z=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),X=Zn==="auto"&&!Ut.current&&!z;X&&(Oe(null),Bt(null),ut("processing"));try{let F=await tr.current(void 0,L=>{f=L}),m=F.result.data.session??null;be.current=ki(F.result);let d=Gi(F.result),C=Si(F.sid||m?.id);if(!k&&X&&m&&!d&&!C){Ut.current=!0,await gu(Rn,F.sdkGeneratedIdempotencyKey,()=>Kn.current(m,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:F.result.autoProcessingError,initialAutoProcessingPending:F.result.autoProcessingPending,autoProcessingAttempted:F.result.autoProcessingAttempted,sessionId:F.sid||m.id}));return}!k&&X&&((d||C)&&(Ut.current=!0),ut(null),Bt(null))}catch(F){if(k)return;let m=fa(F);if(X&&m==="session_auto_completed"){Ut.current=!0,ut("success"),await Qo(600),k||(Rt(()=>{Nt.current?.({status:"succeeded"})}),ut(null),Bt(null));return}X&&(ut(null),Bt(null));let d=F instanceof mn?F:new mn(F instanceof Error?F.message:"Failed to create session","api_error");In(d)}finally{f?.(),f=void 0}})(),()=>{B(),f?.()});N(!0);async function ct(){let z=!1,X=null;try{let F=new La(A,{telemetry:!1}),m=await F.getUnifiedCheckoutSession(wt,t);if(X=m,k)return;Q(m);let d=m.data.session??null;if(Mt(d),!d)throw new mn("No session data returned","api_error");let C=d.checkoutMode;if(C==="setup")throw new mn("This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.","validation_error",{code:"InvalidCardSetupSurface",param:"sessionId"});if(d.status==="authorized"){N(!1),Rt(()=>{Nt.current?.(jr(d,wt)),bn.current?.(d.successUrl??"")});return}if(d.status==="complete"){N(!1),Rt(()=>{bn.current?.(d.successUrl??"")});return}if(d.status==="expired")throw ya(d);z=!0;let L=$??C??"full";Jn(L),zt.current+=1;let te=d.clientSecret||t;Ln.current=d.buyerIdentified===!1&&te?lo(F,wt,te,{...d.customer?.id?{userId:d.customer.id}:{}}):void 0,J(!1),vn(!1);let V=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),b=Gi(m);if(L==="auto"&&!Ut.current&&!V&&!b){Ut.current=!0;let Z=ye(m);try{if(await Kn.current(d,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>Z,sessionId:wt||d.id}),k)return;await Z,k||N(!1);return}catch{if(k)return;await Z,k||N(!1);return}}await ye(m),k||N(!1)}catch(F){if(k)return;let m=qs(F,z);if(z&&Ct({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"}),m){let{errorCode:C,stage:L,...te}=m;Hi(A,o,I,C,L,te)}if(m?.stage==="provider_load"&&($??X?.data.session?.checkoutMode??"full")==="full"&&Us(X,U,qe)){let C=vu({billingApiUrl:A,locale:s,telemetry:o});Ke.current=C,On(C,null),rn(1),N(!1);return}let d=F instanceof mn&&m?.stage!=="provider_load"?F:zs();d!==F&&Rt(()=>Pn.current?.(d)),In(d),N(!1)}}async function ye(z){let{flopay:X,paypalFlopay:F,...m}=await Yi(z,{billingApiUrl:A,locale:s,telemetry:o});be.current={publishableKey:m.publishableKey,paypalPublishableKey:m.paypalPublishableKey},On(X,F),rn(0)}return ct(),B},[$,Rn,Zn,yn,t,U,qe]);let cr=wn(async()=>{if(!x||cn!==1)return;let k=_e.current;rn(2);try{let{flopay:f,paypalFlopay:G}=await Yi(x,{billingApiUrl:A,locale:s,telemetry:o});if(_e.current!==k)return;ae(),On(f,G),rn(0)}catch(f){if(_e.current!==k)return;let{errorCode:G,stage:B,...Ce}=ai(f);Hi(A,o,I,G,B,Ce)}},[ae,On,s,cn,A,o,I,x]),Fr=wn(async()=>{if(!(dn||!H)){Ht(!0),Oe(null);try{await vr(H,{attempt3DS:!0,fallbackToFull:!0,sessionId:wt||H.id})}finally{Ht(!1)}}},[wt,dn,vr,H]),nr=Zi(x),dr=Gi(x),Tn=Yn(()=>{if(!(!x||!H||!x.data.stripe?.publishableKey))return{billingApiUrl:A}},[x,H,A]),An=!!(n&&!T&&de==="buttons"&&ue&&Zn==="full"),Dr=!!(wt&&(H?.vault?.html||Ur(H))),Un=Yn(()=>({session:H,loading:sr,error:fn,checkoutMode:gn,inlineSessionDraft:Kt,applyInlineSessionPatch:An?En:void 0,inlineSessionPatchProcessing:an,claimPending:vt,claimRequiresIdentity:hn,claimBuyerIdentity:Ve,waitForDataAttachment:tn}),[H,sr,fn,gn,Kt,An,En,an,vt,hn,Ve,tn]),Nr=!!n&&de==="buttons"&&!dr&&!Dr&&(!Me||!Tn),Jt=on?re(yr,{status:on,errorMessage:jn,authorized:Gt}):null;if(sr&&!Dr){if(l)return en(hr,{children:[l,Jt]});if(de==="buttons"){let k=Te?.buttonsLayout?.cardButton?.borderRadius??Te?.appearance.variables?.borderRadius??8,f=G=>re("div",{style:{height:G,borderRadius:k,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return en(hr,{children:[en("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[U&&f(So),qe&&(S||W)&&f(So),qe&&f(So),re("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),Jt]})}return en(hr,{children:[en("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[re("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),re("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),Jt]})}return fn?p?re(ar.Provider,{value:Un,children:p(fn)}):re(ar.Provider,{value:Un,children:re("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:fn.message})}):Nr?en(hr,{children:[re(ar.Provider,{value:Un,children:re(Iu,{onButtonClick:$e,showPayPal:U,showStripe:qe,showApplePay:S,showGooglePay:W,theme:Le,buttonsTheme:Se,buttonsStyles:Re,cardButtonContent:Ge,cardBackButtonContent:St,cardTitleContent:tt})}),Jt]}):dr&&H&&nr?en(hr,{children:[re(ar.Provider,{value:Un,children:en("div",{className:st,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Ae&&re(fo,{icon:!1,children:Ae}),$n==="retrying"&&re("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),$n==="exhausted"&&en("div",{role:"alert",children:[re("div",{children:"PayPal is temporarily unavailable. Please try again."}),re("button",{type:"button",onClick:Gr,children:"Retry PayPal"})]}),$n!=="exhausted"&&re("div",{"aria-hidden":$n==="retrying"?!0:void 0,style:$n==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:re(tl,{sessionId:wt,nonce:H.clientSecret||void 0,billingApiUrl:A,email:H.customer?.email||Kt?.account?.email,billingName:[H.customer?.firstName,H.customer?.lastName].filter(Boolean).join(" ")||[Kt?.account?.firstName,Kt?.account?.lastName].filter(Boolean).join(" ")||void 0,onBuyerIdentityReady:Ve,clientId:nr.clientId,environment:nr.environment,currency:(H.currency??"usd").toUpperCase(),isSubscription:H.mode==="subscription",providerObjectType:nr.providerObjectType,approvalPresentation:nr.approvalPresentation,onComplete:v,onErrorChange:Oe,onDecline:y,onButtonClick:$e,runBeforeButtonClick:pn,onInitializationStateChange:Br,allowAutomaticRetry:Yt===0,session:H,telemetry:o,telemetryContext:I,onInstrument:xt,debug:Y},`${R}:paypal-init-${Yt}`)})]})}),Jt]}):(!Me||!Tn)&&!(Dr&&gn==="full")?re(hr,{children:Jt}):gn==="confirm"?en(hr,{children:[re(ar.Provider,{value:Un,children:re(Ea,{flopay:Me,paypalFlopay:le,options:Tn??{billingApiUrl:A},onInstrument:xt,children:en("div",{className:st,children:[Ae&&re("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:Ae}),ie?ie({onConfirm:Fr,isProcessing:dn}):re("button",{type:"button",onClick:Fr,disabled:dn,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:dn?"not-allowed":"pointer",opacity:dn?.6:1},children:dn?"Processing...":Ee??"Confirm Purchase"})]})},R)}),Jt]}):en(hr,{children:[re(ar.Provider,{value:Un,children:en(Ea,{flopay:Me,paypalFlopay:le,options:Tn??{billingApiUrl:A},onInstrument:xt,children:[cn===1&&re("button",{type:"button",onClick:cr,children:"Retry payment methods"}),T?en(hr,{children:[Ae&&re("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:Ae}),re(wu,{sessionId:wt,nonce:H?.clientSecret||void 0,billingApiUrl:A,session:H,submitLabel:he,children:T})]}):re(Vi,{sessionId:wt,nonce:H?.clientSecret||void 0,telemetry:o,email:H?.customer?.email||Kt?.account?.email,userId:H?.customer?.id||Kt?.account?.userId,firstName:H?.customer?.firstName||Kt?.account?.firstName,lastName:H?.customer?.lastName||Kt?.account?.lastName,totalAmount:H?Math.round(uu(H).total*100):0,currency:H?.currency?.toLowerCase()??"usd",onComplete:v,onError:g,onDecline:y,error:Ae,onErrorChange:Oe,showPayPal:U,showStripe:qe,enabledPaymentMethods:cn?[]:ge??x?.data.stripe?.enabledPaymentMethods??H?.gateways?.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:x?.data.stripe?.enabledPaymentMethodCountries,showApplePay:S,showGooglePay:W,layout:de,theme:Le,buttonsTheme:Se,buttonsStyles:Re,appearance:dt,cardButtonContent:Ge,cardBackButtonContent:St,cardTitleContent:tt,onButtonClick:$e,onBeforeButtonClick:ue,onBuyerIdentityReady:Ve,enableAVS:we,...Xe?{cardFieldOrder:Xe}:{},...ee?{cardPreFormSlot:ee}:{},avsLayout:Ie,country:H?.customer?.country,city:H?.customer?.city,state:H?.customer?.state,onCountryChange:_,onZipChange:M,avsCheck:!!we,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:Xi(T,de),className:st,submitLabel:he,directPaypal:Zi(x),isSubscription:H?.mode==="subscription",session:H,dataAttachmentPending:vt,dataAttachmentRequiresIdentity:hn,debug:Y})]},R)}),Jt]})}function wu({sessionId:e,nonce:t,billingApiUrl:n,session:r,submitLabel:o,children:i}){return re(hr,{children:Wi.Children.map(i,s=>{if(!Wi.isValidElement(s))return s;let l=s.props,p={};return l.sessionId||(p.sessionId=e),!l.nonce&&t&&(p.nonce=t),l.billingApiUrl||(p.billingApiUrl=n),l.submitLabel===void 0&&o!==void 0&&(p.submitLabel=o),r?.customer&&(l.email||(p.email=r.customer.email),l.userId||(p.userId=r.customer.id),l.firstName||(p.firstName=r.customer.firstName),l.lastName||(p.lastName=r.customer.lastName)),Object.keys(p).length===0?s:Wi.cloneElement(s,p)})})}function Iu({onButtonClick:e,showPayPal:t,showStripe:n=!0,showApplePay:r,showGooglePay:o,theme:i,buttonsTheme:s,buttonsStyles:l,cardButtonContent:p,cardBackButtonContent:v,cardTitleContent:g}){let[h,y]=Ot(!1),_=Yn(()=>Wl(i),[i]),M=Yn(()=>{let S=_?.buttonsLayout??yu(s);return l?{...S,...l,cardButton:{...S.cardButton,...l.cardButton},cardFormContainer:{...S.cardFormContainer,...l.cardFormContainer},backButton:{...S.backButton,...l.backButton},backButtonIcon:{...S.backButtonIcon,...l.backButtonIcon},submitButton:{...S.submitButton,...l.submitButton},title:{...S.title,...l.title}}:S},[_,s,l]),U=_?.buttonsLayout?.cardButton?.borderRadius??_?.appearance.variables?.borderRadius??8,qe=S=>re("div",{style:{height:S,borderRadius:U,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),ge=p===void 0?{boxSizing:"border-box",height:So,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(h){let S=M.cardInputBorder??"#e5e7eb",W=M.cardInputBackground??"white",Y=oo(v),de=oo(g);return en("div",{style:{backgroundColor:M.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",...M.cardFormContainer},children:[en("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[en("button",{type:"button",onClick:()=>y(!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",...M.backButton},children:[re("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...M.backButtonIcon},children:re("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:re("path",{d:"M15 18l-6-6 6-6"})})}),re(io,{content:v})]}),de?re("div",{style:{flex:1}}):re("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...M.title},children:re(Uo,{content:g})})]}),re("div",{style:{backgroundColor:W,border:`1px solid ${S}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:re("div",{style:{width:"60%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),en("div",{style:{display:"flex"},children:[re("div",{style:{flex:1,backgroundColor:W,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${S}`,borderLeft:`1px solid ${S}`,borderBottomLeftRadius:8,padding:12,height:45},children:re("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),re("div",{style:{flex:1,backgroundColor:W,borderTop:"none",borderRight:`1px solid ${S}`,borderBottom:`1px solid ${S}`,borderLeft:`1px solid ${S}`,borderBottomRightRadius:8,padding:12,height:45},children:re("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),re("div",{style:{backgroundColor:W,border:`1px solid ${S}`,borderRadius:8,marginTop:8,padding:12,height:45},children:re("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),re("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",...M.submitButton,opacity:.5}}),re("style",{children:`
|
|
33
|
+
`}),Do&&br&&ze("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:Le?-2:0},children:[ze("button",{type:"button",onClick:Tn,style:{display:"inline-flex",alignItems:"center",gap:ni?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:v.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...v.backButton},"aria-label":"Back to payment methods",children:[c("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...v.backButtonIcon},children:c("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:c("path",{d:"M15 18l-6-6 6-6"})})}),c(lo,{content:ye})]}),xs?c("div",{style:{flex:1}}):c("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:v.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...v.title},children:c(jo,{content:we})})]}),!Do&&!xs&&c("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:ri,order:Le?-3:0,...v.title},children:c(jo,{content:we})}),Le&&U&&c("div",{style:{order:-2,width:"100%"},children:U}),Le&&Se&&ze("div",{"data-testid":"flopay-vault-identity-fields",style:{order:-1,marginTop:"0.5rem"},children:[c("div",{style:{backgroundColor:ro,border:`1px solid ${Xn(ma)}`,borderRadius:Vt,padding:"10px"},children:c("input",{className:"flopay-shared-input",id:"flopay-buyer-email",name:"email",type:"email",autoComplete:"email","aria-label":"Email address",placeholder:"Email address",value:rn,onChange:a=>{yt("email"),wn.current=a.target.value,wt(a.target.value)},onPointerDown:()=>yt("email"),onKeyDown:()=>yt("email"),onBlur:()=>{En("email")&&Rn(!0),Ge||Ha()},disabled:Ce,required:!0,"aria-invalid":ma||void 0,"aria-describedby":ma?"flopay-buyer-email-error":void 0,"data-testid":"flopay-email",style:{width:"100%",border:"none",outline:"none",background:"transparent",...oi}})}),ma&&c("div",{id:"flopay-buyer-email-error",role:"alert","data-testid":"flopay-email-error",style:Lo,children:pe.empty?"Email address is required":"Enter a valid email address"})]}),te&&c("div",{style:{order:Le?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let a=O,b=(W=!1)=>({backgroundColor:ro,border:`1px solid ${Xn(W)}`,borderRadius:Vt,marginTop:"0.5rem",padding:"10px"}),j=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...oi}),Be=Td(a);return ze(Yr,{children:[rt(te.address_line_1,a)&&ze(Yr,{children:[c("div",{style:b(qt("line1")),children:c("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:mn,onChange:W=>{yt("line1"),It.current.addressLine1=!0,yn.current=W.target.value,_n(W.target.value)},onPointerDown:()=>yt("line1"),onKeyDown:()=>yt("line1"),onBlur:()=>Yn("line1"),disabled:Ce,required:!0,"aria-invalid":qt("line1")||void 0,"aria-describedby":qt("line1")?"flopay-billing-address-line1-error":void 0,"data-testid":"flopay-address-line1",style:j()})}),qt("line1")&&c("div",{id:"flopay-billing-address-line1-error",role:"alert","data-testid":"flopay-address-line1-error",style:Lo,children:"Street address is required"})]}),rt(te.address_line_2,a)&&c("div",{style:b(),children:c("input",{className:"flopay-shared-input",id:"flopay-billing-address-line2",name:"billing-address-line2",placeholder:"Apt, Suite, Unit (optional)",autoComplete:"billing address-line2",value:Fn,onChange:W=>{It.current.addressLine2=!0,Ut.current=W.target.value,Dn(W.target.value)},disabled:Ce,"data-testid":"flopay-address-line2",style:j()})}),(rt(te.city,a)||rt(te.state,a))&&ze("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[rt(te.city,a)&&c("div",{style:{flex:1,backgroundColor:ro,borderTop:`1px solid ${Xn(qt("city"))}`,borderRight:`1px solid ${Xn(qt("city"))}`,borderBottom:`1px solid ${Xn(qt("city"))}`,borderLeft:`1px solid ${Xn(qt("city"))}`,padding:"10px",borderTopLeftRadius:Vt,borderBottomLeftRadius:Vt,...rt(te.state,a)?{borderRight:"none",borderTopRightRadius:0,borderBottomRightRadius:0}:{borderRadius:Vt}},children:c("input",{className:"flopay-shared-input",id:"flopay-billing-city",name:"billing-city",placeholder:"City",autoComplete:"billing address-level2",value:Jt,onChange:W=>{yt("city"),It.current.city=!0,At.current=W.target.value,je(W.target.value)},onPointerDown:()=>yt("city"),onKeyDown:()=>yt("city"),onBlur:()=>Yn("city"),disabled:Ce,required:!0,"aria-invalid":qt("city")||void 0,"aria-describedby":qt("city")?"flopay-billing-city-error":void 0,"data-testid":"flopay-city",style:j()})}),rt(te.state,a)&&c("div",{style:{flex:1,backgroundColor:ro,borderTop:`1px solid ${Xn(qt("state"))}`,borderRight:`1px solid ${Xn(qt("state"))}`,borderBottom:`1px solid ${Xn(qt("state"))}`,borderLeft:`1px solid ${Xn(qt("state"))}`,padding:"10px",borderTopRightRadius:Vt,borderBottomRightRadius:Vt,...rt(te.city,a)?{borderTopLeftRadius:0,borderBottomLeftRadius:0,borderLeft:`1px solid ${Xn(qt("state")||qt("city"))}`}:{borderRadius:Vt}},children:Be?ze("select",{id:"flopay-billing-state",name:"billing-state",value:He,onChange:W=>{yt("state"),It.current.state=!0,Sn.current=W.target.value,St(W.target.value)},onPointerDown:()=>yt("state"),onKeyDown:()=>yt("state"),onBlur:()=>Yn("state"),disabled:Ce,autoComplete:"billing address-level1",required:!0,"aria-invalid":qt("state")||void 0,"aria-describedby":qt("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:{...j(),cursor:"pointer"},children:[c("option",{value:"",children:Mi(a)}),Be.map(W=>c("option",{value:W.code,children:W.name},W.code))]}):c("input",{className:"flopay-shared-input",id:"flopay-billing-state",name:"billing-state",placeholder:Mi(a),autoComplete:"billing address-level1",value:He,onChange:W=>{yt("state"),It.current.state=!0,Sn.current=W.target.value,St(W.target.value)},onPointerDown:()=>yt("state"),onKeyDown:()=>yt("state"),onBlur:()=>Yn("state"),disabled:Ce,required:!0,"aria-invalid":qt("state")||void 0,"aria-describedby":qt("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:j()})})]}),qt("city")&&c("div",{id:"flopay-billing-city-error",role:"alert","data-testid":"flopay-city-error",style:Lo,children:"City is required"}),qt("state")&&ze("div",{id:"flopay-billing-state-error",role:"alert","data-testid":"flopay-state-error",style:Lo,children:[Mi(a)," is required"]}),(rt(te.country,a)||rt(te.postal_code,a))&&ze("div",{style:{display:"flex",flexDirection:V==="column"?"column":"row",gap:V==="column"?"0.5rem":"0",marginTop:"0.5rem"},children:[rt(te.country,a)&&c("div",{style:{flex:V==="row"?1:void 0,backgroundColor:ro,borderTop:`1px solid ${No}`,borderRight:`1px solid ${No}`,borderBottom:`1px solid ${No}`,borderLeft:`1px solid ${No}`,padding:"10px",...V==="row"&&rt(te.postal_code,a)?{borderRadius:"0",borderTopLeftRadius:Vt,borderBottomLeftRadius:Vt,borderRight:"none"}:{borderRadius:Vt}},children:c("select",{id:"flopay-billing-country",name:"billing-country",value:O,onChange:W=>{It.current.country=!0,zt.current=W.target.value,Ot(W.target.value),Ye?.(W.target.value),Sn.current="",St("")},disabled:Ce,autoComplete:"billing country","data-testid":"flopay-country",style:{...j(),cursor:"pointer"},children:kd.map(W=>ze("option",{value:W.code,children:[W.flag," ",W.name]},W.code))})}),rt(te.postal_code,a)&&c("div",{style:{flex:V==="row"?1:void 0,backgroundColor:ro,border:`1px solid ${uc}`,padding:"10px",...V==="row"&&rt(te.country,a)?{borderRadius:"0",borderTopRightRadius:Vt,borderBottomRightRadius:Vt}:{borderRadius:Vt}},children:c("input",{className:"flopay-shared-input",id:"flopay-billing-postal-code",name:"billing-postal-code",placeholder:qi(O),autoComplete:"billing postal-code",value:Cn,onChange:W=>{yt("zip"),It.current.zip=!0,Tt.current=W.target.value,pn(W.target.value),re?.(W.target.value)},onPointerDown:()=>yt("zip"),onKeyDown:()=>yt("zip"),onBlur:()=>{En("zip")&&or(!0)},disabled:Ce,required:sn.required,"aria-invalid":ya||void 0,"aria-describedby":ya?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:j()})})]}),ya&&c("div",{id:"flopay-billing-postal-code-error",role:"alert","data-testid":"flopay-zip-error",style:Lo,children:sn.empty?`${qi(a)} is required`:lu(a)})]})})()}),Le&&gc,P&&c(ho,{margin:"0.75rem 0",styleOverride:v.errorBanner,children:P})]}),fa={margin:0,padding:"6px 8px",background:"#eef2ff",border:"1px solid #c7d2fe",borderRadius:6,color:"#111827",font:"11px/1.35 ui-monospace, SFMono-Regular, Menlo, monospace",whiteSpace:"pre-wrap",wordBreak:"break-word"},Ns=a=>H?!S||!mr?c("pre",{"data-testid":a,style:fa,children:"FloPay/DirectPayPal-debug - not enabled"}):c("pre",{"data-testid":a,style:fa,children:["FloPay/DirectPayPal-debug (parent gate)",` showPayPal=${S}`,` directPaypalConfigured=${mr}`,` inAppBrowserDetected=${String(da)}`,` shouldRenderDirectPayPal=${xo}`,` shouldRenderStripePayPal=${Mo}`,` hasPaypalStripeInstance=${!!tn}`].join(`
|
|
34
|
+
`)}):null,Ls=a=>H?!G||!ht?c("pre",{"data-testid":a,style:fa,children:"FloPay/Stripe-debug - not enabled"}):c("pre",{"data-testid":a,style:fa,children:["FloPay/Stripe-debug (parent gate)",` showStripe=${G}`,` currency=${Me}`,` amountInCents=${qn}`,` enabledPaymentMethods: ${JSON.stringify(X??[])}`,` enabledPaymentMethodsProvided=${To}`,` hasEnabledMethods=${sa}`,` expressMethods: ${JSON.stringify(la)}`,` walletExpressMethods: ${JSON.stringify(to)}`,` paymentElementMethods: ${JSON.stringify(Ao)}`,` paymentElementMethodsForCurrency: ${JSON.stringify(ca)}`,` hasStripeInstance=${!!ht}`,` shouldRenderWallets=${no}`,` shouldRenderPaymentElement=${Bo}`].join(`
|
|
35
|
+
`)}):null,Os=We==="apm-expanding"||We==="apm-form"||We==="apm-collapsing",ao;We==="apm-expanding"?ao=kl:We==="apm-collapsing"&&(ao=_l);let ga=ln?Ul(Ya,ln):null;if(ve==="buttons"){let a=We==="buttons"||We==="expanding"||We==="apm-expanding",b=We==="expanding"||We==="card"||We==="collapsing",j=De===void 0?{boxSizing:"border-box",height:La,padding:"0 1rem"}:{padding:"0.9rem 1rem"},Be;We==="expanding"||We==="apm-expanding"?Be=nu:(We==="collapsing"||We==="apm-collapsing")&&(Be=tu);let W;return We==="expanding"?W=kl:We==="collapsing"&&(W=_l),ze("form",{onSubmit:Qa,className:w,noValidate:!0,style:{position:"relative"},children:[c(Ui,{}),Un&&c(fr,{status:Un,errorMessage:P,authorized:Kn}),ze("div",{style:{display:"grid"},children:[ze("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!a&&!Be?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!a&&!Be?ou:{},...Be?{animation:Be,pointerEvents:"none"}:{}},children:[Ns("flopay-direct-paypal-gate-debug"),Ls("flopay-stripe-gate-debug"),xo&&ke&&ze(Yr,{children:[z&&c("div",{"data-testid":"flopay-paypal-direct-retry-notice",style:{padding:"8px 10px",background:"#fef3c7",border:"1px solid #fcd34d",borderRadius:6,color:"#78350f",fontSize:13,lineHeight:1.4},children:"Please confirm your PayPal payment to complete checkout."}),c(ka,{sessionId:e,nonce:t,billingApiUrl:N,email:y.email,billingName:k||void 0,onBuyerIdentityReady:g,clientId:ke.clientId,environment:ke.environment,currency:Me.toUpperCase(),isSubscription:Ee,providerObjectType:B,approvalPresentation:ua==="popup"?void 0:ua,onTokenizedBody:An,onComplete:s,onErrorChange:he,onDecline:p,onTechnicalFailure:eo,onButtonClick:Z,runBeforeButtonClick:lr,isProcessing:Ce,onLoadStateChange:Ja,onInitializationStateChange:Xa,session:u,existingOrderId:z?.orderId,debug:H},z?.orderId??"fresh")]}),Mo&&c(Gr,{stripe:tn,options:cs,children:c(Al,{sessionId:e,nonce:t,email:y.email,billingName:k||void 0,onBuyerIdentityReady:g,billingApiUrl:N,onTokenizedBody:An,onErrorChange:he,isProcessing:Ce,onButtonClick:Z,onDecline:p,onTechnicalFailure:eo,runBeforeButtonClick:lr,onLoadStateChange:fs,placeholderBorderRadius:jr})}),no?c(Gr,{stripe:ht,options:ls,children:c(xl,{sessionId:e,nonce:t,email:y.email,billingName:k||void 0,onBuyerIdentityReady:g,billingApiUrl:N,intentKind:xe>0?"payment":"setup",expressMethods:to,onTokenizedBody:An,onErrorChange:he,onButtonClick:Z,onDecline:p,onTechnicalFailure:eo,runBeforeButtonClick:lr,onLoadStateChange:hs,placeholderBorderRadius:jr})}):null,!no&&Ss?c("div",{style:{height:La,borderRadius:jr,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,Bo&&c(Ml,{sessionId:e,nonce:t,email:y.email,billingName:[y.firstName,y.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:g,billingApiUrl:N,paymentElementMethods:ca,stripeInstance:ht,paymentElementBaseOptions:Ya,onTokenizedBody:An,onErrorChange:he,onButtonClick:Z,onDecline:p,runBeforeButtonClick:lr,onLoadStateChange:Ps,isProcessing:Ce,submitButtonColor:$r,submitButtonBorderRadius:Vt,submitButtonStyle:v.submitButton,onExpandApm:Tr,expandedApmMethod:ln,themeId:Ue,buttonAppearance:{backgroundColor:v.cardButton?.backgroundColor,borderColor:v.cardInputBorder,textColor:v.cardButton?.color,borderRadius:jr}}),Le&&c("button",{type:"button",onClick:async()=>{Ce||!(await lr("card")).proceed||(Z?.("card"),Xr())},disabled:Ce,style:{width:"100%",...j,...v.cardButton,...Yi({themeBundle:I,resolvedPrimaryColor:$r,resolvedBorderRadius:Vt,submitButtonStyle:v.submitButton,explicitPrimaryColor:xn?.colorPrimary}),fontSize:v.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:Ce?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",transition:"background-color 0.15s, border-color 0.2s, box-shadow 0.2s, transform 0.1s",position:"relative",opacity:Ce?.6:1},onMouseEnter:st=>{!Ce&&(I||xn?.colorPrimary)&&(st.currentTarget.style.backgroundColor=yc)},onMouseLeave:st=>{(I||xn?.colorPrimary)&&(st.currentTarget.style.backgroundColor=$r)},onMouseDown:st=>{st.currentTarget.style.transform="scale(0.985)"},onMouseUp:st=>{st.currentTarget.style.transform="scale(1)"},children:c(so,{content:De})}),P&&We==="buttons"&&c(ho,{margin:"0.25rem 0",styleOverride:v.errorBanner,children:P})]}),Le&&b&&c("div",{style:{gridArea:"1 / 1",...W?{animation:W}:{},...We==="collapsing"?{pointerEvents:"none"}:{}},children:Ds}),G&&Os&&ln&&ga&&ht&&c("div",{style:{gridArea:"1 / 1",...ao?{animation:ao}:{},...We==="apm-collapsing"?{pointerEvents:"none"}:{}},children:ze("div",{style:{backgroundColor:ti,borderRadius:ii,...Oo,padding:ai},children:[ze("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[ze("button",{type:"button","data-testid":"flopay-apm-back-button",onClick:In,style:{display:"inline-flex",alignItems:"center",gap:ni?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:v.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...v.backButton},"aria-label":"Back to payment methods",children:[c("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...v.backButtonIcon},children:c("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:c("path",{d:"M15 18l-6-6 6-6"})})}),c(lo,{content:ye})]}),c("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:v.titleFontSize??"1.05rem",color:ri,paddingRight:80,...v.title},children:`Pay with ${Jr(ln)}`})]}),c(Gr,{stripe:ht,options:ga,children:c(Ki,{method:ln,sessionId:e,nonce:t,email:y.email,billingName:[y.firstName,y.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:g,billingApiUrl:N,onTokenizedBody:An,onErrorChange:he,onDecline:p,onCancel:In,runBeforeButtonClick:lr,onButtonClick:Z,isProcessing:Ce,submitButtonColor:$r,submitButtonBorderRadius:Vt,submitButtonStyle:v.submitButton,errorText:P})},ln)]})})]})]})}return Os&&ln&&ga&&ht&&G?ze("form",{onSubmit:Qa,className:w,noValidate:!0,style:{position:"relative"},children:[c(Ui,{}),Un&&c(fr,{status:Un,errorMessage:P,authorized:Kn}),c("div",{style:{...ao?{animation:ao}:{},...We==="apm-collapsing"?{pointerEvents:"none"}:{}},children:ze("div",{style:{backgroundColor:ti,borderRadius:ii,...Oo,padding:ai},children:[ze("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[ze("button",{type:"button","data-testid":"flopay-apm-back-button-default",onClick:In,style:{display:"inline-flex",alignItems:"center",gap:ni?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:v.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...v.backButton},"aria-label":"Back to payment methods",children:[c("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...v.backButtonIcon},children:c("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:c("path",{d:"M15 18l-6-6 6-6"})})}),c(lo,{content:ye})]}),c("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:v.titleFontSize??"1.05rem",color:ri,paddingRight:80,...v.title},children:`Pay with ${Jr(ln)}`})]}),c(Gr,{stripe:ht,options:ga,children:c(Ki,{method:ln,sessionId:e,nonce:t,email:y.email,billingName:[y.firstName,y.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:g,billingApiUrl:N,onTokenizedBody:An,onErrorChange:he,onDecline:p,onCancel:In,runBeforeButtonClick:lr,onButtonClick:Z,isProcessing:Ce,submitButtonColor:$r,submitButtonBorderRadius:Vt,submitButtonStyle:v.submitButton,errorText:P})},ln)]})})]}):ze("form",{onSubmit:Qa,className:w,noValidate:!0,style:{position:"relative"},children:[c(Ui,{}),Un&&c(fr,{status:Un,errorMessage:P,authorized:Kn}),ze("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Ns("flopay-direct-paypal-gate-debug-default"),Ls("flopay-stripe-gate-debug-default"),xo&&ke&&ze(Yr,{children:[z&&c("div",{"data-testid":"flopay-paypal-direct-retry-notice-default",style:{padding:"8px 10px",background:"#fef3c7",border:"1px solid #fcd34d",borderRadius:6,color:"#78350f",fontSize:13,lineHeight:1.4},children:"Please confirm your PayPal payment to complete checkout."}),c(ka,{sessionId:e,nonce:t,billingApiUrl:N,email:y.email,billingName:k||void 0,onBuyerIdentityReady:g,clientId:ke.clientId,environment:ke.environment,currency:Me.toUpperCase(),isSubscription:Ee,providerObjectType:B,approvalPresentation:ua==="popup"?void 0:ua,onTokenizedBody:An,onComplete:s,onErrorChange:he,onDecline:p,onTechnicalFailure:eo,onButtonClick:Z,runBeforeButtonClick:lr,isProcessing:Ce,onLoadStateChange:Ja,onInitializationStateChange:Xa,session:u,existingOrderId:z?.orderId,debug:H},z?.orderId??"fresh")]}),Mo&&c(Gr,{stripe:tn,options:cs,children:c(Al,{sessionId:e,nonce:t,email:y.email,billingName:k||void 0,onBuyerIdentityReady:g,billingApiUrl:N,onTokenizedBody:An,onErrorChange:he,isProcessing:Ce,onButtonClick:Z,onDecline:p,onTechnicalFailure:eo,runBeforeButtonClick:lr,onLoadStateChange:fs,placeholderBorderRadius:jr})}),no&&c(Gr,{stripe:ht,options:ls,children:c(xl,{sessionId:e,nonce:t,email:y.email,billingName:k||void 0,onBuyerIdentityReady:g,billingApiUrl:N,intentKind:xe>0?"payment":"setup",expressMethods:to,onTokenizedBody:An,onErrorChange:he,onButtonClick:Z,onDecline:p,onTechnicalFailure:eo,runBeforeButtonClick:lr,onLoadStateChange:hs,placeholderBorderRadius:jr})}),Bo&&c(Ml,{sessionId:e,nonce:t,email:y.email,billingName:[y.firstName,y.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:N,paymentElementMethods:ca,stripeInstance:ht,paymentElementBaseOptions:Ya,onTokenizedBody:An,onErrorChange:he,onButtonClick:Z,onDecline:p,runBeforeButtonClick:lr,onLoadStateChange:Ps,isProcessing:Ce,submitButtonColor:$r,submitButtonBorderRadius:Vt,submitButtonStyle:v.submitButton,themeId:Ue,onExpandApm:Tr,expandedApmMethod:ln,buttonAppearance:{backgroundColor:v.cardButton?.backgroundColor,borderColor:v.cardInputBorder,textColor:v.cardButton?.color,borderRadius:jr}})]}),Le&&(sc||ic||lc)&&ze("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem",margin:"0.5rem 0 0.75rem",color:"#999",fontSize:"0.85rem"},children:[c("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}}),c("span",{children:"or pay with card"}),c("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}})]}),Le&&Ds]})}import{Fragment as vr,jsx as oe,jsxs as en}from"react/jsx-runtime";var ko=44,rs="flopay_checkout_saved_payment_resume",$a=new Map,qa=new Map;function jl(e,t){t.settled&&t.consumers===0&&$a.get(e)===t&&$a.delete(e)}function Cu(e,t,n){let r=qa.get(e);if(r&&(!r.sdkGeneratedIdempotencyKey||!t||r.sdkGeneratedIdempotencyKey===t))return r.attempt;let o=n(),i={attempt:o,sdkGeneratedIdempotencyKey:t};qa.set(e,i);let s=()=>{qa.get(e)===i&&qa.delete(e)};return o.then(s,s),o}function na(e){return new Promise(t=>setTimeout(t,e))}function ja(e,t,n){let r=wa({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:Jl,enabled:t!==!1});return r.beginCheckout(n),r}function ra(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function Zi(e,t,n,r,o,i){let s=ja(e,t,n);s.error({errorCode:r,stage:o,paymentMethodCategory:"unknown",...i,...o==="session_read"?{requestCategory:"session_read"}:{}}),ra(s)}function $l(e,t,n,r){e.log({name:t==="session_claim"?"session.claim.completed":"session.request.completed",stage:t,requestCategory:t,statusClass:"2xx"}),e.performance({stage:t,durationMs:Math.max(0,e.now()-n),durationMode:"machine",requestCategory:t,...r===void 0?{}:{attempt:r},statusClass:"2xx"})}function Kl(e,t,n,r,o){let i=Gl(t,"CHECKOUT_SESSION_CREATE_FAILED","unknown");return e.performance({stage:n,durationMs:Math.max(0,e.now()-r),durationMode:"machine",requestCategory:n,attempt:o,statusClass:i.statusClass}),t instanceof bn&&t.code==="session_auto_completed"?!1:t instanceof bn&&t.type==="validation_error"?(e.terminal({outcome:"validation_rejected",stage:n,paymentMethodCategory:"unknown"}),!1):i.statusClass==="4xx"?(e.terminal({outcome:"validation_rejected",stage:n,paymentMethodCategory:"unknown",requestCategory:n,statusClass:"4xx"}),!1):(e.error({...i,stage:n,paymentMethodCategory:"unknown",requestCategory:n}),!0)}function Xl(e,t){let n=e?.data.paypal?.publishableKey;if(n)return{clientId:n,environment:e?.data.paypal?.environment,providerObjectType:e?.data.paypal?.providerObjectType,approvalPresentation:e?.data.paypal?.approvalPresentation,...t?{existingOrderId:t}:{}}}function Qi(e){return!e||e.data.stripe?.publishableKey?!1:!!Xl(e)?.clientId}var Su={name:"provider_unavailable",initialize:()=>Promise.resolve(),getRawProvider:()=>null,destroy:()=>{}};function wu(e){return new yu(Su,{publishableKey:"provider_unavailable",...e})}async function es(e,t){let{publishableKey:n,paypalPublishableKey:r}=Ai(e);return{...await xi({publishableKey:n,paypalPublishableKey:r,...t}),publishableKey:n,paypalPublishableKey:r}}function os(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function Iu(){if(!os())return null;try{let e=window.sessionStorage.getItem(rs);return e?JSON.parse(e):null}catch{return null}}function Vl(e){if(os())try{window.sessionStorage.setItem(rs,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function ts(){if(os())try{window.sessionStorage.removeItem(rs)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}function ku(){if(typeof window>"u")return;let e=new URL(window.location.href),t=["payment_intent","payment_intent_client_secret","redirect_status"],n=!1;for(let r of t)e.searchParams.has(r)&&(e.searchParams.delete(r),n=!0);n&&window.history.replaceState(window.history.state,"",e.toString())}function Hl(e){if(typeof window>"u")return;let t=new URL(window.location.href);t.searchParams.set("mode",e),window.history.replaceState(window.history.state,"",t.toString())}function ns(e,t){return e?"custom_layout":t==="buttons"?"buttons_layout":"default_layout"}function _u(e,t){return e?"unknown":t==="buttons"?"buttons":"embedded"}function Wl(e){return e?.gateways?.stripe?"stripe":e?.gateways?.paypal?"paypal":void 0}function Ru(e){return e?e.account&&Object.keys(e.account).length>0||e.couponCodes!==void 0||e.checkoutMetadata!==void 0||e.tagsData!==void 0||e.utmMetadata!==void 0:!1}function as({sessionId:e,nonce:t,createSession:n,billingApiUrl:r,telemetry:o,appearance:i,locale:s,loading:l,error:p,onComplete:f,onError:C,onInstrument:h,onDecline:m,onCountryChange:w,onZipChange:_,showPayPal:ae=!0,showStripe:Y=!0,enabledPaymentMethods:Pe,showApplePay:S=!0,showGooglePay:G=!0,debug:X=!1,layout:ce,theme:Te,buttonsTheme:Fe,buttonsStyles:ve,cardButtonContent:Ue,cardBackButtonContent:bt,cardTitleContent:ot,showSecurityFooter:$e,onButtonClick:De,onBeforeButtonClick:ye,enableAVS:we,cardFieldOrder:Qe,cardPreFormSlot:Z,avsLayout:Ie,submitLabel:be,className:ct,initialErrorMessage:dt=null,initialPayPalOrderId:U,children:V,checkoutMode:de,confirmLabel:fe,renderConfirmButton:ut,onSessionCompleted:Ne}){let x=vu(r),at=tr(()=>Yl(Te),[Te]),Ye=i??at?.appearance,re=n?"embedded_checkout":"standard_checkout",Q=ns(V,ce),[L,Ae]=jt(null),[xe,Me]=jt(null),qe=Rt(null),ke=Rt(null),Ee=Rt(0),[ee,dn]=jt(null),Yt=Rt(null),[H,Je]=jt(null),$=tr(()=>n?Po(n):"",[n]),K=n?`create:${$}`:`session:${e??""}`,ie=Wl(H),u=Rt(new Set),B=Rt(K),_e=Rt(K);Uo(()=>{_e.current=K,B.current!==K&&(B.current=K,u.current.clear())},[K]);let Ke=Pn(T=>{if(_e.current===K){if(yi.has(T.name)){if(u.current.has(T.name))return;u.current.add(T.name)}Bt(()=>h?.(T))}},[K,h]),Re=go(Ke,K),$t=Rt(!1),N=Pn(T=>{if($t.current)return;let E=T.gateway||!ie?T:{...T,gateway:ie};Ke(E)},[Ke,ie]);ur(()=>{Re({class:"lifecycle",name:"checkout.mount"})},[Re]);let[Ct,Et]=jt(e??""),pt=e??Ct,un=n?"":pt,[O,Ot]=jt(!0),[Cn,pn]=jt(null),[mn,_n]=jt(0),[Fn,Dn]=jt("full"),[Jt,je]=jt(!1),[He,St]=jt(dt),[rn,wt]=jt(null),[$n,mt]=jt(null),[Tt,zt]=jt(!1),[yn,Ut]=jt(void 0),[At,Sn]=jt(""),[wn,It]=jt(!1),[te,on]=jt(!1),[Kn,Ht]=jt(!1),Kt=Rt(null),an=Rt(0),nr=Rt(void 0),[Nn,Wt]=jt("loading"),[Le,fn]=jt(0),se=Rt(!1),M=Rt(!1),Oe=Rt(!1),D=Rt(null),kt=Rt(null),xt=tr(()=>({checkoutMode:de??Fn,layout:_u(V,ce)}),[de,V,Fn,ce]),Gt=Rt(f);Gt.current=f;let Vn=Rt(C);Vn.current=C;let ge=Rt(m);ge.current=m;let sn=Pn(T=>Ma(D,async E=>{try{return await T(E)}catch(F){throw E.aborted?Zo(F):F}}),[]);ur(()=>()=>{D.current?.abort(),D.current=null},[]);let Hn=Pn((T,E)=>{qe.current=T,Me(T),Yt.current=E,dn(E)},[]),Pr=Pn(()=>{let T=ke.current;T&&(ke.current=null,T.destroy())},[]);ur(()=>{Qt(xe)?.setCheckoutContext(xt),ee&&ee!==xe&&Qt(ee)?.setCheckoutContext(xt)},[xe,ee,xt]);let rr=Rt(Ne);rr.current=Ne;let zr=Pn(T=>{Wt(T),!(T!=="exhausted"||Oe.current)&&(Oe.current=!0,Vn.current?.(new bn("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),Ur=Pn(()=>{Wt("retrying"),fn(T=>T+1)},[]);ur(()=>{Wt("loading"),fn(0),Oe.current=!1},[pt]),ur(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:Jl,checkout_type:re,checkout_layout:Q,billing_api_url:x})},[Q,re,x]);let or=tr(()=>n?Po(n,!0):"",[n]),Er=tr(()=>At===or?yn:void 0,[yn,At,or]),Rn=tr(()=>n?di(n,Er):void 0,[n,Er]),ar=de??Rn?.checkoutMode??"full",Dt=tr(()=>Rn?{...Rn,checkoutMode:ar}:void 0,[Rn,ar]);ur(()=>{Ut(void 0),Sn(or),nr.current=void 0,Kt.current=null,Ht(!1)},[or]),ur(()=>{St(dt)},[dt]);let Ln=Pn((T,E,F)=>{Bt(()=>{ge.current?.(nn(T,E,F))})},[]),Wn=Pn(async(T,E)=>{St(null),mt(null),zt(!1),wt("processing");let F=E?.sessionId??T.id,z=T.clientSecret||t,it=Wl(T),R=qe.current??Yt.current,d=Qt(R),A=R?null:ja(x,o,xt),g={log:y=>{d?d.log(y):A?.log(y)},error:y=>{d?d.error(y):A?.error(y)},terminal:y=>{d?d.terminal(y):A?.terminal(y)},performance:y=>{d?d.performance(y):A?.performance(y)},now:()=>d?.now()??A?.now()??0,elapsed:y=>d?.elapsed(y)??Math.max(0,(A?.now()??y)-y)},P=g.now(),I=!!(E?.initialAutoProcessingError||E?.initialAutoProcessingPending),v=!1,q,Ve=()=>{v||(v=!0,I=!0,q=g.now(),g.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),g.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},Nt=!1,Ce=()=>{Nt||(Nt=!0,g.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),g.performance({stage:"processing",durationMs:g.elapsed(P),durationMode:"machine",paymentMethodCategory:"saved",requestCategory:"process_payment"}),q!==void 0&&g.performance({stage:"recovery",durationMs:g.elapsed(q),durationMode:"machine",paymentMethodCategory:"saved"}))};g.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),$t.current=!0;try{g.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"})}finally{$t.current=!1}Re({class:"lifecycle",name:"payment.processing.started",provider:it}),I&&Ve();let ne;try{let y=fl(E?.initialAutoProcessingError),k=E?.initialAutoProcessingError?.type==="3ds_required"&&!E.initialAutoProcessingError.threeDSecureToken&&E.initialAutoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:E.initialAutoProcessingError.nextActionRedirectUrl}:null,J,ue=Se=>(Ve(),sn(pe=>Co(Se,{billingApiUrl:x,sessionId:F,nonce:z,session:T,signal:pe})));if(k)J=await ue(k);else if(y)Ve(),y.type==="paypal_redirect_required"&&kt.current?.publishableKey&&Vl({sessionId:F,publishableKey:kt.current.publishableKey,paypalPublishableKey:kt.current.paypalPublishableKey}),J=await sn(Se=>Fa(y,{flopay:qe.current,paypalFlopay:Yt.current,attempt3DS:E?.attempt3DS,billingApiUrl:x,sessionId:F,session:T,telemetry:!1,signal:Se})),y.type==="paypal_redirect_required"&&ts();else if(E?.initialAutoProcessingPending){let Se=E.initialAutoProcessingPending,pe=new Ua(x,{telemetry:!1}),Ge=await sn(qn=>pe.waitForCheckoutSessionCompletion(Se.sessionId,{initialDelayMs:Se.retryAfterMs,nonce:z,statusUrl:Se.statusUrl,signal:qn})),ht=Ge.data.session,tn=Ge.autoProcessingError?.type==="3ds_required"&&Ge.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:Ge.autoProcessingError.nextActionRedirectUrl}:null;if(tn)J=await ue(tn);else{if(!Mr(ht))throw po(ht);J=Sr(ht,F)}}else{if(E?.initialAutoProcessingError)throw gr(E.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:E.initialAutoProcessingError.checkoutMethod});if(E?.fromCreateSession)return E?.fallbackToFull&&(Dn("full"),Hl("full")),!1;{let Se=await So({billingApiUrl:x,sessionId:F,session:T,nonce:z,telemetry:!1});Se.type==="success"?J=Se.result:Se.type==="next_action_required"?J=await ue(Se):(Ve(),Se.type==="paypal_redirect_required"&&kt.current?.publishableKey&&Vl({sessionId:F,publishableKey:kt.current.publishableKey,paypalPublishableKey:kt.current.paypalPublishableKey}),J=await sn(pe=>Fa(Se,{flopay:qe.current,paypalFlopay:Yt.current,attempt3DS:E?.attempt3DS,billingApiUrl:x,sessionId:F,session:T,telemetry:!1,signal:pe})),Se.type==="paypal_redirect_required"&&ts())}}F&&bo(F),Ce(),I&&(g.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),g.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),g.terminal({outcome:J.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),zt(J.status==="authorized"),wt("success"),await na(600),ne=()=>Gt.current?.(J)}catch(y){let k=Qo(y);if(k.code==="three_ds_aborted")return!1;let J=k.checkoutMethod??Xo;St(k.message),mt(k.message),zt(!1),E?.fallbackToFull&&(g.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),Dn("full"),Hl("full")),Ce();let ue=k.statusCode===void 0?void 0:bu(k.statusCode,"unknown"),Se=ue==="4xx"?{requestCategory:"process_payment",statusClass:ue}:{},pe=ue===void 0||ue==="4xx";if(pe&&(k.telemetryOutcome==="payment_declined"||!!(k.declineCode||k.code?.toLowerCase().includes("declin"))))g.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...Se});else if(pe&&(k.telemetryOutcome==="validation_rejected"||k.type==="validation_error"))g.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...Se});else{let tn=Gl(y,I?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown"),qn=k.telemetryRequestCategory??"process_payment";$t.current=!0;try{g.error({...tn,...k.telemetryFailureCategory?{failureCategory:k.telemetryFailureCategory}:{},stage:I?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:qn})}finally{$t.current=!1}Re({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:qn,provider:it})}return Bt(()=>Vn.current?.(k)),Ln(J,k,{code:k.code,declineCode:k.declineCode}),wt("error"),await Promise.allSettled([na(400),E?.ensureProvidersReady?E.ensureProvidersReady():Promise.resolve()]),I&&(g.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),g.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{Ce(),A&&ra(A),wt(null),mt(null)}return Bt(ne),!0},[Ln,Re,t,x,sn,o,xt]);ur(()=>{if(typeof window>"u"||M.current)return;let T=new URLSearchParams(window.location.search),E=T.get("payment_intent_client_secret");if(!E)return;let F=Iu();F&&(M.current=!0,(async()=>{let z,it=0;St(null),mt(null),wt("processing"),je(!0);try{if(T.get("redirect_status")==="failed")throw Object.assign(new bn("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:R,paypalFlopay:d}=await xi({publishableKey:F.publishableKey,paypalPublishableKey:F.paypalPublishableKey,billingApiUrl:x,locale:s,telemetry:o});z=Qt(d??R),z?.setCheckoutContext(xt),it=z?.now()??0,z?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),z?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let A=(d??R)?.getRawProvider();if(!A)throw Object.assign(new bn("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:g,error:P}=await A.retrievePaymentIntent(E);if(P)throw Object.assign(new bn(P.message??"Failed to retrieve PayPal payment status.","api_error",{code:P.code}),{checkoutMethod:"paypal"});let I=Ys(g?.status);if(!g||I==="failed")throw Object.assign(new bn("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let v=typeof g.payment_method=="string"?g.payment_method:g.payment_method?.id,q=I;if(F.sessionId){let Ce=(await new Ua(x,{telemetry:!1}).getUnifiedCheckoutSession(F.sessionId)).data.session;if(Ce&&Ce.status!=="complete"){let ne=await So({billingApiUrl:x,sessionId:F.sessionId,session:Ce,telemetry:!1,tokenizedData:{id:v??g.id,type:"card",threeDSecureActionResultTokenId:g.id,isPaypal:!0}});if(ne.type!=="success")throw Object.assign(new bn("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});q=ne.result.status}}F.sessionId&&bo(F.sessionId),z?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),z?.performance({stage:"redirect_resume",durationMs:z.elapsed(it),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),z?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),wt("success"),await na(600),Bt(()=>Gt.current?.({status:q,paymentIntentId:g.id,paymentMethodId:v,checkoutMethod:"paypal"}))}catch(R){let d=Qo(R),A=d.checkoutMethod??"paypal",g=!!(d.declineCode||d.code?.toLowerCase().includes("declin"));if(z)z.performance({stage:"redirect_resume",durationMs:z.elapsed(it),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),g?z.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):z.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(g){let P=ja(x,o,xt);P.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),ra(P)}else Zi(x,o,xt,"REDIRECT_RESUME_FAILED","redirect_resume");St(d.message),mt(d.message),Bt(()=>Vn.current?.(d)),Ln(A,d,{code:d.code,declineCode:d.declineCode}),wt("error"),await na(400)}finally{ts(),ku(),wt(null),mt(null),je(!1)}})())},[Ln,s,x,o,xt]);let Gn=Rt(null),yt=tr(()=>Dt?Po(Dt):"",[Dt]),En=Rt(Dt);En.current=Dt,ur(()=>{Et(e??"")},[e]),ur(()=>{se.current=!1,St(dt),mt(null),zt(!1),wt(null)},[yt,dt,e]);async function Yn(T,E,F){let z=ja(x,o,xt),it=new Ua(x,{telemetry:!1}),R=!1;try{let d=T.idempotencyKey===void 0?void 0:ql(T.idempotencyKey),A=wi(E,F),g=Ii(E,F);A?.canonicalIdentity===F&&g&&g.canonicalIdentity===void 0&&(Ta(E,F,g.idempotencyKey),g={...g,canonicalIdentity:F});let P=d??(g?.canonicalIdentity===F?g.idempotencyKey:void 0),I,v=!1;z.log({name:A?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let q=A?.sid??null,Ve=null,Nt,Ce,ne=!1;if(q)try{Ve=await it.getUnifiedCheckoutSession(q,A?.nonce),A&&A.canonicalIdentity===void 0&&(ll(Ve.data.session,T)?(Ea(E,F,q,A.nonce??Ve.data.session?.clientSecret),g&&g.canonicalIdentity===void 0&&(Ta(E,F,g.idempotencyKey),P??(P=g.idempotencyKey))):(Ra(E,F),g=null,P=d,q=null,Ve=null));let k=Ve?.data.session?.status,J=Ve?.data.session,ue=J?.clientSecret||A?.nonce;if(q&&J?.buyerIdentified===!1&&ue&&(Ce=uo(it,q,ue,T.account)),q&&Ve&&k==="complete"){if(ki(q))return{sid:q,result:Ve};Ra(E,F),q=null,Ve=null,v=!0}}catch{z.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),A?.canonicalIdentity===void 0?(Ra(E,F),P=d):_a(E,F),q=null}if(!q){!d&&(v||!P)&&(P=ql(),I=P),P&&Ta(E,F,P);let k=z.now(),J=0;z.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let ue={...T,idempotencyKey:P,avsCheck:!!we,avsConfig:typeof we=="object"?we:void 0,checkoutType:"embedded_checkout",checkoutLayout:ns(V,ce)};Object.defineProperty(ue,fu,{configurable:!1,enumerable:!1,value:{onAttempt:Ge=>{J=Math.max(J,Ge)}}});let Se=()=>{$l(z,"session_create",k,J)},pe=Ge=>{Kl(z,Ge,"session_create",k,J)&&Re({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_create"})};try{if(hu(ue)){let Ge=await it.createDetachedSession(ue);Ge.claimed.catch(()=>{}),Ve=Ge.shell,q=Ge.sessionId,Ce=Ge.claim;let ht=z.now();z.log({name:"session.claim.started",stage:"session_claim",requestCategory:"session_claim"}),Nt=Ge.claimed.then(tn=>{let qn=tn.data.session?.id??Ge.sessionId;return qn&&Ea(E,F,qn,tn.data.session?.clientSecret??Ge.nonce),$l(z,"session_claim",ht),Se(),tn},tn=>{throw _a(E,F),Kl(z,tn,"session_claim",ht,0)&&Re({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_claim"}),tn}).finally(()=>ra(z)),Nt.catch(()=>{}),R=!0,z.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),z.performance({stage:"session_shell",durationMs:z.now()-k,durationMode:"machine",requestCategory:"session_create",attempt:J,statusClass:"2xx",paymentMethodCategory:"card"})}else Ve=await it.createAndFetchSession(ue),Se()}catch(Ge){throw pe(Ge),Ge}q=Ve.data.session?.id??q??"",q&&!Nt&&Ea(E,F,q,Ve.data.session?.clientSecret)}let y=Ve?.data.session;return!Ce&&q&&y?.buyerIdentified===!1&&y.clientSecret&&(Ce=uo(it,q,y.clientSecret,T.account)),{sid:q??"",result:Ve,sdkGeneratedIdempotencyKey:I,...Nt?{claimed:Nt}:{},...Ce?{claim:Ce}:{},...ne?{claimRequiresIdentity:!0}:{}}}finally{R||ra(z)}}let ir=Rt(Yn);Uo(()=>{ir.current=Yn},[Yn]);let gn=Pn(async(T,E)=>{let F=En.current;if(!F)throw new bn("createSession is required to bootstrap checkout.","validation_error");let z=di(F,T),it=Po(z),R=sl(z),d=$a.get(it);if(!d){let P={canonicalIdentity:it,promise:ir.current(z,R,it),consumers:0,settled:!1};d=P,$a.set(it,P);let I=()=>{P.settled=!0,jl(it,P)};P.promise.then(I,I)}d.consumers+=1;let A=!1,g=()=>{A||(A=!0,d.consumers-=1,jl(it,d))};E?.(g);try{let P=await d.promise;Gn.current=it,T&&(Sn(or),Ut(y=>Hs(y,T)));let{sid:I,result:v,claimed:q,claim:Ve,claimRequiresIdentity:Nt}=P;if(nr.current=Ve,Ht(Nt===!0),Ae(v),v.data.session&&Je(v.data.session),I&&Et(I),q){an.current+=1;let y=an.current;Kt.current=q,on(!0),q.then(k=>{an.current===y&&(Kt.current===q&&(Kt.current=null),Ae(k),k.data.session&&Je(k.data.session),on(!1),Ht(!1))},k=>{an.current===y&&(Kt.current===q&&(Kt.current=null),on(!1),Ht(!1),pn(k instanceof bn?k:new bn(k instanceof Error?k.message:"Failed to create session","api_error")))})}else an.current+=1,Kt.current=null,on(!1),Ht(!1);let{flopay:Ce,paypalFlopay:ne}=await es(v,{billingApiUrl:x,locale:s,telemetry:o});return Hn(Ce,ne),Ot(!1),P}catch(P){throw Gn.current===it&&(Gn.current=null),P}finally{E||g()}},[or,Hn,s,x,o]),We=Rt(Wn);We.current=Wn;let hn=Rt(gn);hn.current=gn;let ln=Pn(async T=>{if(!Ru(T)||wn)return{sessionId:Ct,session:H};It(!0);try{let E=await gn(T);return{sessionId:E.sid,session:E.result.data.session??null}}finally{It(!1)}},[gn,wn,Ct,H]),On=Pn(async T=>{let E=nr.current;if(!E)return;let F=an.current,z=await E(T);an.current===F&&(Ae(z),z.data.session&&Je(z.data.session))},[]),br=Pn(async()=>{await Kt.current},[]),qr=Pn(async()=>(await br(),{proceed:!0}),[br]);ur(()=>{let T=!1,E,F=++Ee.current;Pr(),pn(null),_n(0);let z=()=>{T=!0,Ee.current===F&&(Ee.current+=1,Pr())},it=En.current;if(yt&&it)return Dn(ar),Ot(!1),Gn.current===yt?z:(Je(Ws(it,de)),(async()=>{let A=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),g=ar==="auto"&&!se.current&&!A;g&&(St(null),mt(null),wt("processing"));try{let P=await hn.current(void 0,Ve=>{E=Ve}),I=P.result.data.session??null;kt.current=Ai(P.result);let v=Qi(P.result),q=ki(P.sid||I?.id);if(!T&&g&&I&&!v&&!q){se.current=!0,await Cu(yt,P.sdkGeneratedIdempotencyKey,()=>We.current(I,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:P.result.autoProcessingError,initialAutoProcessingPending:P.result.autoProcessingPending,autoProcessingAttempted:P.result.autoProcessingAttempted,sessionId:P.sid||I.id}));return}!T&&g&&((v||q)&&(se.current=!0),wt(null),mt(null))}catch(P){if(T)return;let I=va(P);if(g&&I==="session_auto_completed"){se.current=!0,wt("success"),await na(600),T||(Bt(()=>{Gt.current?.({status:"succeeded"})}),wt(null),mt(null));return}g&&(wt(null),mt(null));let v=P instanceof bn?P:new bn(P instanceof Error?P.message:"Failed to create session","api_error");pn(v)}finally{E?.(),E=void 0}})(),()=>{z(),E?.()});Ot(!0);async function R(){let A=!1,g=null;try{let P=new Ua(x,{telemetry:!1}),I=await P.getUnifiedCheckoutSession(pt,t);if(g=I,T)return;Ae(I);let v=I.data.session??null;if(Je(v),!v)throw new bn("No session data returned","api_error");let q=v.checkoutMode;if(q==="setup")throw new bn("This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.","validation_error",{code:"InvalidCardSetupSurface",param:"sessionId"});if(v.status==="authorized"){Ot(!1),Bt(()=>{Gt.current?.(Sr(v,pt)),rr.current?.(v.successUrl??"")});return}if(v.status==="complete"){Ot(!1),Bt(()=>{rr.current?.(v.successUrl??"")});return}if(v.status==="expired")throw ha(v);A=!0;let Ve=de??q??"full";Dn(Ve),an.current+=1;let Nt=v.clientSecret||t;nr.current=v.buyerIdentified===!1&&Nt?uo(P,pt,Nt,{...v.customer?.id?{userId:v.customer.id}:{}}):void 0,on(!1),Ht(!1);let Ce=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),ne=Qi(I);if(Ve==="auto"&&!se.current&&!Ce&&!ne){se.current=!0;let y=d(I);try{if(await We.current(v,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>y,sessionId:pt||v.id}),T)return;await y,T||Ot(!1);return}catch{if(T)return;await y,T||Ot(!1);return}}await d(I),T||Ot(!1)}catch(P){if(T)return;let I=Vs(P,A);if(A&&Re({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"}),I){let{errorCode:q,stage:Ve,...Nt}=I;Zi(x,o,xt,q,Ve,Nt)}if(I?.stage==="provider_load"&&(de??g?.data.session?.checkoutMode??"full")==="full"&&Ks(g,ae,Y)){let q=wu({billingApiUrl:x,locale:s,telemetry:o});ke.current=q,Hn(q,null),_n(1),Ot(!1);return}let v=P instanceof bn&&I?.stage!=="provider_load"?P:$s();v!==P&&Bt(()=>Vn.current?.(v)),pn(v),Ot(!1)}}async function d(A){let{flopay:g,paypalFlopay:P,...I}=await es(A,{billingApiUrl:x,locale:s,telemetry:o});kt.current={publishableKey:I.publishableKey,paypalPublishableKey:I.paypalPublishableKey},Hn(g,P),_n(0)}return R(),z},[de,yt,ar,un,t,ae,Y]);let Cr=Pn(async()=>{if(!L||mn!==1)return;let T=Ee.current;_n(2);try{let{flopay:E,paypalFlopay:F}=await es(L,{billingApiUrl:x,locale:s,telemetry:o});if(Ee.current!==T)return;Pr(),Hn(E,F),_n(0)}catch(E){if(Ee.current!==T)return;let{errorCode:F,stage:z,...it}=li(E);Zi(x,o,xt,F,z,it)}},[Pr,Hn,s,mn,x,o,xt,L]),zn=!!(pt&&(H?.clientSecret||t)),vn=Jt||!zn,Xr=Pn(async()=>{if(!(Jt||!zn||!H)){je(!0),St(null);try{await Wn(H,{attempt3DS:!0,fallbackToFull:!0,sessionId:pt||H.id})}finally{je(!1)}}},[pt,Jt,zn,Wn,H]),Tn=Xl(L,U),Tr=Qi(L),In=tr(()=>{if(!(!L||!H||!L.data.stripe?.publishableKey))return{billingApiUrl:x}},[L,H,x]),Un=!!(n&&!V&&ce==="buttons"&&ye&&ar==="full"),et=!!(pt&&(H?.vault?.html||Ar(H))),Jn=tr(()=>({session:H,loading:O,error:Cn,checkoutMode:Fn,inlineSessionDraft:Dt,applyInlineSessionPatch:Un?ln:void 0,inlineSessionPatchProcessing:wn,claimPending:te,claimRequiresIdentity:Kn,claimBuyerIdentity:On,waitForDataAttachment:br}),[H,O,Cn,Fn,Dt,Un,ln,wn,te,Kn,On,br]),Xt=!!n&&ce==="buttons"&&!Tr&&!et&&(!xe||!In),_t=rn?oe(fr,{status:rn,errorMessage:$n,authorized:Tt}):null;if(O&&!et){if(l)return en(vr,{children:[l,_t]});if(ce==="buttons"){let T=at?.buttonsLayout?.cardButton?.borderRadius??at?.appearance.variables?.borderRadius??8,E=F=>oe("div",{style:{height:F,borderRadius:T,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return en(vr,{children:[en("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[ae&&E(ko),Y&&(S||G)&&E(ko),Y&&E(ko),oe("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),_t]})}return en(vr,{children:[en("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[oe("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),oe("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),_t]})}return Cn?p?oe(cr.Provider,{value:Jn,children:p(Cn)}):oe(cr.Provider,{value:Jn,children:oe("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:Cn.message})}):Xt?en(vr,{children:[oe(cr.Provider,{value:Jn,children:oe(Tu,{onButtonClick:De,showPayPal:ae,showStripe:Y,showApplePay:S,showGooglePay:G,theme:Te,buttonsTheme:Fe,buttonsStyles:ve,cardButtonContent:Ue,cardBackButtonContent:bt,cardTitleContent:ot})}),_t]}):Tr&&H&&Tn?en(vr,{children:[oe(cr.Provider,{value:Jn,children:en("div",{className:ct,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[He&&oe(ho,{icon:!1,children:He}),Nn==="retrying"&&oe("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),Nn==="exhausted"&&en("div",{role:"alert",children:[oe("div",{children:"PayPal is temporarily unavailable. Please try again."}),oe("button",{type:"button",onClick:Ur,children:"Retry PayPal"})]}),Nn!=="exhausted"&&oe("div",{"aria-hidden":Nn==="retrying"?!0:void 0,style:Nn==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:oe(al,{sessionId:pt,nonce:H.clientSecret||void 0,billingApiUrl:x,email:H.customer?.email||Dt?.account?.email,billingName:[H.customer?.firstName,H.customer?.lastName].filter(Boolean).join(" ")||[Dt?.account?.firstName,Dt?.account?.lastName].filter(Boolean).join(" ")||void 0,onBuyerIdentityReady:On,clientId:Tn.clientId,environment:Tn.environment,currency:(H.currency??"usd").toUpperCase(),isSubscription:H.mode==="subscription",providerObjectType:Tn.providerObjectType,approvalPresentation:Tn.approvalPresentation,existingOrderId:Tn.existingOrderId,onComplete:f,onErrorChange:St,onDecline:m,onButtonClick:De,runBeforeButtonClick:qr,onInitializationStateChange:zr,allowAutomaticRetry:Le===0,session:H,telemetry:o,telemetryContext:xt,onInstrument:N,debug:X},`${K}:paypal-init-${Le}`)})]})}),_t]}):Fn==="confirm"?en(vr,{children:[oe(cr.Provider,{value:Jn,children:oe(Aa,{flopay:xe,paypalFlopay:ee,options:In??{billingApiUrl:x},onInstrument:N,children:en("div",{className:ct,children:[He&&oe("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:He}),ut?ut({onConfirm:Xr,isProcessing:vn}):oe("button",{type:"button",onClick:Xr,disabled:vn,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:vn?"not-allowed":"pointer",opacity:vn?.6:1},children:Jt?"Processing...":fe??"Confirm Purchase"})]})},K)}),_t]}):(!xe||!In)&&!(et&&Fn==="full")?oe(vr,{children:_t}):en(vr,{children:[oe(cr.Provider,{value:Jn,children:en(Aa,{flopay:xe,paypalFlopay:ee,options:In??{billingApiUrl:x},onInstrument:N,children:[mn===1&&oe("button",{type:"button",onClick:Cr,children:"Retry payment methods"}),V?en(vr,{children:[He&&oe("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:He}),oe(Eu,{sessionId:pt,nonce:H?.clientSecret||void 0,billingApiUrl:x,session:H,submitLabel:be,children:V})]}):oe(Ji,{sessionId:pt,nonce:H?.clientSecret||void 0,telemetry:o,email:H?.customer?.email||Dt?.account?.email,userId:H?.customer?.id||Dt?.account?.userId,firstName:H?.customer?.firstName||Dt?.account?.firstName,lastName:H?.customer?.lastName||Dt?.account?.lastName,totalAmount:H?Math.round(gu(H).total*100):0,currency:H?.currency?.toLowerCase()??"usd",onComplete:f,onError:C,onDecline:m,error:He,onErrorChange:St,showPayPal:ae,showStripe:Y,enabledPaymentMethods:mn?[]:Pe??L?.data.stripe?.enabledPaymentMethods??H?.gateways?.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:L?.data.stripe?.enabledPaymentMethodCountries,showApplePay:S,showGooglePay:G,layout:ce,theme:Te,buttonsTheme:Fe,buttonsStyles:ve,appearance:Ye,cardButtonContent:Ue,cardBackButtonContent:bt,cardTitleContent:ot,onButtonClick:De,onBeforeButtonClick:ye,onBuyerIdentityReady:On,enableAVS:we,...Qe?{cardFieldOrder:Qe}:{},...Z?{cardPreFormSlot:Z}:{},avsLayout:Ie,country:H?.customer?.country,city:H?.customer?.city,state:H?.customer?.state,onCountryChange:w,onZipChange:_,avsCheck:!!we,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:ns(V,ce),className:ct,submitLabel:be,directPaypal:Tn,isSubscription:H?.mode==="subscription",session:H,dataAttachmentPending:te,dataAttachmentRequiresIdentity:Kn,debug:X})]},K)}),_t]})}function Eu({sessionId:e,nonce:t,billingApiUrl:n,session:r,submitLabel:o,children:i}){return oe(vr,{children:Xi.Children.map(i,s=>{if(!Xi.isValidElement(s))return s;let l=s.props,p={};return l.sessionId||(p.sessionId=e),!l.nonce&&t&&(p.nonce=t),l.billingApiUrl||(p.billingApiUrl=n),l.submitLabel===void 0&&o!==void 0&&(p.submitLabel=o),r?.customer&&(l.email||(p.email=r.customer.email),l.userId||(p.userId=r.customer.id),l.firstName||(p.firstName=r.customer.firstName),l.lastName||(p.lastName=r.customer.lastName)),Object.keys(p).length===0?s:Xi.cloneElement(s,p)})})}function Tu({onButtonClick:e,showPayPal:t,showStripe:n=!0,showApplePay:r,showGooglePay:o,theme:i,buttonsTheme:s,buttonsStyles:l,cardButtonContent:p,cardBackButtonContent:f,cardTitleContent:C}){let[h,m]=jt(!1),w=tr(()=>Yl(i),[i]),_=tr(()=>{let S=w?.buttonsLayout??Pu(s);return l?{...S,...l,cardButton:{...S.cardButton,...l.cardButton},cardFormContainer:{...S.cardFormContainer,...l.cardFormContainer},backButton:{...S.backButton,...l.backButton},backButtonIcon:{...S.backButtonIcon,...l.backButtonIcon},submitButton:{...S.submitButton,...l.submitButton},title:{...S.title,...l.title}}:S},[w,s,l]),ae=w?.buttonsLayout?.cardButton?.borderRadius??w?.appearance.variables?.borderRadius??8,Y=S=>oe("div",{style:{height:S,borderRadius:ae,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),Pe=p===void 0?{boxSizing:"border-box",height:ko,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(h){let S=_.cardInputBorder??"#e5e7eb",G=_.cardInputBackground??"white",X=io(f),ce=io(C);return en("div",{style:{backgroundColor:_.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",..._.cardFormContainer},children:[en("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[en("button",{type:"button",onClick:()=>m(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:X?0:"0.5rem",background:"none",border:"none",color:"#4b5563",fontSize:"0.85rem",fontWeight:500,padding:0,flexShrink:0,opacity:1,cursor:"pointer",..._.backButton},children:[oe("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",..._.backButtonIcon},children:oe("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:oe("path",{d:"M15 18l-6-6 6-6"})})}),oe(lo,{content:f})]}),ce?oe("div",{style:{flex:1}}):oe("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,..._.title},children:oe(jo,{content:C})})]}),oe("div",{style:{backgroundColor:G,border:`1px solid ${S}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:oe("div",{style:{width:"60%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),en("div",{style:{display:"flex"},children:[oe("div",{style:{flex:1,backgroundColor:G,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${S}`,borderLeft:`1px solid ${S}`,borderBottomLeftRadius:8,padding:12,height:45},children:oe("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),oe("div",{style:{flex:1,backgroundColor:G,borderTop:"none",borderRight:`1px solid ${S}`,borderBottom:`1px solid ${S}`,borderLeft:`1px solid ${S}`,borderBottomRightRadius:8,padding:12,height:45},children:oe("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),oe("div",{style:{backgroundColor:G,border:`1px solid ${S}`,borderRadius:8,marginTop:8,padding:12,height:45},children:oe("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),oe("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",..._.submitButton,opacity:.5}}),oe("style",{children:`
|
|
36
36
|
@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }
|
|
37
37
|
@keyframes flopay-interim-expand {
|
|
38
38
|
0% { opacity: 0; max-height: 0; transform: translateY(-12px); }
|
|
39
39
|
40% { opacity: 1; }
|
|
40
40
|
100% { opacity: 1; max-height: 600px; transform: translateY(0); }
|
|
41
41
|
}
|
|
42
|
-
`})]})}return en("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&qe(So),n&&(r||o)&&qe(So),n&&re("button",{type:"button",onClick:()=>{e?.("card"),y(!0)},style:{width:"100%",...ge,backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:"8px",fontSize:M.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,...M.cardButton},onMouseDown:S=>{S.currentTarget.style.transform="scale(0.985)"},onMouseUp:S=>{S.currentTarget.style.transform="scale(1)"},children:re(ao,{content:p})}),re("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}import{Fragment as Bu,jsx as ko,jsxs as Fu}from"react/jsx-runtime";var Eu=44;function Gl(e){return new Promise(t=>setTimeout(t,e))}function Tu(e,t){return e instanceof ra?e:new ra(e instanceof Error?e.message:t,"api_error")}function Au(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function Mu(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 xu({sessionId:e,nonce:t,createSession:n,paymentMethodId:r,checkoutMethod:o,clientId:i,products:s,items:l,subscriptions:p,account:v,successUrl:g,cancelUrl:h,couponCodes:y,tagsData:_,utmMetadata:M,billingApiUrl:U,locale:qe,theme:ge,appearance:S,buttonsTheme:W,buttonsStyles:Y,onSuccess:de,onError:Le,onDecline:Se,children:Re,disabled:Ge=!1,type:St="button",style:tt,...je}){let $e=ta(()=>ku(U),[U]),ue=ta(()=>Mu({createSession:n,clientId:i,products:s,items:l,subscriptions:p,account:v,successUrl:g,cancelUrl:h,couponCodes:y,tagsData:_,utmMetadata:M}),[v,h,i,y,n,s,l,p,g,_,M]),[we,Xe]=na(!1),[ee,Ie]=na(null),[he,st]=na(null),[lt,T]=na(!1),[$,Ee]=na(null),ie=Io(!0),rt=Io(null),A=Io($),Te=Io(de),dt=Io(Le),We=Io(Se);wo(()=>{A.current=$},[$]),wo(()=>{Te.current=de},[de]),wo(()=>{dt.current=Le},[Le]),wo(()=>{We.current=Se},[Se]),wo(()=>(ie.current=!0,()=>{ie.current=!1,rt.current?.abort()}),[]),wo(()=>{if(typeof window>"u")return;let u=w=>{w.key==="Escape"&&Ee(null)};return window.addEventListener("keydown",u),()=>{window.removeEventListener("keydown",u)}},[]);let se=xr((u,w=Yo)=>{We.current?.(nn(w,u,{code:u.code,declineCode:u.declineCode}))},[]),x=xr(async u=>{ie.current&&(st(null),T(u.result.status==="authorized"),Ie("success"),await Gl(600),ie.current&&Rt(()=>Te.current?.(u)))},[]),Q=xr(async(u,w)=>{ie.current&&(dt.current?.(u),w?.emitDecline&&se(u,w.method),st(u.message),T(!1),Ie("error"),await Gl(400))},[se]),Me=xr(async(u,w,xe)=>{let me=u.data.session??null;if(!me)throw new ra("No session data returned","api_error");let Ct=me.clientSecret||t;if(co(me)){await x({result:jr(me,w),session:me,sessionId:me.id||w,autoCompleted:!1});return}if(me.status==="expired")throw ya(me);try{if(u.autoProcessingPending){let Wt=(await new ns($e).waitForCheckoutSessionCompletion(u.autoProcessingPending.sessionId,{initialDelayMs:u.autoProcessingPending.retryAfterMs})).data.session;if(!co(Wt))throw ga(Wt);await x({result:jr(Wt,w),session:Wt,sessionId:Wt.id||w,autoCompleted:!1});return}if(u.autoProcessingError){if(u.autoProcessingError.type==="3ds_required"&&u.autoProcessingError.nextActionRedirectUrl&&w&&Ct){let xt=new AbortController;rt.current=xt;let K;try{K=await pl({billingApiUrl:$e,sessionId:w,nonce:Ct,nextActionRedirectUrl:u.autoProcessingError.nextActionRedirectUrl,signal:xt.signal})}finally{rt.current===xt&&(rt.current=null)}if(K.status==="declined")throw Tr({type:K.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:K.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:u.autoProcessingError.checkoutMethod});let yn=(await new ns($e).waitForCheckoutSessionCompletion(w,{initialDelayMs:0,nonce:Ct})).data.session;if(!co(yn))throw Tr({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:u.autoProcessingError.checkoutMethod});await x({result:jr(yn,w),session:yn,sessionId:yn.id||w,autoCompleted:!1});return}throw Tr(u.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:u.autoProcessingError.checkoutMethod})}if(xe?.fromCreateSession&&u.autoProcessingAttempted===!0)throw Tr({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let nt=await Po({billingApiUrl:$e,sessionId:w??me.id,session:me,nonce:Ct});if(nt.type!=="success")throw Tr({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await x({result:nt.result,session:me,sessionId:me.id||w,autoCompleted:!1})}catch(nt){let xt=Jo(nt),K=me.id||w;await Q(xt,{emitDecline:!0,method:xt.checkoutMethod??Yo}),Au(xt,K)&&K&&ie.current&&Ee({sessionId:K,errorMessage:xt.message,nonce:Ct||void 0})}},[t,$e,Q,x]),ot=xr(async u=>{if(je.onClick?.(u),!(u.defaultPrevented||Ge||we)){if(Ee(null),e&&ue){let w=new ra("Provide either sessionId or create-session props, not both.","validation_error");await Q(w),ie.current&&(Ie(null),st(null));return}if(!e&&!ue){let w=new ra("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await Q(w),ie.current&&(Ie(null),st(null));return}Xe(!0),st(null),T(!1),Ie("processing");try{let w=new ns($e);if(e){let xe=await w.getUnifiedCheckoutSession(e,t);await Me(xe,e);return}try{let xe=await w.createAndFetchSession({...ue});await Me(xe,xe.data.session?.id??null,{fromCreateSession:!0})}catch(xe){if(fa(xe)==="session_auto_completed"){await x({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw xe}}catch(w){await Q(Tu(w,"Automatic payment failed. Please try again."))}finally{ie.current&&(Ie(null),st(null),Xe(!1))}}},[je.onClick,ue,Ge,we,t,Me,$e,e,Q,x]),ke=xr(u=>{let w=A.current;Ee(null),Te.current?.({result:u,session:null,sessionId:w?.sessionId??null,autoCompleted:!1})},[]),Ke=xr(u=>{dt.current?.(u)},[]),_e=xr(u=>{We.current?.(u)},[]),le=ta(()=>Ru(ge),[ge]),ve=ta(()=>{let u=le?.buttonsLayout??_u(W);return Y?{...u,...Y,cardButton:{...u.cardButton,...Y.cardButton}}:u},[le,W,Y]),Vt=ta(()=>{let u=le?.appearance;return S?u?{...u,...S,variables:{...u.variables,...S.variables}}:S:u},[S,le]),H=Vt?.variables,Mt=H?.colorPrimary??"#4A49FF",mt=H?.colorPrimaryHover??zo(Mt,.12),R=H?.borderRadius??"8px";return Fu(Bu,{children:[ko("button",{...je,type:St,onClick:ot,disabled:Ge||we,"aria-busy":we,style:{width:"100%",...Re===void 0?{boxSizing:"border-box",height:Eu,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...ve.cardButton,...Ki({themeBundle:le,resolvedPrimaryColor:Mt,resolvedBorderRadius:R,submitButtonStyle:ve.submitButton,explicitPrimaryColor:H?.colorPrimary}),fontSize:ve.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:Ge||we?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",transition:"background-color 0.15s, border-color 0.2s, box-shadow 0.2s, transform 0.1s",position:"relative",opacity:Ge||we?.6:1,...tt},onMouseEnter:u=>{je.onMouseEnter?.(u),!u.defaultPrevented&&!Ge&&!we&&(le||H?.colorPrimary)&&(u.currentTarget.style.backgroundColor=mt)},onMouseLeave:u=>{je.onMouseLeave?.(u),!u.defaultPrevented&&(le||H?.colorPrimary)&&(u.currentTarget.style.backgroundColor=Mt)},onMouseDown:u=>{je.onMouseDown?.(u),u.defaultPrevented||(u.currentTarget.style.transform="scale(0.985)")},onMouseUp:u=>{je.onMouseUp?.(u),u.defaultPrevented||(u.currentTarget.style.transform="scale(1)")},children:ko(ao,{content:Re})}),ee&&ko(yr,{status:ee,errorMessage:he,authorized:lt}),$&&ko("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:u=>{u.target===u.currentTarget&&Ee(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:ko("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:ko(ts,{sessionId:$.sessionId,nonce:$.nonce,checkoutMode:"full",billingApiUrl:$e,locale:qe,theme:ge,...Vt?{appearance:Vt}:{},buttonsTheme:W,buttonsStyles:Y,initialErrorMessage:$.errorMessage,cardTitleContent:null,onComplete:ke,onError:Ke,onDecline:_e})})})]})}export{wa as DirectPayPalButton,xu as FloPayAutomaticPaymentButton,yc as FloPayCardSetup,mc as FloPayCardSetupError,ts as FloPayCheckout,Ea as FloPayProvider,Vi as SplitCardForm,oi as VaultCardFields,$m as dropThirdPartyOnlyError,Tc as useCheckout,kr as useFloPay,di as usePayPalFloPay};
|
|
42
|
+
`})]})}return en("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&Y(ko),n&&(r||o)&&Y(ko),n&&oe("button",{type:"button",onClick:()=>{e?.("card"),m(!0)},style:{width:"100%",...Pe,backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:"8px",fontSize:_.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",boxShadow:"0 1px 2px rgba(0,0,0,0.04)",transition:"transform 0.1s",position:"relative",opacity:1,..._.cardButton},onMouseDown:S=>{S.currentTarget.style.transform="scale(0.985)"},onMouseUp:S=>{S.currentTarget.style.transform="scale(1)"},children:oe(so,{content:p})}),oe("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}import{Fragment as Ou,jsx as Eo,jsxs as zu}from"react/jsx-runtime";var Bu=44;function Zl(e){return new Promise(t=>setTimeout(t,e))}function Fu(e,t){return e instanceof ia?e:new ia(e instanceof Error?e.message:t,"api_error")}function Du(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function Nu(e){if(e.createSession)return{...e.createSession,checkoutMode:"auto"};if(!e.clientId||!e.account||!e.successUrl||!e.cancelUrl)return null;let t=e.products!=null;return{clientId:e.clientId,products:e.products,items:t?void 0:e.items,subscriptions:t?void 0:e.subscriptions,account:e.account,successUrl:e.successUrl,cancelUrl:e.cancelUrl,couponCodes:e.couponCodes,tagsData:e.tagsData,utmMetadata:e.utmMetadata,checkoutMode:"auto"}}function Lu({sessionId:e,nonce:t,createSession:n,paymentMethodId:r,checkoutMethod:o,clientId:i,products:s,items:l,subscriptions:p,account:f,successUrl:C,cancelUrl:h,couponCodes:m,tagsData:w,utmMetadata:_,billingApiUrl:ae,locale:Y,theme:Pe,appearance:S,buttonsTheme:G,buttonsStyles:X,onSuccess:ce,onError:Te,onDecline:Fe,children:ve,disabled:Ue=!1,type:bt="button",style:ot,...$e}){let De=oa(()=>Au(ae),[ae]),ye=oa(()=>Nu({createSession:n,clientId:i,products:s,items:l,subscriptions:p,account:f,successUrl:C,cancelUrl:h,couponCodes:m,tagsData:w,utmMetadata:_}),[f,h,i,m,n,s,l,p,C,w,_]),[we,Qe]=aa(!1),[Z,Ie]=aa(null),[be,ct]=aa(null),[dt,U]=aa(!1),[V,de]=aa(null),fe=Ro(!0),ut=Ro(null),Ne=Ro(V),x=Ro(ce),at=Ro(Te),Ye=Ro(Fe),re=Rr(u=>Ma(ut,async B=>{try{return await u(B)}catch(_e){throw B.aborted?Zo(_e):_e}}),[]);_o(()=>{Ne.current=V},[V]),_o(()=>{x.current=ce},[ce]),_o(()=>{at.current=Te},[Te]),_o(()=>{Ye.current=Fe},[Fe]),_o(()=>(fe.current=!0,()=>{fe.current=!1,ut.current?.abort()}),[]),_o(()=>{if(typeof window>"u")return;let u=B=>{B.key==="Escape"&&de(null)};return window.addEventListener("keydown",u),()=>{window.removeEventListener("keydown",u)}},[]);let Q=Rr((u,B=Xo)=>{Ye.current?.(nn(B,u,{code:u.code,declineCode:u.declineCode}))},[]),L=Rr(async u=>{fe.current&&(ct(null),U(u.result.status==="authorized"),Ie("success"),await Zl(600),fe.current&&Bt(()=>x.current?.(u)))},[]),Ae=Rr(async(u,B)=>{fe.current&&(at.current?.(u),B?.emitDecline&&Q(u,B.method),ct(u.message),U(!1),Ie("error"),await Zl(400))},[Q]),xe=Rr(async(u,B,_e)=>{let Ke=u.data.session??null;if(!Ke)throw new ia("No session data returned","api_error");let Re=Ke.clientSecret||t;if(Mr(Ke)){await L({result:Sr(Ke,B),session:Ke,sessionId:Ke.id||B,autoCompleted:!1});return}if(Ke.status==="expired")throw ha(Ke);try{if(u.autoProcessingPending){let N=u.autoProcessingPending,Ct=new is(De),Et=await re(O=>Ct.waitForCheckoutSessionCompletion(N.sessionId,{initialDelayMs:N.retryAfterMs,nonce:Re,statusUrl:N.statusUrl,signal:O})),pt=Et.data.session,un=Et.autoProcessingError?.type==="3ds_required"&&Et.autoProcessingError.nextActionRedirectUrl?{type:"next_action_required",nextActionRedirectUrl:Et.autoProcessingError.nextActionRedirectUrl}:null;if(un&&B&&Re){let O=await re(Ot=>Co(un,{billingApiUrl:De,sessionId:B,nonce:Re,session:Ke,signal:Ot}));await L({result:O,session:Ke,sessionId:Ke.id||B,autoCompleted:!1});return}if(Et.autoProcessingError)throw gr(Et.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:Et.autoProcessingError.checkoutMethod});if(!Mr(pt))throw po(pt);await L({result:Sr(pt,B),session:pt,sessionId:pt.id||B,autoCompleted:!1});return}if(u.autoProcessingError){let N=u.autoProcessingError.nextActionRedirectUrl;if(u.autoProcessingError.type==="3ds_required"&&N&&B&&Re){let Ct=await re(O=>Ti({billingApiUrl:De,sessionId:B,nonce:Re,nextActionRedirectUrl:N,signal:O}));if(Ct.status==="declined")throw gr({type:Ct.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:Ct.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:u.autoProcessingError.checkoutMethod});let un=(await new is(De).waitForCheckoutSessionCompletion(B,{initialDelayMs:0,nonce:Re})).data.session;if(!Mr(un))throw gr({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:u.autoProcessingError.checkoutMethod});await L({result:Sr(un,B),session:un,sessionId:un.id||B,autoCompleted:!1});return}throw gr(u.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:u.autoProcessingError.checkoutMethod})}if(_e?.fromCreateSession&&u.autoProcessingAttempted===!0)throw gr({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let $t=await So({billingApiUrl:De,sessionId:B??Ke.id,session:Ke,nonce:Re});if($t.type==="next_action_required"&&Re){let N=B??Ke.id,Ct=await re(Et=>Co($t,{billingApiUrl:De,sessionId:N,nonce:Re,session:Ke,signal:Et}));await L({result:Ct,session:Ke,sessionId:Ke.id||N,autoCompleted:!1});return}if($t.type!=="success")throw gr({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await L({result:$t.result,session:Ke,sessionId:Ke.id||B,autoCompleted:!1})}catch($t){let N=Qo($t);if(N.code==="three_ds_aborted")return;let Ct=Ke.id||B;await Ae(N,{emitDecline:!0,method:N.checkoutMethod??Xo}),Du(N,Ct)&&Ct&&fe.current&&de({sessionId:Ct,errorMessage:N.message,nonce:Re||void 0,payPalOrderId:N.orderId})}},[t,De,re,Ae,L]),Me=Rr(async u=>{if($e.onClick?.(u),!(u.defaultPrevented||Ue||we)){if(de(null),e&&ye){let B=new ia("Provide either sessionId or create-session props, not both.","validation_error");await Ae(B),fe.current&&(Ie(null),ct(null));return}if(!e&&!ye){let B=new ia("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await Ae(B),fe.current&&(Ie(null),ct(null));return}Qe(!0),ct(null),U(!1),Ie("processing");try{let B=new is(De);if(e){let _e=await B.getUnifiedCheckoutSession(e,t);await xe(_e,e);return}try{let _e=await B.createAndFetchSession({...ye});await xe(_e,_e.data.session?.id??null,{fromCreateSession:!0})}catch(_e){if(va(_e)==="session_auto_completed"){await L({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw _e}}catch(B){await Ae(Fu(B,"Automatic payment failed. Please try again."))}finally{fe.current&&(Ie(null),ct(null),Qe(!1))}}},[$e.onClick,ye,Ue,we,t,xe,De,e,Ae,L]),qe=Rr(u=>{let B=Ne.current;de(null),x.current?.({result:u,session:null,sessionId:B?.sessionId??null,autoCompleted:!1})},[]),ke=Rr(u=>{at.current?.(u)},[]),Ee=Rr(u=>{Ye.current?.(u)},[]),ee=oa(()=>Mu(Pe),[Pe]),dn=oa(()=>{let u=ee?.buttonsLayout??xu(G);return X?{...u,...X,cardButton:{...u.cardButton,...X.cardButton}}:u},[ee,G,X]),Yt=oa(()=>{let u=ee?.appearance;return S?u?{...u,...S,variables:{...u.variables,...S.variables}}:S:u},[S,ee]),H=Yt?.variables,Je=H?.colorPrimary??"#4A49FF",$=H?.colorPrimaryHover??qo(Je,.12),K=H?.borderRadius??"8px";return zu(Ou,{children:[Eo("button",{...$e,type:bt,onClick:Me,disabled:Ue||we,"aria-busy":we,style:{width:"100%",...ve===void 0?{boxSizing:"border-box",height:Bu,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...dn.cardButton,...Yi({themeBundle:ee,resolvedPrimaryColor:Je,resolvedBorderRadius:K,submitButtonStyle:dn.submitButton,explicitPrimaryColor:H?.colorPrimary}),fontSize:dn.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:Ue||we?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",transition:"background-color 0.15s, border-color 0.2s, box-shadow 0.2s, transform 0.1s",position:"relative",opacity:Ue||we?.6:1,...ot},onMouseEnter:u=>{$e.onMouseEnter?.(u),!u.defaultPrevented&&!Ue&&!we&&(ee||H?.colorPrimary)&&(u.currentTarget.style.backgroundColor=$)},onMouseLeave:u=>{$e.onMouseLeave?.(u),!u.defaultPrevented&&(ee||H?.colorPrimary)&&(u.currentTarget.style.backgroundColor=Je)},onMouseDown:u=>{$e.onMouseDown?.(u),u.defaultPrevented||(u.currentTarget.style.transform="scale(0.985)")},onMouseUp:u=>{$e.onMouseUp?.(u),u.defaultPrevented||(u.currentTarget.style.transform="scale(1)")},children:Eo(so,{content:ve})}),Z&&Eo(fr,{status:Z,errorMessage:be,authorized:dt}),V&&Eo("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:u=>{u.target===u.currentTarget&&de(null)},style:{position:"fixed",inset:0,background:"rgba(0, 0, 0, 0.45)",display:"flex",alignItems:"center",justifyContent:"center",padding:"1.5rem",zIndex:1100},children:Eo("div",{style:{width:"100%",maxWidth:520,maxHeight:"90vh",overflowY:"auto",background:"white",borderRadius:20,padding:"1.5rem",boxShadow:"0 24px 80px rgba(15, 23, 42, 0.28)",display:"flex",flexDirection:"column",gap:"1rem"},children:Eo(as,{sessionId:V.sessionId,nonce:V.nonce,checkoutMode:"full",billingApiUrl:De,locale:Y,theme:Pe,...Yt?{appearance:Yt}:{},buttonsTheme:G,buttonsStyles:X,initialErrorMessage:V.errorMessage,initialPayPalOrderId:V.payPalOrderId,cardTitleContent:null,onComplete:qe,onError:ke,onDecline:Ee})})})]})}export{ka as DirectPayPalButton,Lu as FloPayAutomaticPaymentButton,vc as FloPayCardSetup,hc as FloPayCardSetupError,as as FloPayCheckout,Aa as FloPayProvider,Ji as SplitCardForm,si as VaultCardFields,Xm as dropThirdPartyOnlyError,Bc as useCheckout,Br as useFloPay,mi as usePayPalFloPay};
|