@flopay/react 1.8.3 → 1.8.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,7 +1,7 @@
1
- import{a as tt,b as Yn,c as wa,d as po,e as Oi,f as zi,g as sl,h as ll}from"./chunk-W24FSJC5.mjs";import{dropThirdPartyOnlyError as ap}from"@flopay/shared";import{PaymentAPI as si}from"@flopay/js";import{FloPayError as Zr,resolveBillingApiUrl as Gc,resolveButtonsLayoutTheme as Wc,resolveTheme as Jc}from"@flopay/shared";import{useCallback as hr,useEffect as Wr,useMemo as Eo,useRef as Jr,useState as Ro}from"react";import{Fragment as Or,jsx as wn,jsxs as Ui}from"react/jsx-runtime";function cl(){return Ui(Or,{children:[Ui("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:[wn("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),wn("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",wn("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:wn("path",{d:"M9 18l6-6-6-6"})})]})}function dl(){return wn(Or,{children:"Go back"})}function ul(){return wn(Or,{children:"Secure card checkout"})}function Nr(e){return e!==void 0&&(e===""||e===null||e===!1)}function Dr({content:e}){return wn(Or,{children:e===void 0?wn(cl,{}):e})}function Lr({content:e}){return wn(Or,{children:e===void 0?wn(dl,{}):e})}function mo({content:e}){return wn(Or,{children:e===void 0?wn(ul,{}):e})}import{FloPayError as qi,isMoneySettledOutcome as pl,isSetupIntentClientSecret as ld}from"@flopay/shared";function $i(e,t){return t?e?{account:{...e.account??{},...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}:t:e}function ka(e,t){return t?{...e,account:{...e.account,...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}:e}function ji(e,t){let n=e.products??[...(e.subscriptions??[]).map(a=>({type:"subscription",code:a.code??a.providerPlanId,name:a.subscriptionName??a.providerPlanName??a.code??a.providerPlanId??null,quantity:a.quantity??1,totalAmount:a.totalAmount,overrideAmount:a.overrideAmount,currency:a.currency,metadata:a.metadata})),...(e.items??[]).map(a=>({type:"item",code:a.code??a.providerItemId,name:a.itemName??a.providerItemName??a.code??a.providerItemId??null,quantity:a.quantity??1,totalAmount:a.totalAmount,overrideAmount:a.overrideAmount,currency:a.currency,metadata:a.metadata}))],r=n.reduce((a,c)=>a+(c.overrideAmount??c.totalAmount??0),0),o=e.currency??n.find(a=>a.currency)?.currency??"USD";return{id:"",clientSecret:"",mode:n.some(a=>a.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((a,c)=>({uuid:`synthetic-${a.type??"item"}-${c}`,checkoutSessionId:"",type:a.type??"item",code:a.code,name:a.name??null,quantity:a.quantity??1,totalAmount:a.totalAmount,overrideAmount:a.overrideAmount??null,currency:a.currency??o,metadata:a.metadata??null}))}}function kn(e){let t=e?.trim().split(/\s+/).filter(Boolean)??[];return t.length===0?{}:{firstName:t[0],lastName:t.length>1?t.slice(1).join(" "):void 0}}function Ia(e,t){return t?{...e,...t}:e}function $t(e,t,n){let r=typeof t=="string"?t:t.message,o=typeof t=="string"?n?.code:n?.code??t.code,a=typeof t=="string"?n?.declineCode:n?.declineCode??t.declineCode;return{method:e,message:r,...o?{code:o}:{},...a?{declineCode:a}:{}}}var ml=[{match:/^paypal authorization required\.?$/i,replacement:"For your additional security, please re-authenticate this payment via PayPal."}];function cr(e){if(typeof e!="string")return e??void 0;let t=e.trim();if(!t)return e;for(let{match:n,replacement:r}of ml)if(n.test(t))return r;return e}function kr(e,t){return e.status!=="authorized"?{status:"succeeded"}:{status:"authorized",paymentId:e.paymentId,sessionId:e.id||t||void 0,authorizationExpiresAt:e.authorizationExpiresAt}}function zr(e){return e?.status==="authorized"||e?.status==="complete"}function Ki(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function qo(e){let t=Ki(e);return new qi(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function $o(e){let t=Ki(e);return new qi(t?"Authorization has expired.":"Automatic payment failed. Please try again.","api_error",{code:t?"authorization_expired":e?.status==="expired"?"checkout_session_expired":"checkout_processing_timeout"})}function jo(e,t){return e==="processing"||pl(e,t)}function Vi(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}function Hi(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?{mode:"setup"}:{mode:"payment",amount:e}}function yo(e){let t=[e?.id,e?.originalPaymentMethodId];for(let n of t)if(typeof n=="string"&&n.startsWith("pm_"))return n}import{PaymentAPI as ia,SESSION_CREATE_TELEMETRY as Ac}from"@flopay/js";import{buildCheckoutDisplayData as Mc,classifyTelemetryFailure as Ms,FloPayError as Kt,foldIntoProducts as Bc,isDetachedSessionEligible as Fc,resolveBillingApiUrl as Nc,resolveButtonsLayoutTheme as Dc,resolveIdempotencyKey as Bs,resolveSessionCurrency as Lc,resolveTheme as Ls,SDK_VERSION as Os,telemetryStatusClass as Oc}from"@flopay/shared";import Ga,{useCallback as Wn,useEffect as Jn,useMemo as En,useRef as At,useState as Et}from"react";import{createContext as Yi}from"react";var In=Yi({flopay:null,paypalFlopay:null,billingApiUrl:""}),Ln=Yi({session:null,loading:!1,error:null});import{PaymentAPI as Ta}from"@flopay/js";import{classifyTelemetryFailure as Tl,FloPayError as Xi,generateIdempotencyKey as Al,isValidEmail as Go,normalizeGatewayEnvironment as Ml,PAYPAL_VAULTED_PAYMENT_METHOD_TYPE as Aa,SDK_VERSION as Bl}from"@flopay/shared";import{loadScript as Fl}from"@paypal/paypal-js";import{useCallback as ho,useEffect as ft,useMemo as bo,useRef as Ve,useState as nr}from"react";import{isValidEmail as yl}from"@flopay/shared";import{useCallback as Gi,useEffect as fl,useRef as Wi,useState as Ra}from"react";import{jsx as Ea,jsxs as Ur}from"react/jsx-runtime";function fo(e){return!!(e.firstName?.trim()||e.lastName?.trim())}function qr(){let[e,t]=Ra(null),n=Wi(null),r=Wi(0),o=Gi((c,s)=>(n.current?.(null),r.current+=1,t({id:r.current,methodLabel:c,identity:s}),new Promise(S=>{n.current=S})),[]),a=Gi(c=>{let s=n.current;n.current=null,t(null),s?.(c)},[]);return fl(()=>()=>{n.current?.(null),n.current=null},[]),{request:e,collect:o,finish:a}}function Ir({identity:e,methodLabel:t,onComplete:n,onCancel:r,submitting:o=!1,testId:a="flopay-buyer-identity-pane"}){let[c,s]=Ra(e.email?.trim()??""),[S,b]=Ra([e.firstName,e.lastName].filter(Boolean).join(" ")),g=yl(c.trim())&&!!S.trim();return Ur("div",{"data-testid":a,style:{display:"flex",flexDirection:"column",gap:"0.75rem",padding:"0.875rem",border:"1px solid #d1d5db",borderRadius:8,background:"#fff",color:"#262833"},children:[Ur("div",{style:{fontWeight:700},children:["Continue with ",t]}),Ur("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",Ea("input",{type:"email",autoComplete:"email",required:!0,value:c,onChange:m=>s(m.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]}),Ur("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Full name",Ea("input",{type:"text",autoComplete:"name",required:!0,value:S,onChange:m=>b(m.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]}),Ur("div",{style:{display:"flex",gap:"0.5rem"},children:[r&&Ea("button",{type:"button",onClick:r,style:{flex:1,minHeight:42},children:"Cancel"}),Ur("button",{type:"button",disabled:!g||o,onClick:()=>{let m=kn(S);n({email:c.trim(),firstName:m.firstName,lastName:m.lastName})},style:{flex:2,minHeight:42},children:["Continue with ",t]})]})]})}function gl(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 Er(e){if(typeof e!="string")return;let t=e.trim();return/^[a-z0-9_.-]{1,64}$/i.test(t)?t:void 0}function tr(e){if(typeof e!="object"||e===null)return;let t=e;return Er(t.code)??Er(t.type)??Er(t.name)}function $r(e){if(!(typeof e!="object"||e===null))return Er(e.decline_code)}function go(e){return typeof e!="object"||e===null?!1:Er(e.type)?.toLowerCase()==="card_error"||$r(e)!==void 0}function dr(e){let t=gl(e)?.toLowerCase()??"",r=`${tr(e)?.toLowerCase()??""} ${t}`;return r.includes("popup")&&r.includes("block")}import{resolveBillingApiUrl as hl}from"@flopay/shared";import{useContext as Ko}from"react";function ur(){return Ko(In).flopay}function _a(){return Ko(In).paypalFlopay??null}function bl(){return Ko(Ln)}function Ji(){return Ko(In).billingApiUrl||hl()}import{FLO_INSTRUMENT_SCHEMA_VERSION as Cl}from"@flopay/shared";import{useCallback as Sl,useRef as Ho}from"react";import{useEffect as vl,useLayoutEffect as Pl}from"react";var Vo=typeof window>"u"?vl:Pl;var wl={"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 kl(e){return e==="stripe"||e==="paypal"?e:void 0}function Il(e){let t=kl(e.provider),n={schemaVersion:Cl,...t?{gateway:t}:{}};if(e.class==="lifecycle"){let r=wl[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 xa=new Set(["checkout_mount","sdk_loaded","form_rendered","card_expanded"]);function jr(e,t){let n=Ho(e);n.current=e;let r=Ho(new Set),o=Ho(t),a=Ho(t);return Vo(()=>{a.current=t,o.current!==t&&(o.current=t,r.current.clear())},[t]),Sl(c=>{if(a.current!==t)return;let s=Il(c);if(s){if(xa.has(s.name)){if(r.current.has(s.name))return;r.current.add(s.name)}tt(()=>n.current?.(s))}},[t])}var El=Symbol.for("@flopay/js.telemetry.bridge.v1"),Rl=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function _l(){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 xl(e){let t=_l(),n=(o,a)=>o?o.bind(e):a,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 Yo(e){let t=globalThis[Rl];return xl(t?.(e)??{})}function jt(e){if(e)return e[El]}import{jsx as pr,jsxs as Ma}from"react/jsx-runtime";var Wo=45,Nl=1e3,Dl=11e3,Ll=["https://www.paypal.com","https://www.sandbox.paypal.com"],Zi="We couldn't open PayPal. Try again or choose another payment method.",Ol={width:"100%",minHeight:Wo,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 Qi(e){return e.includes("No ack for postMessage init()")&&Ll.some(t=>e.includes(t))&&e.includes("10000ms")}function zl(e){return e?`${Zi} Allow pop-ups for this site, then try again.`:Zi}function Ul(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 es({sessionId:e,nonce:t,billingApiUrl:n,email:r,billingName:o,onBuyerIdentityReady:a,clientId:c,environment:s,currency:S,isSubscription:b,providerObjectType:g,onTokenizedBody:m,onComplete:M,onErrorChange:D,onDecline:u,onTechnicalFailure:w,isProcessing:ve=!1,onLoadStateChange:H,onInitializationStateChange:P,allowAutomaticRetry:fe=!0,onButtonClick:Q,runBeforeButtonClick:ce,session:oe,existingOrderId:Ce,telemetry:He,telemetryContext:be,onInstrument:Rt,debug:De=!1}){let Te=ur(),Ae=jr(Rt,e),ee=bo(()=>{if(Te)return null;let v=Yo({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:Bl,enabled:He!==!1});return v.setCheckoutContext(be??{}),v.beginCheckout(be??{}),v},[n,Te,He,be?.checkoutMode,be?.layout]),J=bo(()=>jt(Te),[Te]);ft(()=>()=>{ee&&ee.flush().catch(()=>{}).finally(()=>ee.destroy())},[ee]);let L=bo(()=>({error:v=>{J?J.error(v):ee?.error(v),Ae({class:"technical_error",errorCode:v.requestCategory==="intent_create"?"PAYMENT_PROCESSING_FAILED":v.errorCode,requestCategory:v.requestCategory,provider:v.provider})},log:v=>{J?J.log(v):ee?.log(v),Ae({class:"lifecycle",name:v.name,provider:v.provider})},performance:v=>{J?J.performance(v):ee?.performance(v)},terminal:v=>{J?J.terminal(v):ee?.terminal(v)},startTiming:()=>J?.now()??ee?.now()??0,elapsed:v=>J?.elapsed(v)??Math.max(0,(ee?.now()??v)-v)}),[Ae,J,ee]),me=Ve(null),et=Ve(0),Ue=Ve(null),Ye=Ve(!1),[te,T]=nr(!1),[ae,Fe]=nr(!1),[ie,j]=nr(0),_e=Ve(0),[Je,We]=nr(!1),Se=Ve(!1),G=Ve(!1),[Y,$]=nr(!1),[we,Me]=nr(!1),[x,K]=nr(!1),[I,C]=nr(!1),nt=kn(o??[oe?.customer?.firstName,oe?.customer?.lastName].filter(Boolean).join(" ")),St=!x&&a&&!Go(r?.trim()||oe?.customer?.email?.trim())?{email:r?.trim()||oe?.customer?.email?.trim(),firstName:nt.firstName,lastName:nt.lastName}:null,{request:de,collect:ct,finish:it}=qr(),rt=bo(()=>n.replace(/\/+$/,""),[n]),je=g??(b?"subscription":"order"),y=g==="order"||g==="setup_token",U=bo(()=>JSON.stringify([rt,c,S,s??"",je,y,e,Ce??""]),[rt,c,S,s,Ce,je,y,e]),Xe=Ve(U),dt=Xe.current!==U,[Mt,Bt]=nr([]),W=v=>{De&&Bt(ut=>[...ut,`${new Date().toISOString().slice(11,23)} ${v}`])},Le=Ve(m),Wt=Ve(M),wt=Ve(D),Ot=Ve(u),Rn=Ve(w),_n=Ve(Q),Zn=Ve(H),Jt=Ve(P),cn=Ve(a),dn=Ve(ce),Ft=Ve(oe),vn=Ve(r),bt=Ve(o),ir=Ve(null),Ht=Ve(e),sr=Ve(t),Nt=Ve(null),zn=Ve(0),ot=Ve(null),_t=Ve(null),xt=Ve(new Map),tn=Ve(new Map),un=Ve(!1);ft(()=>(un.current=!0,()=>{un.current=!1}),[]),ft(()=>{Le.current=m},[m]),ft(()=>{cn.current=a},[a]),ft(()=>{Wt.current=M},[M]),ft(()=>{wt.current=D},[D]),ft(()=>{Ot.current=u},[u]),ft(()=>{Rn.current=w},[w]),ft(()=>{_n.current=Q},[Q]),ft(()=>{Zn.current=H},[H]),ft(()=>{Jt.current=P},[P]),ft(()=>{dn.current=ce},[ce]),ft(()=>{Ft.current=oe},[oe]),ft(()=>{vn.current=r},[r]),ft(()=>{bt.current=o},[o]),ft(()=>{sr.current=t},[t]),ft(()=>{Ht.current!==e&&(Ht.current=e,ir.current=null,K(!1),C(!1))},[e]),ft(()=>{_e.current=ie},[ie]),ft(()=>{Je&&Ue.current?.focus()},[Je,ie]);let pn=ho(()=>{window.setTimeout(()=>{Ue.current?.focus()},0)},[]),Un=ho(async v=>{C(!0);try{await cn.current?.(v),ir.current=v,vn.current=v.email,bt.current=[v.firstName,v.lastName].filter(Boolean).join(" "),K(!0),tt(()=>wt.current?.(null))}catch(ut){let qe=ut instanceof Error?ut.message:"Buyer details could not be attached to checkout.";tt(()=>wt.current?.(qe))}finally{C(!1)}},[]),qn=ho(()=>{T(!1),j(v=>v+1)},[]),zt=ho(()=>{We(!1),(me.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??me.current)?.focus?.()},[]);ft(()=>{!te||!Ye.current||(Ye.current=!1,zt())},[zt,te,ie]);let X=ho((v,ut)=>{let qe=Rn.current;if(qe){qe("paypal",v,ut);return}wt.current?.(zl(ut?.popupBlocked??dr(v)))},[]),Pn=()=>{ot.current?.timer&&(clearTimeout(ot.current.timer),ot.current.timer=null)},xn=()=>{Pn();let v=zn.current+1;return zn.current=v,_t.current=null,ot.current={generation:v,timer:null,yieldedControl:!1},We(!1),v},Qn=v=>v!==void 0&&ot.current?.generation!==v?!1:(Pn(),ot.current=null,_t.current=null,!0),br=v=>{let ut=v?.generation??ot.current?.generation??zn.current;(!v?.generation||ot.current?.generation===ut)&&(Pn(),ot.current=null),_t.current=ut,v?.showRetry&&We(!0),v?.remount&&qn(),v?.focus!==!1&&pn()},Tr=v=>ot.current?.generation===v&&_t.current!==v,Tn=v=>{typeof document<"u"&&document.visibilityState!=="visible"||(Pn(),v.timer=setTimeout(()=>{ot.current?.generation===v.generation&&(ot.current=null,_t.current=v.generation,X(new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}),We(!0),qn(),pn())},600))},mn=()=>{let v=ot.current;v?.yieldedControl&&Tn(v)},Be=()=>{let v=ot.current;v&&(v.yieldedControl=!0,Pn())},Xt=v=>{let ut=Nt.current;return ut&&tn.current.set(v,ut),v};ft(()=>{let v=()=>{document.visibilityState==="visible"?mn():Be()};return document.addEventListener("visibilitychange",v),window.addEventListener("focus",mn),window.addEventListener("blur",Be),()=>{document.removeEventListener("visibilitychange",v),window.removeEventListener("focus",mn),window.removeEventListener("blur",Be),Pn()}},[]),ft(()=>{Xe.current!==U&&(Xe.current=U,Se.current=!1,G.current=!1,T(!1),Fe(!1),$(!1),Jt.current?.("loading"))},[U]),ft(()=>{tt(()=>Zn.current?.(te&&!Y))},[te,Y]);let Dt=Ml(s);ft(()=>{let v=c?`${c.slice(0,6)}\u2026(len ${c.length})`:"(empty)",ut=typeof navigator<"u"?navigator.userAgent:"(no navigator)";if(W(`mount clientId=${v} env=${s??"(unset)"}\u2192${Dt??"live"} ccy=${S} sub=${b}`),W(`ua=${ut.slice(0,80)}${ut.length>80?"\u2026":""}`),!c){W("FAIL: clientId empty \u2014 gateway misconfigured"),$(!0),L.error({errorCode:"CONFIGURATION_INVALID",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),console.error("[FloPay] DirectPayPal: clientId empty \u2014 gateway misconfigured");return}if(!me.current){W("FAIL: containerRef not attached");return}et.current=L.startTiming(),L.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let qe=!1,yn=!1,Ze=()=>qe||yn,Ut,lr=!1,jn=()=>{Ut=Al(),Ut||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),lr=!0},Cn=null,Zt=!1,fn=null,gn=!1,xe=()=>{!fn||gn||(gn=!0,fn.close().catch(()=>{}))},kt=null,Tt=()=>{kt!==null&&(L.log({name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal"}),L.performance({stage:"overlay_return",durationMs:L.elapsed(kt),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal"}),kt=null)},An=!1,hn=me.current,Mn=null,Bn=null,qt=[],on=d=>{if(!d||typeof d.getBoundingClientRect!="function")return"(no rect)";let p=d.getBoundingClientRect();return`${Math.round(p.width)}\xD7${Math.round(p.height)}`},an=d=>{if(!d)return"(empty)";try{let p=new URL(d,typeof window<"u"?window.location.href:"https://localhost"),k=p.pathname.toLowerCase();return k.includes("checkcaptcha")||k.includes("captcha")?`CAPTCHA(${p.host}${k})`:k.includes("risk")||k.includes("challenge")?`RISK(${p.host}${k})`:k.includes("smart/buttons")?`smart-buttons(${p.host})`:`${p.host}${k}`.slice(0,100)}catch{return d.slice(0,80)}},er=d=>{let p=d.getAttribute("src"),k=d.getAttribute("srcdoc"),Ee=d.getAttribute("name"),q=d.getAttribute("sandbox"),F=[];return p&&F.push(`src=${an(p)}`),k&&F.push(`srcdoc[${k.length}ch]`),!p&&!k&&F.push("src=(empty) srcdoc=(empty)"),Ee&&F.push(`name=${Ee.slice(0,40)}`),q!==null&&F.push(`sandbox="${q.slice(0,40)}"`),F.join(" ")},Ar=d=>{if(!(d instanceof HTMLIFrameElement))return"";try{let p=d.contentDocument;if(!p)return"cd=null";let k=p.body?.children.length??0,Ee=p.body?.innerHTML.length??0,q=p.head?.innerHTML.length??0;return`cd=same-origin readyState=${p.readyState} body[${k}children,${Ee}ch] head[${q}ch]`}catch(p){return`cd=cross-origin(${p.message.slice(0,30)})`}},Fn=[],Kn=d=>{if(Ze())return;let p=d.message??String(d.error??"(no message)");p&&(p.toLowerCase().includes("paypal")||p.toLowerCase().includes("zoid")||p.toLowerCase().includes("postrobot")||p.toLowerCase().includes("storage"))&&(W(`window:error ${p.slice(0,140)}`),Fn.push(p))},Qt=d=>{if(Ze())return;let p=d.reason instanceof Error?d.reason.message:String(d.reason??"(no reason)");p&&(p.toLowerCase().includes("paypal")||p.toLowerCase().includes("zoid")||p.toLowerCase().includes("postrobot")||p.toLowerCase().includes("storage"))&&(W(`window:rejection ${p.slice(0,140)}`),Fn.push(p))};De&&typeof window<"u"&&(window.addEventListener("error",Kn),window.addEventListener("unhandledrejection",Qt));let at={value:0};if(De&&typeof PerformanceObserver<"u")try{Bn=new PerformanceObserver(d=>{if(!Ze())for(let p of d.getEntries()){if(!p.name.toLowerCase().includes("paypal"))continue;at.value+=1;let k=Math.round(p.duration);W(`net ${k}ms ${p.name.slice(0,90)}`)}}),Bn.observe({type:"resource",buffered:!0})}catch{}let Yt=()=>{for(Mn?.disconnect(),Mn=null,Bn?.disconnect(),Bn=null;qt.length;)clearTimeout(qt.pop());De&&typeof window<"u"&&(window.removeEventListener("error",Kn),window.removeEventListener("unhandledrejection",Qt))},_=d=>{if(!d)return!1;let p=d.toLowerCase();return p.includes("zoid destroyed")||p.includes("destroyed all components")||p.includes("window closed")||p.includes("detected container element removed")},E=d=>{if(Ze()||_(d))return;let p=cr(d)??d;tt(()=>wt.current?.(p))},V=d=>{qe||($(!0),d.includes("paypal_ineligible")||L.error({errorCode:"PROVIDER_LOAD_FAILED",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime"}),console.error("[FloPay] DirectPayPal load/render failure:",d))},Z=(d,p=!1)=>{if(qe)return;let k=Se.current||!fe;if(Zt)return;Zt=!0,yn=!0,Yt(),xe();let Ee=p||Qi(d);if(Ee&&fe&&!Se.current){Se.current=!0,T(!1),Me(!1),Fe(!0),Jt.current?.("retrying"),Cn=setTimeout(()=>{qe||j(q=>q+1)},Nl);return}if(Ee||k){if(T(!1),Me(!1),Fe(!1),$(!0),Jt.current?.("exhausted"),!G.current){G.current=!0;let q=Qi(d)?"paypal_init_timeout":p?"paypal_render_timeout":"paypal_init_failure";console.error("[FloPay] Direct PayPal initialization failed:",q)}return}V(d)};$(!1);let $e=async(d,p=Nt.current)=>{if(Ze())return;let k=p?.sessionId??e;if(Le.current){await Le.current(d,{sessionId:k,accountPatch:p?.accountPatch,nonce:p?.nonce});return}let Ee=L.startTiming();L.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let q=()=>{L.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),L.performance({stage:"processing",durationMs:L.elapsed(Ee),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})};try{let F=Ft.current,Ge=p?.accountPatch?.email??vn.current,Qe=p?.accountPatch?.userId??F?.customer?.id??F?.accountData?.userId??"",ue=await new Ta(rt,{telemetry:!1}).processPayment(Qe,{sessionId:k,nonce:p?.nonce??sr.current,tokenizedData:d,accountData:{userId:Qe,email:Ge??F?.customer?.email??"",firstName:p?.accountPatch?.firstName??F?.customer?.firstName??F?.accountData?.firstName??"",lastName:p?.accountPatch?.lastName??F?.customer?.lastName??F?.accountData?.lastName??"",country:p?.accountPatch?.country??F?.customer?.country??F?.accountData?.country??void 0,zip:p?.accountPatch?.zip??F?.customer?.zip??F?.accountData?.zip??void 0}});if(ue.ok){if(yn||qe&&un.current)return;q(),L.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),tt(()=>Wt.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(Ze())return;let A=await ue.json().catch(()=>null),le=A?.message??"PayPal payment failed.",st=cr(le)??le;q(),ue.status===400&&(typeof A?.declineCode=="string"||!Array.isArray(A?.fields))?L.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):ue.status===400||ue.status===422?L.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx"}):L.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:ue.status>=500?"5xx":ue.status>=400?"4xx":ue.status>=300?"3xx":"unknown",failureCategory:ue.status>=500?"server_error":void 0}),E(st),tt(()=>Ot.current?.($t("paypal",st,{code:A?.code,declineCode:A?.declineCode})));return}catch(F){if(Ze())return;q(),L.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let Ge=F instanceof Error?F.message:"PayPal payment failed.",Qe=cr(Ge)??Ge;E(Qe),tt(()=>Ot.current?.($t("paypal",Qe)));return}},ne=()=>new Xi("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),B=d=>Ze()?Promise.reject(ne()):Promise.resolve(d),h=async d=>{if(Ze())throw ne();lr||jn();let p=Nt.current,k=p?.sessionId??e,Ee=p?.nonce??sr.current;L.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let q;try{q=await new Ta(rt,{telemetry:!1}).createSessionIntent(k,Ee??"",y?{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:Aa,paymentMethodId:null,intentKind:je==="setup_token"?"setup":"payment"}:{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"},{idempotencyKey:Ut})}catch(F){throw L.error({...Tl(F,"PAYMENT_PROCESSING_FAILED","unknown"),stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"}),F}if(Ze())throw ne();if(q.provider!=="paypal"||q.providerObjectType!==je)throw new Error(d);return L.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),q.providerObjectId},f=(d,p)=>{let k=p?.nonce??sr.current;if(!k)return;let Ee=p?.sessionId??e,q=$r(d)??tr(d)??"provider_declined";new Ta(rt,{telemetry:!1}).reportSessionIntentDecline(Ee,k,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:q}).catch(()=>{})},O=ie;W("loadScript:scheduled (deferred 1 tick)");let pt=null,vt=setTimeout(()=>{if(qe){W("loadScript:skipped (cancelled before defer ran)");return}W("loadScript:start");let d=Dt==="live"?"production":Dt;pt=Fl({clientId:c,currency:S,...je==="subscription"?{intent:"subscription",vault:!0}:je==="order"?{intent:"capture"}:{},...d?{environment:d}:{},...d==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}}),pt.then(p=>{if(W(`loadScript:resolved inactive=${Ze()} ns=${!!p} buttons=${!!p?.Buttons}`),Ze())return;if(!p?.Buttons){W("FAIL: namespace missing Buttons factory"),Z("PayPal SDK did not expose the Buttons factory.");return}L.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),L.performance({stage:"provider_ready",durationMs:L.elapsed(et.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),L.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let k=async(se,ue)=>{if(Ze()||_e.current!==O)return;let A=se.vaultSetupToken??se.subscriptionID??se.orderID??"",le=A?tn.current.get(A):xt.current.get(O);if(!(!le||!Tr(le.generation))&&Qn(le.generation)){tn.current.delete(A),xt.current.delete(le.surfaceKey),Tt();try{if(Me(!0),tt(()=>wt.current?.(null)),!A)throw new Xi("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});let st=Ft.current,Lt=kn(bt.current??[st?.customer?.firstName,st?.customer?.lastName].filter(Boolean).join(" ")),ge={email:le.accountPatch?.email?.trim()||vn.current?.trim()||st?.customer?.email?.trim(),firstName:le.accountPatch?.firstName?.trim()||Lt.firstName,lastName:le.accountPatch?.lastName?.trim()||Lt.lastName};if(!Go(ge.email)||!(ge.firstName||ge.lastName))try{let bn=Ul(await ue?.order?.get?.());ge={email:bn.email||ge.email,firstName:bn.firstName||ge.firstName,lastName:bn.lastName||ge.lastName}}catch{}if(cn.current&&(!Go(ge.email)||!(ge.firstName||ge.lastName))){let bn=await ct("PayPal",ge);if(!bn)return;ge=bn}Go(ge.email)&&(ge.firstName||ge.lastName)&&(le.accountPatch={...le.accountPatch,...ge},await cn.current?.(ge)),await $e(je==="setup_token"?{id:A,type:"paypal_setup_token",isPaypal:!0,gateway:"paypal",paymentMethodType:Aa}:y?{id:A,isPaypal:!0,gateway:"paypal",paymentMethodType:Aa}:{id:A,isPaypal:!0},le)}catch(st){E(st instanceof Error?st.message:"PayPal capture failed.")}finally{Ze()||Me(!1)}}},Ee=p.Buttons({style:{layout:"horizontal",height:Wo,tagline:!1},onClick:async(se,ue)=>{if(Ze()){await ue.reject();return}jn();let A=dn.current,le={accountPatch:ir.current??void 0};if(A)try{let ge=await A("paypal");if(Ze()){await ue.reject();return}if(!ge.proceed){Nt.current=null,xt.current.delete(O),await ue.reject();return}le={sessionId:ge.sessionId,accountPatch:{...ir.current,...ge.accountPatch},nonce:ge.nonce}}catch(ge){W(`onClick:runBeforeButtonClick rejected msg=${(ge instanceof Error?ge.message:String(ge)).slice(0,120)}`),Nt.current=null,xt.current.delete(O),await ue.reject();return}tt(()=>_n.current?.("paypal"));let Lt={generation:xn(),surfaceKey:O,...le};Nt.current=Lt,xt.current.set(O,Lt),await ue.resolve(),L.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),L.log({name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),L.log({name:"provider.overlay.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),kt=L.startTiming()},createOrder:je==="order"?Ce?()=>B(Ce).then(Xt):()=>h("Failed to create PayPal order.").then(Xt):void 0,createSubscription:je==="subscription"?Ce?()=>B(Ce).then(Xt):()=>h("Failed to create PayPal subscription.").then(Xt):void 0,createVaultSetupToken:je==="setup_token"?()=>h("Failed to create PayPal setup token.").then(Xt):void 0,onApprove:k,onCancel:()=>{if(Ze())return;let se=xt.current.get(O)??Nt.current;se&&xt.current.delete(se.surfaceKey),Nt.current=null,Tt(),L.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),Ye.current=!0,br({generation:se?.generation,remount:!0,focus:!1})},onError:se=>{if(Ze()||_e.current!==O)return;let ue=se instanceof Error?se.message:"PayPal failed to render.";if(W(`onError rendered=${An} msg=${ue.slice(0,120)}`),An){let A=xt.current.get(O)??Nt.current;if(A&&!Tr(A.generation)||!A&&_t.current===zn.current)return;if(_(ue)){Qn(A?.generation);return}if(Tt(),go(se)){L.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),f(se,A),tt(()=>Ot.current?.($t("paypal",ue))),A&&xt.current.delete(A.surfaceKey),Nt.current=null,Qn(A?.generation);return}let le=ue.toLowerCase();L.error({errorCode:le.includes("popup")&&le.includes("block")?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),A&&xt.current.delete(A.surfaceKey),Nt.current=null,br({generation:A?.generation,remount:!0,showRetry:!0,focus:!0}),X(se,{code:"paypal_runtime_failed"});return}Z(ue)}}),q=Ee.isEligible();if(W(`isEligible=${q}`),L.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!q){T(!1),Z("PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}fn=Ee,De&&W(`container:dims ${on(hn)} visibility=${typeof document<"u"?document.visibilityState:"(no document)"}`),De&&typeof MutationObserver<"u"&&(Mn=new MutationObserver(se=>{if(!Ze()){for(let ue of se)if(ue.type==="childList")ue.addedNodes.forEach(A=>{if(!(A instanceof Element))return;let le=A.tagName.toLowerCase(),st=(A.getAttribute("title")??"").slice(0,40),Lt=le==="iframe"?` ${er(A)}`:"";W(`child+ ${le}${st?` title="${st}"`:""}${Lt} dims=${on(A)}`)});else if(ue.type==="attributes"&&ue.target instanceof Element){let A=ue.target;if(A.tagName.toLowerCase()!=="iframe")continue;let le=ue.attributeName;(le==="src"||le==="srcdoc")&&W(`attr~ iframe ${le}=${le==="srcdoc"?`[${(A.getAttribute("srcdoc")??"").length}ch]`:an(A.getAttribute("src"))} dims=${on(A)}`)}}}),Mn.observe(hn,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let Ge=se=>{if(Ze()||An)return;let ue=hn.querySelectorAll("iframe"),A=typeof document<"u"&&"hasStorageAccess"in document;W(`watchdog:${se} container=${on(hn)} children=${hn.childElementCount} iframes=${ue.length} visibility=${typeof document<"u"?document.visibilityState:"(no document)"} cookies=${typeof navigator<"u"?navigator.cookieEnabled:"?"} hasStorageAccessApi=${A} paypalNetRequests=${at.value}`),ue.forEach((le,st)=>{let Lt=(le.getAttribute("title")??"").slice(0,40);W(` iframe[${st}] ${on(le)}${Lt?` title="${Lt}"`:""} ${er(le)}`);let ge=Ar(le);ge&&W(` ${ge}`)}),Fn.length===0&&W(" (no PayPal/zoid window errors captured)")};De&&(qt.push(setTimeout(()=>Ge("3s"),3e3)),qt.push(setTimeout(()=>Ge("8s"),8e3)),qt.push(setTimeout(()=>Ge("15s"),15e3))),W("render:start");let Qe=L.startTiming();qt.push(setTimeout(()=>{Ze()||An||(W("watchdog:11s retryable render timeout"),Z("PayPal Buttons render did not settle within 11000ms.",!0))},Dl)),Ee.render(hn).then(()=>{if(W(`render:resolved inactive=${Ze()}`),Yt(),Ze()){xe();return}An=!0,T(!0),Fe(!1),Jt.current?.("ready"),L.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),L.performance({stage:"checkout_render",durationMs:L.elapsed(Qe),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}).catch(se=>{let ue=se instanceof Error?se.message:"PayPal failed to render.";W(`render:rejected msg=${ue.slice(0,120)}`),Yt(),Z(ue)})}).catch(p=>{let k=p instanceof Error?p.message:"PayPal SDK failed to load.";W(`loadScript:rejected msg=${k.slice(0,120)}`),Z(k)})},0);return()=>{qe=!0,clearTimeout(vt),Cn&&clearTimeout(Cn),Yt(),xe()}},[fe,rt,c,S,s,je,y,e,Ce,ie,L,ct]);let $n=De?Ma("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:Y?"#fef2f2":"#f3f4f6",border:`1px solid ${Y?"#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=${te} failed=${Y})`,Mt.length===0?`
1
+ import{a as at,b as qn,c as va,d as lo,e as Mi,f as Fi,g as rl,h as ol}from"./chunk-W24FSJC5.mjs";import{dropThirdPartyOnlyError as tp}from"@flopay/shared";import{PaymentAPI as ni}from"@flopay/js";import{FloPayError as Xr,resolveBillingApiUrl as Vc,resolveButtonsLayoutTheme as Hc,resolveTheme as Yc}from"@flopay/shared";import{useCallback as mr,useEffect as Gr,useMemo as So,useRef as Wr,useState as wo}from"react";import{Fragment as Dr,jsx as kn,jsxs as Di}from"react/jsx-runtime";function al(){return Di(Dr,{children:[Di("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[kn("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),kn("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",kn("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"#9ca3af",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{position:"absolute",right:"1rem"},"aria-hidden":"true",children:kn("path",{d:"M9 18l6-6-6-6"})})]})}function il(){return kn(Dr,{children:"Go back"})}function sl(){return kn(Dr,{children:"Secure card checkout"})}function Ar(e){return e!==void 0&&(e===""||e===null||e===!1)}function Mr({content:e}){return kn(Dr,{children:e===void 0?kn(al,{}):e})}function Fr({content:e}){return kn(Dr,{children:e===void 0?kn(il,{}):e})}function co({content:e}){return kn(Dr,{children:e===void 0?kn(sl,{}):e})}import{FloPayError as Pa,isMoneySettledOutcome as ll,isSetupIntentClientSecret as ad,isValidEmail as cl}from"@flopay/shared";function Lr(e,t,n,r={}){let o;return(a={})=>{if(o)return o;let d={...r,...a,email:a.email?.trim()||r.email?.trim()};if(!cl(d.email))return Promise.reject(new Pa("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}));let l={};for(let[S,g]of Object.entries(d)){if(typeof g!="string")continue;let h=g.trim();h&&(l[S]=h)}return o=e.claimCheckoutSession(t,n,{accountData:l}),o.catch(()=>{}),o}}function Li(e,t){return t?e?{account:{...e.account??{},...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}:t:e}function Ca(e,t){return t?{...e,account:{...e.account,...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}:e}function Ni(e,t){let n=e.products??[...(e.subscriptions??[]).map(a=>({type:"subscription",code:a.code??a.providerPlanId,name:a.subscriptionName??a.providerPlanName??a.code??a.providerPlanId??null,quantity:a.quantity??1,totalAmount:a.totalAmount,overrideAmount:a.overrideAmount,currency:a.currency,metadata:a.metadata})),...(e.items??[]).map(a=>({type:"item",code:a.code??a.providerItemId,name:a.itemName??a.providerItemName??a.code??a.providerItemId??null,quantity:a.quantity??1,totalAmount:a.totalAmount,overrideAmount:a.overrideAmount,currency:a.currency,metadata:a.metadata}))],r=n.reduce((a,d)=>a+(d.overrideAmount??d.totalAmount??0),0),o=e.currency??n.find(a=>a.currency)?.currency??"USD";return{id:"",clientSecret:"",mode:n.some(a=>a.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((a,d)=>({uuid:`synthetic-${a.type??"item"}-${d}`,checkoutSessionId:"",type:a.type??"item",code:a.code,name:a.name??null,quantity:a.quantity??1,totalAmount:a.totalAmount,overrideAmount:a.overrideAmount??null,currency:a.currency??o,metadata:a.metadata??null}))}}function vr(e){let t=e?.trim().split(/\s+/).filter(Boolean)??[];return t.length===0?{}:{firstName:t[0],lastName:t.length>1?t.slice(1).join(" "):void 0}}function Sa(e,t){return t?{...e,...t}:e}function Ft(e,t,n){let r=typeof t=="string"?t:t.message,o=typeof t=="string"?n?.code:n?.code??t.code,a=typeof t=="string"?n?.declineCode:n?.declineCode??t.declineCode;return{method:e,message:r,...o?{code:o}:{},...a?{declineCode:a}:{}}}var dl=[{match:/^paypal authorization required\.?$/i,replacement:"For your additional security, please re-authenticate this payment via PayPal."}];function sr(e){if(typeof e!="string")return e??void 0;let t=e.trim();if(!t)return e;for(let{match:n,replacement:r}of dl)if(n.test(t))return r;return e}function Pr(e,t){return e.status!=="authorized"?{status:"succeeded"}:{status:"authorized",paymentId:e.paymentId,sessionId:e.id||t||void 0,authorizationExpiresAt:e.authorizationExpiresAt}}function Nr(e){return e?.status==="authorized"||e?.status==="complete"}function Oi(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function Fo(e){let t=Oi(e);return new Pa(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function Do(e){let t=Oi(e);return new Pa(t?"Authorization has expired.":"Automatic payment failed. Please try again.","api_error",{code:t?"authorization_expired":e?.status==="expired"?"checkout_session_expired":"checkout_processing_timeout"})}function Lo(e,t){return e==="processing"||ll(e,t)}function zi(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}function Ui(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?{mode:"setup"}:{mode:"payment",amount:e}}function uo(e){let t=[e?.id,e?.originalPaymentMethodId];for(let n of t)if(typeof n=="string"&&n.startsWith("pm_"))return n}import{PaymentAPI as Qo,SESSION_CREATE_TELEMETRY as _c}from"@flopay/js";import{buildCheckoutDisplayData as xc,classifyTelemetryFailure as _s,FloPayError as Lt,foldIntoProducts as Tc,isDetachedSessionEligible as Bc,resolveBillingApiUrl as Ac,resolveButtonsLayoutTheme as Mc,resolveIdempotencyKey as xs,resolveSessionCurrency as Fc,resolveTheme as Ms,SDK_VERSION as Fs,telemetryStatusClass as Dc}from"@flopay/shared";import ja,{useCallback as jn,useEffect as Kn,useMemo as Rn,useRef as Et,useState as wt}from"react";import{createContext as qi}from"react";var In=qi({flopay:null,paypalFlopay:null,billingApiUrl:""}),Bn=qi({session:null,loading:!1,error:null});import{PaymentAPI as Ia}from"@flopay/js";import{classifyTelemetryFailure as El,FloPayError as Yi,generateIdempotencyKey as _l,isValidEmail as yo,normalizeGatewayEnvironment as xl,PAYPAL_VAULTED_PAYMENT_METHOD_TYPE as Ra,SDK_VERSION as Tl}from"@flopay/shared";import{loadScript as Bl}from"@paypal/paypal-js";import{useCallback as qo,useEffect as gt,useMemo as fo,useRef as Ge,useState as Sr}from"react";import{isValidEmail as ul}from"@flopay/shared";import{useCallback as $i,useEffect as pl,useRef as ji,useState as Vi}from"react";import{jsx as Ki,jsxs as po}from"react/jsx-runtime";function sn(e){let{firstName:t,lastName:n,...r}=e,o=t?.trim(),a=n?.trim();return{...r,...o?{firstName:o}:{},...a?{lastName:a}:{}}}function Or(){let[e,t]=Vi(null),n=ji(null),r=ji(0),o=$i((d,l)=>(n.current?.(null),r.current+=1,t({id:r.current,methodLabel:d,identity:l}),new Promise(S=>{n.current=S})),[]),a=$i(d=>{let l=n.current;n.current=null,t(null),l?.(d)},[]);return pl(()=>()=>{n.current?.(null),n.current=null},[]),{request:e,collect:o,finish:a}}function zr({identity:e,methodLabel:t,onComplete:n,onCancel:r,submitting:o=!1,testId:a="flopay-buyer-identity-pane"}){let[d,l]=Vi(e.email?.trim()??""),S=ul(d.trim());return po("div",{"data-testid":a,style:{display:"flex",flexDirection:"column",gap:"0.75rem",padding:"0.875rem",border:"1px solid #d1d5db",borderRadius:8,background:"#fff",color:"#262833"},children:[po("div",{style:{fontWeight:700},children:["Continue with ",t]}),po("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",Ki("input",{type:"email",autoComplete:"email","data-testid":"flopay-email",required:!0,value:d,onChange:g=>l(g.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]}),po("div",{style:{display:"flex",gap:"0.5rem"},children:[r&&Ki("button",{type:"button",onClick:r,style:{flex:1,minHeight:42},children:"Cancel"}),po("button",{type:"button",disabled:!S||o,onClick:()=>{n(sn({...e,email:d.trim()}))},style:{flex:2,minHeight:42},children:["Continue with ",t]})]})]})}function ml(e){if(e instanceof Error)return e.message;if(typeof e=="object"&&e!==null){let t=e.message;return typeof t=="string"?t:void 0}return typeof e=="string"?e:void 0}function Cr(e){if(typeof e!="string")return;let t=e.trim();return/^[a-z0-9_.-]{1,64}$/i.test(t)?t:void 0}function Zn(e){if(typeof e!="object"||e===null)return;let t=e;return Cr(t.code)??Cr(t.type)??Cr(t.name)}function Ur(e){if(!(typeof e!="object"||e===null))return Cr(e.decline_code)}function mo(e){return typeof e!="object"||e===null?!1:Cr(e.type)?.toLowerCase()==="card_error"||Ur(e)!==void 0}function lr(e){let t=ml(e)?.toLowerCase()??"",r=`${Zn(e)?.toLowerCase()??""} ${t}`;return r.includes("popup")&&r.includes("block")}import{resolveBillingApiUrl as yl}from"@flopay/shared";import{useContext as No}from"react";function cr(){return No(In).flopay}function wa(){return No(In).paypalFlopay??null}function fl(){return No(Bn)}function Hi(){return No(In).billingApiUrl||yl()}import{FLO_INSTRUMENT_SCHEMA_VERSION as bl}from"@flopay/shared";import{useCallback as vl,useRef as zo}from"react";import{useEffect as gl,useLayoutEffect as hl}from"react";var Oo=typeof window>"u"?gl:hl;var Pl={"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 Cl(e){return e==="stripe"||e==="paypal"?e:void 0}function Sl(e){let t=Cl(e.provider),n={schemaVersion:bl,...t?{gateway:t}:{}};if(e.class==="lifecycle"){let r=Pl[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 ka=new Set(["checkout_mount","sdk_loaded","form_rendered","card_expanded"]);function qr(e,t){let n=zo(e);n.current=e;let r=zo(new Set),o=zo(t),a=zo(t);return Oo(()=>{a.current=t,o.current!==t&&(o.current=t,r.current.clear())},[t]),vl(d=>{if(a.current!==t)return;let l=Sl(d);if(l){if(ka.has(l.name)){if(r.current.has(l.name))return;r.current.add(l.name)}at(()=>n.current?.(l))}},[t])}var wl=Symbol.for("@flopay/js.telemetry.bridge.v1"),kl=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function Il(){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 Rl(e){let t=Il(),n=(o,a)=>o?o.bind(e):a,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 Uo(e){let t=globalThis[kl];return Rl(t?.(e)??{})}function Dt(e){if(e)return e[wl]}import{jsx as wr,jsxs as Ea}from"react/jsx-runtime";var $o=45,Al=1e3,Ml=11e3,Fl=["https://www.paypal.com","https://www.sandbox.paypal.com"],Gi="We couldn't open PayPal. Try again or choose another payment method.",Dl={width:"100%",minHeight:$o,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 Wi(e){return e.includes("No ack for postMessage init()")&&Fl.some(t=>e.includes(t))&&e.includes("10000ms")}function Ll(e){return e?`${Gi} Allow pop-ups for this site, then try again.`:Gi}function Nl(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 Ji({sessionId:e,nonce:t,billingApiUrl:n,email:r,billingName:o,onBuyerIdentityReady:a,clientId:d,environment:l,currency:S,isSubscription:g,providerObjectType:h,onTokenizedBody:v,onComplete:A,onErrorChange:F,onDecline:m,onTechnicalFailure:w,isProcessing:ge=!1,onLoadStateChange:V,onInitializationStateChange:C,allowAutomaticRetry:pe=!0,onButtonClick:ne,runBeforeButtonClick:ce,session:de,existingOrderId:ve,telemetry:Ve,telemetryContext:fe,onInstrument:kt,debug:Le=!1}){let Ie=cr(),Re=qr(kt,e),re=fo(()=>{if(Ie)return null;let f=Uo({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:Tl,enabled:Ve!==!1});return f.setCheckoutContext(fe??{}),f.beginCheckout(fe??{}),f},[n,Ie,Ve,fe?.checkoutMode,fe?.layout]),oe=fo(()=>Dt(Ie),[Ie]);gt(()=>()=>{re&&re.flush().catch(()=>{}).finally(()=>re.destroy())},[re]);let D=fo(()=>({error:f=>{oe?oe.error(f):re?.error(f),Re({class:"technical_error",errorCode:f.requestCategory==="intent_create"?"PAYMENT_PROCESSING_FAILED":f.errorCode,requestCategory:f.requestCategory,provider:f.provider})},log:f=>{oe?oe.log(f):re?.log(f),Re({class:"lifecycle",name:f.name,provider:f.provider})},performance:f=>{oe?oe.performance(f):re?.performance(f)},terminal:f=>{oe?oe.terminal(f):re?.terminal(f)},startTiming:()=>oe?.now()??re?.now()??0,elapsed:f=>oe?.elapsed(f)??Math.max(0,(re?.now()??f)-f)}),[Re,oe,re]),_e=Ge(null),xe=Ge(0),Te=Ge(null),Ne=Ge(!1),[Pe,B]=Sr(!1),[se,Ae]=Sr(!1),[le,H]=Sr(0),ke=Ge(0),[We,nt]=Sr(!1),Be=Ge(!1),Y=Ge(!1),[j,q]=Sr(!1),[Ce,qe]=Sr(!1),{request:R,collect:G,finish:_}=Or(),P=Ge({sessionId:e,required:!yo(r?.trim()||de?.customer?.email?.trim())});P.current.sessionId!==e&&(P.current={sessionId:e,required:!yo(r?.trim()||de?.customer?.email?.trim())});let Ze=P.current.required,pt=fo(()=>n.replace(/\/+$/,""),[n]),J=h??(g?"subscription":"order"),Qe=h==="order"||h==="setup_token",Ke=fo(()=>JSON.stringify([pt,d,S,l??"",J,Qe,e,ve??""]),[pt,d,S,l,ve,J,Qe,e]),mt=Ge(Ke),vt=mt.current!==Ke,[b,W]=Sr([]),X=f=>{Le&&W(yt=>[...yt,`${new Date().toISOString().slice(11,23)} ${f}`])},rt=Ge(v),_t=Ge(A),ht=Ge(F),He=Ge(m),$e=Ge(w),Vt=Ge(ne),Ot=Ge(V),xt=Ge(C),mn=Ge(a),En=Ge(ce),Mn=Ge(de),en=Ge(r),_n=Ge(o),Gt=Ge(t),et=Ge(null),yn=Ge(0),Oe=Ge(null),Fn=Ge(null),ot=Ge(new Map),nr=Ge(new Map),zt=Ge(!1);gt(()=>(zt.current=!0,()=>{zt.current=!1}),[]),gt(()=>{rt.current=v},[v]),gt(()=>{mn.current=a},[a]),gt(()=>{_t.current=A},[A]),gt(()=>{ht.current=F},[F]),gt(()=>{He.current=m},[m]),gt(()=>{$e.current=w},[w]),gt(()=>{Vt.current=ne},[ne]),gt(()=>{Ot.current=V},[V]),gt(()=>{xt.current=C},[C]),gt(()=>{En.current=ce},[ce]),gt(()=>{Mn.current=de},[de]),gt(()=>{en.current=r},[r]),gt(()=>{_n.current=o},[o]),gt(()=>{Gt.current=t},[t]),gt(()=>{ke.current=le},[le]),gt(()=>{We&&Te.current?.focus()},[We,le]);let Ht=qo(()=>{window.setTimeout(()=>{Te.current?.focus()},0)},[]),fn=qo(()=>{B(!1),H(f=>f+1)},[]),ln=qo(()=>{nt(!1),(_e.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??_e.current)?.focus?.()},[]);gt(()=>{!Pe||!Ne.current||(Ne.current=!1,ln())},[ln,Pe,le]);let gn=qo((f,yt)=>{let Yt=$e.current;if(Yt){Yt("paypal",f,yt);return}ht.current?.(Ll(yt?.popupBlocked??lr(f)))},[]),Bt=()=>{Oe.current?.timer&&(clearTimeout(Oe.current.timer),Oe.current.timer=null)},rr=()=>{Bt();let f=yn.current+1;return yn.current=f,Fn.current=null,Oe.current={generation:f,timer:null,yieldedControl:!1},nt(!1),f},Ut=f=>f!==void 0&&Oe.current?.generation!==f?!1:(Bt(),Oe.current=null,Fn.current=null,!0),Q=f=>{let yt=f?.generation??Oe.current?.generation??yn.current;(!f?.generation||Oe.current?.generation===yt)&&(Bt(),Oe.current=null),Fn.current=yt,f?.showRetry&&nt(!0),f?.remount&&fn(),f?.focus!==!1&&Ht()},or=f=>Oe.current?.generation===f&&Fn.current!==f,hn=f=>{typeof document<"u"&&document.visibilityState!=="visible"||(Bt(),f.timer=setTimeout(()=>{Oe.current?.generation===f.generation&&(Oe.current=null,Fn.current=f.generation,gn(new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}),nt(!0),fn(),Ht())},600))},tn=()=>{let f=Oe.current;f?.yieldedControl&&hn(f)},Dn=()=>{let f=Oe.current;f&&(f.yieldedControl=!0,Bt())},bn=f=>{let yt=et.current;return yt&&nr.current.set(f,yt),f};gt(()=>{let f=()=>{document.visibilityState==="visible"?tn():Dn()};return document.addEventListener("visibilitychange",f),window.addEventListener("focus",tn),window.addEventListener("blur",Dn),()=>{document.removeEventListener("visibilitychange",f),window.removeEventListener("focus",tn),window.removeEventListener("blur",Dn),Bt()}},[]),gt(()=>{mt.current!==Ke&&(mt.current=Ke,Be.current=!1,Y.current=!1,B(!1),Ae(!1),q(!1),xt.current?.("loading"))},[Ke]),gt(()=>{at(()=>Ot.current?.(Pe&&!j))},[Pe,j]);let Hn=xl(l);gt(()=>{let f=d?`${d.slice(0,6)}\u2026(len ${d.length})`:"(empty)",yt=typeof navigator<"u"?navigator.userAgent:"(no navigator)";if(X(`mount clientId=${f} env=${l??"(unset)"}\u2192${Hn??"live"} ccy=${S} sub=${g}`),X(`ua=${yt.slice(0,80)}${yt.length>80?"\u2026":""}`),!d){X("FAIL: clientId empty \u2014 gateway misconfigured"),q(!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(!_e.current){X("FAIL: containerRef not attached");return}xe.current=D.startTiming(),D.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let Yt=!1,Yn=!1,Me=()=>Yt||Yn,Pt,lt=!1,Wt=()=>{Pt=_l(),Pt||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),lt=!0},Gn=null,nn=!1,ar=null,yr=!1,Pn=()=>{!ar||yr||(yr=!0,ar.close().catch(()=>{}))},Wn=null,cn=()=>{Wn!==null&&(D.log({name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal"}),D.performance({stage:"overlay_return",durationMs:D.elapsed(Wn),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal"}),Wn=null)},At=!1,ae=_e.current,It=null,bt=null,Jt=[],dn=y=>{if(!y||typeof y.getBoundingClientRect!="function")return"(no rect)";let s=y.getBoundingClientRect();return`${Math.round(s.width)}\xD7${Math.round(s.height)}`},Jn=y=>{if(!y)return"(empty)";try{let s=new URL(y,typeof window<"u"?window.location.href:"https://localhost"),c=s.pathname.toLowerCase();return c.includes("checkcaptcha")||c.includes("captcha")?`CAPTCHA(${s.host}${c})`:c.includes("risk")||c.includes("challenge")?`RISK(${s.host}${c})`:c.includes("smart/buttons")?`smart-buttons(${s.host})`:`${s.host}${c}`.slice(0,100)}catch{return y.slice(0,80)}},ir=y=>{let s=y.getAttribute("src"),c=y.getAttribute("srcdoc"),p=y.getAttribute("name"),x=y.getAttribute("sandbox"),ie=[];return s&&ie.push(`src=${Jn(s)}`),c&&ie.push(`srcdoc[${c.length}ch]`),!s&&!c&&ie.push("src=(empty) srcdoc=(empty)"),p&&ie.push(`name=${p.slice(0,40)}`),x!==null&&ie.push(`sandbox="${x.slice(0,40)}"`),ie.join(" ")},Xt=y=>{if(!(y instanceof HTMLIFrameElement))return"";try{let s=y.contentDocument;if(!s)return"cd=null";let c=s.body?.children.length??0,p=s.body?.innerHTML.length??0,x=s.head?.innerHTML.length??0;return`cd=same-origin readyState=${s.readyState} body[${c}children,${p}ch] head[${x}ch]`}catch(s){return`cd=cross-origin(${s.message.slice(0,30)})`}},rn=[],on=y=>{if(Me())return;let s=y.message??String(y.error??"(no message)");s&&(s.toLowerCase().includes("paypal")||s.toLowerCase().includes("zoid")||s.toLowerCase().includes("postrobot")||s.toLowerCase().includes("storage"))&&(X(`window:error ${s.slice(0,140)}`),rn.push(s))},fr=y=>{if(Me())return;let s=y.reason instanceof Error?y.reason.message:String(y.reason??"(no reason)");s&&(s.toLowerCase().includes("paypal")||s.toLowerCase().includes("zoid")||s.toLowerCase().includes("postrobot")||s.toLowerCase().includes("storage"))&&(X(`window:rejection ${s.slice(0,140)}`),rn.push(s))};Le&&typeof window<"u"&&(window.addEventListener("error",on),window.addEventListener("unhandledrejection",fr));let Xn={value:0};if(Le&&typeof PerformanceObserver<"u")try{bt=new PerformanceObserver(y=>{if(!Me())for(let s of y.getEntries()){if(!s.name.toLowerCase().includes("paypal"))continue;Xn.value+=1;let c=Math.round(s.duration);X(`net ${c}ms ${s.name.slice(0,90)}`)}}),bt.observe({type:"resource",buffered:!0})}catch{}let Ln=()=>{for(It?.disconnect(),It=null,bt?.disconnect(),bt=null;Jt.length;)clearTimeout(Jt.pop());Le&&typeof window<"u"&&(window.removeEventListener("error",on),window.removeEventListener("unhandledrejection",fr))},Cn=y=>{if(!y)return!1;let s=y.toLowerCase();return s.includes("zoid destroyed")||s.includes("destroyed all components")||s.includes("window closed")||s.includes("detected container element removed")},un=y=>{if(Me()||Cn(y))return;let s=sr(y)??y;at(()=>ht.current?.(s))},Xe=y=>{Yt||(q(!0),y.includes("paypal_ineligible")||D.error({errorCode:"PROVIDER_LOAD_FAILED",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime"}),console.error("[FloPay] DirectPayPal load/render failure:",y))},pn=(y,s=!1)=>{if(Yt)return;let c=Be.current||!pe;if(nn)return;nn=!0,Yn=!0,Ln(),Pn();let p=s||Wi(y);if(p&&pe&&!Be.current){Be.current=!0,B(!1),qe(!1),Ae(!0),xt.current?.("retrying"),Gn=setTimeout(()=>{Yt||H(x=>x+1)},Al);return}if(p||c){if(B(!1),qe(!1),Ae(!1),q(!0),xt.current?.("exhausted"),!Y.current){Y.current=!0;let x=Wi(y)?"paypal_init_timeout":s?"paypal_render_timeout":"paypal_init_failure";console.error("[FloPay] Direct PayPal initialization failed:",x)}return}Xe(y)};q(!1);let Tt=async(y,s=et.current)=>{if(Me())return;let c=s?.sessionId??e;if(rt.current){await rt.current(y,{sessionId:c,accountPatch:s?.accountPatch,nonce:s?.nonce});return}let p=D.startTiming();D.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let x=()=>{D.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),D.performance({stage:"processing",durationMs:D.elapsed(p),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})};try{let ie=Mn.current,Je=s?.accountPatch?.email??en.current,L=s?.accountPatch?.userId??ie?.customer?.id??ie?.accountData?.userId??"",$=s?.accountPatch?.firstName??ie?.customer?.firstName??ie?.accountData?.firstName,k=s?.accountPatch?.lastName??ie?.customer?.lastName??ie?.accountData?.lastName,E=await new Ia(pt,{telemetry:!1}).processPayment(L,{sessionId:c,nonce:s?.nonce??Gt.current,tokenizedData:y,accountData:{userId:L,email:Je??ie?.customer?.email??"",...$?{firstName:$}:{},...k?{lastName:k}:{},country:s?.accountPatch?.country??ie?.customer?.country??ie?.accountData?.country??void 0,zip:s?.accountPatch?.zip??ie?.customer?.zip??ie?.accountData?.zip??void 0}});if(E.ok){if(Yn||Yt&&zt.current)return;x(),D.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),at(()=>_t.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(Me())return;let K=await E.json().catch(()=>null),he=K?.message??"PayPal payment failed.",ee=sr(he)??he;x(),E.status===400&&(typeof K?.declineCode=="string"||!Array.isArray(K?.fields))?D.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):E.status===400||E.status===422?D.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx"}):D.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:E.status>=500?"5xx":E.status>=400?"4xx":E.status>=300?"3xx":"unknown",failureCategory:E.status>=500?"server_error":void 0}),un(ee),at(()=>He.current?.(Ft("paypal",ee,{code:K?.code,declineCode:K?.declineCode})));return}catch(ie){if(Me())return;x(),D.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let Je=ie instanceof Error?ie.message:"PayPal payment failed.",L=sr(Je)??Je;un(L),at(()=>He.current?.(Ft("paypal",L)));return}},Rt=()=>new Yi("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),Ct=y=>Me()?Promise.reject(Rt()):Promise.resolve(y),M=async y=>{if(Me())throw Rt();lt||Wt();let s=et.current,c=s?.sessionId??e,p=s?.nonce??Gt.current;D.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let x;try{x=await new Ia(pt,{telemetry:!1}).createSessionIntent(c,p??"",Qe?{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:Ra,paymentMethodId:null,intentKind:J==="setup_token"?"setup":"payment"}:{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"},{idempotencyKey:Pt})}catch(ie){throw D.error({...El(ie,"PAYMENT_PROCESSING_FAILED","unknown"),stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"}),ie}if(Me())throw Rt();if(x.provider!=="paypal"||x.providerObjectType!==J)throw new Error(y);return D.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),x.providerObjectId},N=(y,s)=>{let c=s?.nonce??Gt.current;if(!c)return;let p=s?.sessionId??e,x=Ur(y)??Zn(y)??"provider_declined";new Ia(pt,{telemetry:!1}).reportSessionIntentDecline(p,c,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:x}).catch(()=>{})},T=le;X("loadScript:scheduled (deferred 1 tick)");let Z=null,ze=setTimeout(()=>{if(Yt){X("loadScript:skipped (cancelled before defer ran)");return}X("loadScript:start");let y=Hn==="live"?"production":Hn;Z=Bl({clientId:d,currency:S,...J==="subscription"?{intent:"subscription",vault:!0}:J==="order"?{intent:"capture"}:{},...y?{environment:y}:{},...y==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}}),Z.then(s=>{if(X(`loadScript:resolved inactive=${Me()} ns=${!!s} buttons=${!!s?.Buttons}`),Me())return;if(!s?.Buttons){X("FAIL: namespace missing Buttons factory"),pn("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(xe.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),D.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let c=async($,k)=>{if(Me()||ke.current!==T)return;let O=$.vaultSetupToken??$.subscriptionID??$.orderID??"",E=O?nr.current.get(O):ot.current.get(T);if(!(!E||!or(E.generation))&&Ut(E.generation)){nr.current.delete(O),ot.current.delete(E.surfaceKey),cn();try{if(qe(!0),at(()=>ht.current?.(null)),!O)throw new Yi("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});let K=Mn.current,he=vr(_n.current??[K?.customer?.firstName,K?.customer?.lastName].filter(Boolean).join(" ")),ee=sn({email:E.accountPatch?.email?.trim()||en.current?.trim()||K?.customer?.email?.trim(),firstName:E.accountPatch?.firstName?.trim()||he.firstName,lastName:E.accountPatch?.lastName?.trim()||he.lastName});if(!yo(ee.email)||!(ee.firstName||ee.lastName))try{let Ee=Nl(await k?.order?.get?.());ee=sn({email:Ee.email||ee.email,firstName:Ee.firstName||ee.firstName,lastName:Ee.lastName||ee.lastName})}catch{}if((mn.current||Ze)&&!yo(ee.email)){let Ee=await G("PayPal",ee);if(!Ee)return;ee=Ee}yo(ee.email)&&(E.accountPatch=sn({...E.accountPatch,...ee}),await mn.current?.(ee)),await Tt(J==="setup_token"?{id:O,type:"paypal_setup_token",isPaypal:!0,gateway:"paypal",paymentMethodType:Ra}:Qe?{id:O,isPaypal:!0,gateway:"paypal",paymentMethodType:Ra}:{id:O,isPaypal:!0},E)}catch(K){un(K instanceof Error?K.message:"PayPal capture failed.")}finally{Me()||qe(!1)}}},p=s.Buttons({style:{layout:"horizontal",height:$o,tagline:!1},onClick:async($,k)=>{if(Me()){await k.reject();return}Wt();let O=En.current,E={};if(O)try{let ee=await O("paypal");if(Me()){await k.reject();return}if(!ee.proceed){et.current=null,ot.current.delete(T),await k.reject();return}E={sessionId:ee.sessionId,accountPatch:ee.accountPatch,nonce:ee.nonce}}catch(ee){X(`onClick:runBeforeButtonClick rejected msg=${(ee instanceof Error?ee.message:String(ee)).slice(0,120)}`),et.current=null,ot.current.delete(T),await k.reject();return}at(()=>Vt.current?.("paypal"));let he={generation:rr(),surfaceKey:T,...E};et.current=he,ot.current.set(T,he),await k.resolve(),D.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),D.log({name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),D.log({name:"provider.overlay.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),Wn=D.startTiming()},createOrder:J==="order"?ve?()=>Ct(ve).then(bn):()=>M("Failed to create PayPal order.").then(bn):void 0,createSubscription:J==="subscription"?ve?()=>Ct(ve).then(bn):()=>M("Failed to create PayPal subscription.").then(bn):void 0,createVaultSetupToken:J==="setup_token"?()=>M("Failed to create PayPal setup token.").then(bn):void 0,onApprove:c,onCancel:()=>{if(Me())return;let $=ot.current.get(T)??et.current;$&&ot.current.delete($.surfaceKey),et.current=null,cn(),D.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),Ne.current=!0,Q({generation:$?.generation,remount:!0,focus:!1})},onError:$=>{if(Me()||ke.current!==T)return;let k=$ instanceof Error?$.message:"PayPal failed to render.";if(X(`onError rendered=${At} msg=${k.slice(0,120)}`),At){let O=ot.current.get(T)??et.current;if(O&&!or(O.generation)||!O&&Fn.current===yn.current)return;if(Cn(k)){Ut(O?.generation);return}if(cn(),mo($)){D.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),N($,O),at(()=>He.current?.(Ft("paypal",k))),O&&ot.current.delete(O.surfaceKey),et.current=null,Ut(O?.generation);return}let E=k.toLowerCase();D.error({errorCode:E.includes("popup")&&E.includes("block")?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),O&&ot.current.delete(O.surfaceKey),et.current=null,Q({generation:O?.generation,remount:!0,showRetry:!0,focus:!0}),gn($,{code:"paypal_runtime_failed"});return}pn(k)}}),x=p.isEligible();if(X(`isEligible=${x}`),D.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!x){B(!1),pn("PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}ar=p,Le&&X(`container:dims ${dn(ae)} visibility=${typeof document<"u"?document.visibilityState:"(no document)"}`),Le&&typeof MutationObserver<"u"&&(It=new MutationObserver($=>{if(!Me()){for(let k of $)if(k.type==="childList")k.addedNodes.forEach(O=>{if(!(O instanceof Element))return;let E=O.tagName.toLowerCase(),K=(O.getAttribute("title")??"").slice(0,40),he=E==="iframe"?` ${ir(O)}`:"";X(`child+ ${E}${K?` title="${K}"`:""}${he} dims=${dn(O)}`)});else if(k.type==="attributes"&&k.target instanceof Element){let O=k.target;if(O.tagName.toLowerCase()!=="iframe")continue;let E=k.attributeName;(E==="src"||E==="srcdoc")&&X(`attr~ iframe ${E}=${E==="srcdoc"?`[${(O.getAttribute("srcdoc")??"").length}ch]`:Jn(O.getAttribute("src"))} dims=${dn(O)}`)}}}),It.observe(ae,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let Je=$=>{if(Me()||At)return;let k=ae.querySelectorAll("iframe"),O=typeof document<"u"&&"hasStorageAccess"in document;X(`watchdog:${$} container=${dn(ae)} children=${ae.childElementCount} iframes=${k.length} visibility=${typeof document<"u"?document.visibilityState:"(no document)"} cookies=${typeof navigator<"u"?navigator.cookieEnabled:"?"} hasStorageAccessApi=${O} paypalNetRequests=${Xn.value}`),k.forEach((E,K)=>{let he=(E.getAttribute("title")??"").slice(0,40);X(` iframe[${K}] ${dn(E)}${he?` title="${he}"`:""} ${ir(E)}`);let ee=Xt(E);ee&&X(` ${ee}`)}),rn.length===0&&X(" (no PayPal/zoid window errors captured)")};Le&&(Jt.push(setTimeout(()=>Je("3s"),3e3)),Jt.push(setTimeout(()=>Je("8s"),8e3)),Jt.push(setTimeout(()=>Je("15s"),15e3))),X("render:start");let L=D.startTiming();Jt.push(setTimeout(()=>{Me()||At||(X("watchdog:11s retryable render timeout"),pn("PayPal Buttons render did not settle within 11000ms.",!0))},Ml)),p.render(ae).then(()=>{if(X(`render:resolved inactive=${Me()}`),Ln(),Me()){Pn();return}At=!0,B(!0),Ae(!1),xt.current?.("ready"),D.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),D.performance({stage:"checkout_render",durationMs:D.elapsed(L),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}).catch($=>{let k=$ instanceof Error?$.message:"PayPal failed to render.";X(`render:rejected msg=${k.slice(0,120)}`),Ln(),pn(k)})}).catch(s=>{let c=s instanceof Error?s.message:"PayPal SDK failed to load.";X(`loadScript:rejected msg=${c.slice(0,120)}`),pn(c)})},0);return()=>{Yt=!0,clearTimeout(ze),Gn&&clearTimeout(Gn),Ln(),Pn()}},[pe,pt,d,S,l,J,Qe,e,ve,le,D,G,Ze]);let vn=Le?Ea("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:j?"#fef2f2":"#f3f4f6",border:`1px solid ${j?"#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=${Pe} failed=${j})`,b.length===0?`
2
2
  (waiting for first lifecycle event\u2026)`:`
3
- ${Mt.join(`
4
- `)}`]}):null;return Y&&!dt?De?pr("div",{children:$n}):null:Ma("div",{children:[$n,St&&pr(Ir,{identity:St,methodLabel:"PayPal",testId:"flopay-direct-paypal-identity-pane",onComplete:v=>{Un(v)},submitting:I}),de&&pr(Ir,{identity:de.identity,methodLabel:de.methodLabel,testId:"flopay-direct-paypal-identity-pane",onComplete:it,onCancel:()=>it(null)}),Ma("div",{"aria-hidden":ae||St||de?!0:void 0,style:ae||St||de?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:Wo},children:[!te&&!ae&&pr("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"}}),pr("div",{ref:me,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,role:"group","aria-label":"PayPal payment method",style:{minHeight:Wo,display:"flex",opacity:te?1:0},"aria-busy":we||ve},ie)]},ie),Je&&pr("button",{ref:Ue,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:zt,style:Ol,children:"Try PayPal again"})]})}function Jo(e){return pr(es,{...e})}function ts(e){return pr(es,{...e})}import{jsx as ns,jsxs as ql}from"react/jsx-runtime";function Kr({children:e,margin:t,icon:n=!0,styleOverride:r}){return ql("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&&ns("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:ns("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{resolveBillingApiUrl as $l}from"@flopay/shared";import{useEffect as mr,useMemo as jl,useRef as rs,useState as os}from"react";import{jsx as Kl}from"react/jsx-runtime";function Xo({flopay:e,paypalFlopay:t,options:n,onInstrument:r,children:o}){let[a,c]=os(e instanceof Promise?null:e),[s,S]=os(t instanceof Promise||!t?null:t),b=rs(null),g=rs(null),m=jr(r);mr(()=>{m({class:"lifecycle",name:"checkout.mount"})},[m]),mr(()=>{a&&m({class:"lifecycle",name:"sdk.initialize.ready"})},[m,a]),mr(()=>{if(a)return jt(a)?.subscribe?.(m)},[m,a]),mr(()=>{if(!(!s||s===a))return jt(s)?.subscribe?.(m)},[m,a,s]),mr(()=>{if(!a)return;let u=jt(a);return b.current=u?.beginCheckout()??u?.now()??0,u?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{u?.log({name:"checkout.unmount",stage:"unmount"})}},[a]),mr(()=>{let u=!1;return e instanceof Promise?e.then(w=>{u||c(w)},()=>{u||m({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"})}):c(e),()=>{u=!0}},[m,e]),mr(()=>{let u=!1;if(!t){S(null);return}return t instanceof Promise?t.then(w=>{u||S(w)},()=>{u||m({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED",provider:"paypal"})}):S(t),()=>{u=!0}},[m,t]),mr(()=>{if(!a||g.current===a)return;g.current=a;let u=jt(a);u?.log({name:"checkout.rendered",stage:"checkout_render"}),m({class:"lifecycle",name:"checkout.rendered"}),u?.performance({stage:"checkout_render",durationMs:u.elapsed(b.current??0),durationMode:"machine"})},[m,a]);let M=$l(n?.billingApiUrl),D=jl(()=>({flopay:a,paypalFlopay:s,billingApiUrl:M,emitInstrument:m}),[a,s,M,m]);return Kl(In.Provider,{value:D,children:o})}var Zo="flopay_recent_completion_";function Vr(e){if(!(!e||typeof window>"u"))try{let t={expiresAt:Date.now()+6e4};window.sessionStorage.setItem(Zo+e,JSON.stringify(t))}catch{}}function Fa(e){if(!e||typeof window>"u")return!1;try{let t=window.sessionStorage.getItem(Zo+e);if(!t)return!1;let n=JSON.parse(t);return typeof n?.expiresAt!="number"||n.expiresAt<=Date.now()?(window.sessionStorage.removeItem(Zo+e),!1):!0}catch{return!1}}import{loadFloPay as as,PaymentAPI as ss}from"@flopay/js";import{classifyPaymentRejection as Vl,FloPayError as lt,isAuthorizationOnlySession as Hl,isSetupIntentClientSecret as Yl,normalizeCheckoutFailureOutcome as is}from"@flopay/shared";var Po="card";async function Gl(e,t,n){if(n){if(typeof e.retrieveSetupIntent!="function")return null;let{setupIntent:a,error:c}=await e.retrieveSetupIntent(t);return{error:c,intent:a??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 Wl(e,t,n,r){if(r){if(typeof e.confirmCardSetup!="function")return null;let{setupIntent:c,error:s}=await e.confirmCardSetup(t,n);return{error:s,intent:c??null}}if(typeof e.confirmCardPayment!="function")return null;let{paymentIntent:o,error:a}=await e.confirmCardPayment(t,n);return{error:a,intent:o??null}}function Da(e,t){return Object.assign(e,{checkoutMethod:t})}function rr(e,t){let n=e instanceof lt?e:new lt(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 vo(e,t){try{return await e()}catch(n){throw rr(n,t)}}function ls(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 Jl(e){return e.status==="succeeded"||e.status==="declined"}async function cs(e){if(typeof document>"u"||typeof window>"u")throw new lt("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});if(e.signal?.aborted)throw new lt("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`,a=async()=>{let g=new AbortController,m=()=>g.abort();e.signal?.aborted?g.abort():e.signal?.addEventListener("abort",m);let M=window.setTimeout(()=>g.abort(),r);try{let D=await fetch(o,{method:"POST",headers:{"x-checkout-session-token":e.nonce,"content-type":"application/json"},body:"{}",signal:g.signal});if(!D.ok)return{status:"unknown"};let u=await D.json().catch(()=>null);return Xl(u)}catch{return{status:"unknown"}}finally{window.clearTimeout(M),e.signal?.removeEventListener("abort",m)}},c=document.activeElement instanceof HTMLElement?document.activeElement:null,s=document.createElement("div");s.setAttribute("data-flopay-auto-3ds-overlay","1"),s.setAttribute("role","dialog"),s.setAttribute("aria-modal","true"),s.setAttribute("aria-label","Card authentication"),s.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 S=document.createElement("iframe");S.setAttribute("title","Card authentication"),S.setAttribute("allow","payment"),S.tabIndex=0,S.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(";"),S.src=e.nextActionRedirectUrl,s.appendChild(S),document.body.appendChild(s),S.focus();let b=null;try{b=new URL(e.billingApiUrl,window.location.href).origin}catch{b=null}try{let g=await new Promise((m,M)=>{let D=!1,u=0,w=0,ve=0,H=!1,P=()=>{window.clearTimeout(u),window.clearInterval(w),window.clearTimeout(ve),window.removeEventListener("message",oe),S.removeEventListener("load",Q),e.signal?.removeEventListener("abort",ce)},fe=async()=>{if(!(D||H)){H=!0;try{let Ce=await a();if(D||!Jl(Ce))return;D=!0,P(),m(Ce)}finally{H=!1}}},Q=()=>{window.clearTimeout(ve),ve=window.setTimeout(()=>{fe()},250)},ce=()=>{D||(D=!0,P(),M(new lt("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"})))},oe=Ce=>{if(Ce.source!==S.contentWindow||b&&Ce.origin!==b)return;let He=Ce.data;!He||typeof He!="object"||He.source!=="flopay-vault-3ds-return"||D||(D=!0,P(),m(null))};u=window.setTimeout(()=>{D||(D=!0,P(),M(new lt("Card authentication timed out.","api_error",{code:"three_ds_timeout"})))},t),w=window.setInterval(()=>{fe()},n),S.addEventListener("load",Q),window.addEventListener("message",oe),e.signal?.addEventListener("abort",ce),e.signal?.aborted&&ce()});return g||await a()}finally{s.parentNode?.removeChild(s),c?.isConnected&&c.focus()}}function Xl(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"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 yr(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,a=cr(o)??o;return Da(new lt(a,"api_error",{code:is(e?.outcome)??is(e?.type)??e?.gatewayErrorCode}),r)}function Na(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function Qo(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}async function Zl(e){try{return await e()}catch(t){let n=t instanceof Error?t.message:String(t);if(!/failed to fetch|fetch failed/i.test(n))throw t;return e()}}function ds(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let o of n)if(typeof o=="string"&&o.length>0&&(!t?.requirePaymentIntentClientSecret||Qo(o)))return o;let r=e?.data;if(r&&typeof r=="object"){let o=r,a=[o.threeDSecureToken,o.clientSecret,o.stripeClientSecret,o.id];for(let s of a)if(typeof s=="string"&&s.length>0&&(!t?.requirePaymentIntentClientSecret||Qo(s)))return s;let c=o.gateways;if(c&&typeof c=="object"){let s=c.stripe;if(s&&typeof s=="object"){let S=s,b=[S.stripeClientSecret,S.clientSecret];for(let g of b)if(typeof g=="string"&&g.length>0&&(!t?.requirePaymentIntentClientSecret||Qo(g)))return g}}}}async function Ql({billingApiUrl:e,sessionId:t,nonce:n,responseJson:r}){let o=ds(r,{requirePaymentIntentClientSecret:!0});if(typeof o=="string"&&o.length>0)return{type:"3ds_required",threeDSecureToken:o};if(!t)return null;try{let s=(await new ss(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(Qo(s))return{type:"3ds_required",threeDSecureToken:s}}catch{}return null}async function Hr({billingApiUrl:e,sessionId:t,session:n,nonce:r,tokenizedData:o,returnUrl:a,telemetry:c}){let s=e.replace(/\/+$/,""),S=t??n.id,b=r??n.clientSecret,g=n.customer?.id??n.accountData?.userId??"",m=n.customer?.email??n.accountData?.email??"",M=n.customer?.firstName??n.accountData?.firstName??"",D=n.customer?.lastName??n.accountData?.lastName??"",u=n.customer?.country??n.accountData?.country??void 0,w=n.customer?.zip??n.accountData?.zip??void 0,ve=new ss(s,c===!1?{telemetry:!1}:void 0),H=await Zl(()=>ve.processPayment(g,{sessionId:S,nonce:b,tokenizedData:o,accountData:{userId:g,email:m,firstName:M,lastName:D,country:u,zip:w},returnUrl:a??Na(n)}));if(H.ok){let Q=typeof H.json=="function"?await H.json().catch(()=>null):null;return Hl(n)||Q?.status==="authorized"?{type:"success",result:{status:"authorized",paymentId:typeof Q?.paymentId=="string"?Q.paymentId:n.paymentId,sessionId:typeof Q?.sessionId=="string"?Q.sessionId:S,authorizationExpiresAt:typeof Q?.authorizationExpiresAt=="string"?Q.authorizationExpiresAt:n.authorizationExpiresAt,paymentMethodId:yo(o),checkoutMethod:o?o.isPaypal?"paypal":"card":void 0}}:{type:"success",result:{status:"succeeded",paymentIntentId:o?.threeDSecureActionResultTokenId,paymentMethodId:yo(o),checkoutMethod:o?o.isPaypal?"paypal":"card":void 0}}}let P;try{P=await H.json()}catch{throw new lt("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:H.status})}if(P?.type==="paypal_redirect_required"||P?.type==="3ds_required"){let Q=ds(P);if(!Q)throw new lt("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:H.status});return{type:P.type,threeDSecureToken:Q,paymentMethodId:P.paymentMethodId}}if(P?.gatewayErrorCode==="authentication_required"){let Q=await Ql({billingApiUrl:s,sessionId:S,nonce:b,responseJson:P});if(Q)return Q;throw Da(new lt("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}let fe=new lt(P?.message??"Payment failed. Please try again.","api_error",{code:P?.code??P?.gatewayErrorCode,declineCode:P?.declineCode??P?.gatewayDeclineReason,statusCode:H.status});throw Object.assign(fe,{telemetryOutcome:Vl(H.status,P)})}async function ea(e,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:a,session:c,returnUrl:s,telemetry:S}){let b=t?.getRawProvider();if(!b)throw rr(new lt("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!r||!e.threeDSecureToken)throw Da(new lt("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let g=Yl(e.threeDSecureToken),m=null,M=e.paymentMethodId,D=await vo(()=>Gl(b,e.threeDSecureToken,g),"card");if(D){if(D.error)throw rr(new lt(D.error.message??`Failed to retrieve 3DS ${g?"setup":"payment"} status.`,"api_error",{code:D.error.code}),"card");let w=D.intent;!M&&w?.payment_method&&(typeof w.payment_method=="string"?M=w.payment_method:"id"in w.payment_method&&(M=w.payment_method.id??void 0))}let u=M?await vo(()=>Wl(b,e.threeDSecureToken,{payment_method:M,return_url:s??Na(c)??window.location.href},g),"card"):null;if(u){if(u.error)throw rr(new lt(u.error.message??"3DS authentication failed.","api_error",{code:u.error.code}),"card");m=u.intent}else{let w=await vo(()=>b.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(w.error)throw rr(new lt(w.error.message??"3DS authentication failed.","api_error",{code:w.error.code}),"card");m=(g?w.setupIntent:w.paymentIntent)??null}if(m&&(m.status==="requires_capture"||m.status==="succeeded"||m.status==="processing")){let w=await Hr({billingApiUrl:o,sessionId:a,session:c,telemetry:S,tokenizedData:{id:m.id,type:"card",threeDSecureActionResultTokenId:m.id},returnUrl:s});return w.type==="success"?{...w.result,paymentIntentId:w.result.paymentIntentId??m.id,paymentMethodId:w.result.paymentMethodId??M}:ea(w,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:a,session:c,returnUrl:s,telemetry:S})}throw rr(new lt("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let g=(n??t)?.getRawProvider();if(!g)throw rr(new lt("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:M}=await vo(()=>g.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(M)throw rr(new lt(M.message??"PayPal authorization failed.","api_error",{code:M.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:m}=await vo(()=>g.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:s??Na(c)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(m)throw rr(new lt(m.message??"PayPal authorization failed.","api_error",{code:m.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new lt("Unsupported payment redirect state.","api_error")}function Rr(e){if(e instanceof lt){let r=cr(e.message);return r&&r!==e.message?Object.assign(new lt(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=cr(t)??t;return new lt(n,"api_error")}function ta(e){let t=e.data.stripe?.publishableKey,n=!!e.data.paypal?.publishableKey;if(!t&&!n)throw new lt("Session advertises no supported gateways (expected `gateways.stripe` and/or `gateways.paypal`).","validation_error");return t?{publishableKey:t,paypalPublishableKey:e.data.stripe?.paypalPublishableKey??t}:{}}async function na({publishableKey:e,paypalPublishableKey:t,billingApiUrl:n,locale:r,telemetry:o}){if(!e)return{flopay:null,paypalFlopay:null};let a=!!t&&t!==e,[c,s]=await Promise.all([as(e,{billingApiUrl:n,locale:r,telemetry:o}),a?as(t,{billingApiUrl:n,locale:r,telemetry:o}).catch(S=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",S),null)):Promise.resolve(null)]);return{flopay:c,paypalFlopay:t?a?s:c:null}}import{PaymentAPI as So,toStripeAppearance as ec}from"@flopay/js";import{COUNTRY_OPTIONS as tc,classifyPaymentRejection as nc,FloPayError as On,filterStripeMethodsByCountry as rc,getPostalCodeExample as oc,getPostalCodeLabel as Ua,getStateFromPostalCode as ms,getStateLabel as ys,getStateOptions as ac,getStripeMethodDisplayName as xr,hasVendoredStripeMethodLogo as ic,isAuthorizationOnlySession as La,isAVSFieldVisible as ze,isPostalCodeSupported as sc,isSetupIntentClientSecret as lc,isValidEmail as en,isValidPostalCode as cc,needsStripeMethodExplicitConfirm as fs,normalizeCheckoutFailureOutcome as dc,partitionStripeMethods as uc,resolveAVSConfig as pc,resolveButtonsLayoutTheme as mc,resolveStripeMethodBrandVariant as yc,resolveTheme as fc,stripeExpressMethodToOptionKey as gs}from"@flopay/shared";import{ExpressCheckoutElement as Is,PaymentElement as gc,Elements as _r,useElements as ja,useStripe as Ka}from"@stripe/react-stripe-js";import hc,{useCallback as Pe,useContext as Yr,useEffect as ht,useMemo as gt,useRef as Ie,useState as ye}from"react";function us(e){let t=e??(typeof navigator<"u"?navigator.userAgent:"");return t?!!(/FBAN|FBAV|FB_IAB|FBIOS|Instagram|musical_ly|BytedanceWebview|TikTok/i.test(t)||/Twitter|Snapchat|Pinterest|LinkedInApp|Line\/|MicroMessenger|GSA\//i.test(t)||/Android.*;\s?wv\)/.test(t)||/(iPhone|iPad|iPod).*AppleWebKit(?!.*Safari)/.test(t)):!1}var ps={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 fr,jsx as l,jsxs as ke}from"react/jsx-runtime";var Gn="flopay_stripe_resume",hs="flopay_wallet_resume";function Es(e){return e instanceof On&&(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 So(e).createSessionIntent(...n)}catch(o){throw Es(o)||t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"intent_create",provider:r}),o}}var Co="flopay_paypal_resume",bc=250,bs="Just a moment \u2014 we are finalizing your order. Please press pay again.";function Va(e,t,n){e?.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:"provider_runtime",stage:"provider_load",provider:t,paymentMethodCategory:n,requestCategory:"provider_sdk"})}async function aa({billingApiUrl:e,sessionId:t,nonce:n,request:r}){if(!(!t||!n))try{await new So(e,{telemetry:!1}).reportSessionIntentDecline(t,n,r)}catch{}}function vc(e){return e instanceof On&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function Oa(e){return e?.html?{html:e.html,...e.messageToken?{messageToken:e.messageToken}:{},...e.expectedOrigin?{expectedOrigin:e.expectedOrigin}:{}}:null}function Pc({event:e,fallbackEmail:t,fallbackName:n}){let r=e.billingDetails,o=kn(r?.name),a=kn(n);return{email:r?.email?.trim()||t?.trim(),firstName:o.firstName??a.firstName,lastName:o.lastName??a.lastName}}async function Rs({event:e,prepared:t,email:n,billingName:r,methodLabel:o,collect:a}){let c=Pc({event:e,fallbackEmail:t?.accountPatch?.email??n,fallbackName:[t?.accountPatch?.firstName,t?.accountPatch?.lastName].filter(Boolean).join(" ")||r});return!en(c.email)||!fo(c)?a(o,c):c}var Cc=`
3
+ ${b.join(`
4
+ `)}`]}):null;return j&&!vt?Le?wr("div",{children:vn}):null:Ea("div",{children:[vn,R&&wr(zr,{identity:R.identity,methodLabel:R.methodLabel,testId:"flopay-direct-paypal-identity-pane",onComplete:_,onCancel:()=>_(null)}),Ea("div",{"aria-hidden":se||R?!0:void 0,style:se||R?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:$o},children:[!Pe&&!se&&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:_e,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,role:"group","aria-label":"PayPal payment method",style:{minHeight:$o,display:"flex",opacity:Pe?1:0},"aria-busy":Ce||ge},le)]},le),We&&wr("button",{ref:Te,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:ln,style:Dl,children:"Try PayPal again"})]})}function jo(e){return wr(Ji,{...e})}function Xi(e){return wr(Ji,{...e})}import{jsx as Zi,jsxs as Ol}from"react/jsx-runtime";function $r({children:e,margin:t,icon:n=!0,styleOverride:r}){return Ol("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&&Zi("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:Zi("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{resolveBillingApiUrl as zl}from"@flopay/shared";import{useEffect as dr,useMemo as Ul,useRef as Qi,useState as es}from"react";import{jsx as ql}from"react/jsx-runtime";function Ko({flopay:e,paypalFlopay:t,options:n,onInstrument:r,children:o}){let[a,d]=es(e instanceof Promise?null:e),[l,S]=es(t instanceof Promise||!t?null:t),g=Qi(null),h=Qi(null),v=qr(r);dr(()=>{v({class:"lifecycle",name:"checkout.mount"})},[v]),dr(()=>{a&&v({class:"lifecycle",name:"sdk.initialize.ready"})},[v,a]),dr(()=>{if(a)return Dt(a)?.subscribe?.(v)},[v,a]),dr(()=>{if(!(!l||l===a))return Dt(l)?.subscribe?.(v)},[v,a,l]),dr(()=>{if(!a)return;let m=Dt(a);return g.current=m?.beginCheckout()??m?.now()??0,m?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{m?.log({name:"checkout.unmount",stage:"unmount"})}},[a]),dr(()=>{let m=!1;return e instanceof Promise?e.then(w=>{m||d(w)},()=>{m||v({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"})}):d(e),()=>{m=!0}},[v,e]),dr(()=>{let m=!1;if(!t){S(null);return}return t instanceof Promise?t.then(w=>{m||S(w)},()=>{m||v({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED",provider:"paypal"})}):S(t),()=>{m=!0}},[v,t]),dr(()=>{if(!a||h.current===a)return;h.current=a;let m=Dt(a);m?.log({name:"checkout.rendered",stage:"checkout_render"}),v({class:"lifecycle",name:"checkout.rendered"}),m?.performance({stage:"checkout_render",durationMs:m.elapsed(g.current??0),durationMode:"machine"})},[v,a]);let A=zl(n?.billingApiUrl),F=Ul(()=>({flopay:a,paypalFlopay:l,billingApiUrl:A,emitInstrument:v}),[a,l,A,v]);return ql(In.Provider,{value:F,children:o})}var Vo="flopay_recent_completion_";function jr(e){if(!(!e||typeof window>"u"))try{let t={expiresAt:Date.now()+6e4};window.sessionStorage.setItem(Vo+e,JSON.stringify(t))}catch{}}function xa(e){if(!e||typeof window>"u")return!1;try{let t=window.sessionStorage.getItem(Vo+e);if(!t)return!1;let n=JSON.parse(t);return typeof n?.expiresAt!="number"||n.expiresAt<=Date.now()?(window.sessionStorage.removeItem(Vo+e),!1):!0}catch{return!1}}import{loadFloPay as ts,PaymentAPI as rs}from"@flopay/js";import{classifyPaymentRejection as $l,FloPayError as it,isAuthorizationOnlySession as jl,isSetupIntentClientSecret as Kl,normalizeCheckoutFailureOutcome as ns}from"@flopay/shared";var ho="card";async function Vl(e,t,n){if(n){if(typeof e.retrieveSetupIntent!="function")return null;let{setupIntent:a,error:d}=await e.retrieveSetupIntent(t);return{error:d,intent:a??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 Hl(e,t,n,r){if(r){if(typeof e.confirmCardSetup!="function")return null;let{setupIntent:d,error:l}=await e.confirmCardSetup(t,n);return{error:l,intent:d??null}}if(typeof e.confirmCardPayment!="function")return null;let{paymentIntent:o,error:a}=await e.confirmCardPayment(t,n);return{error:a,intent:o??null}}function Ba(e,t){return Object.assign(e,{checkoutMethod:t})}function Qn(e,t){let n=e instanceof it?e:new it(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 Qn(n,t)}}function os(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 Yl(e){return e.status==="succeeded"||e.status==="declined"}async function as(e){if(typeof document>"u"||typeof window>"u")throw new it("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});if(e.signal?.aborted)throw new it("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`,a=async()=>{let h=new AbortController,v=()=>h.abort();e.signal?.aborted?h.abort():e.signal?.addEventListener("abort",v);let A=window.setTimeout(()=>h.abort(),r);try{let F=await fetch(o,{method:"POST",headers:{"x-checkout-session-token":e.nonce,"content-type":"application/json"},body:"{}",signal:h.signal});if(!F.ok)return{status:"unknown"};let m=await F.json().catch(()=>null);return Gl(m)}catch{return{status:"unknown"}}finally{window.clearTimeout(A),e.signal?.removeEventListener("abort",v)}},d=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 S=document.createElement("iframe");S.setAttribute("title","Card authentication"),S.setAttribute("allow","payment"),S.tabIndex=0,S.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(";"),S.src=e.nextActionRedirectUrl,l.appendChild(S),document.body.appendChild(l),S.focus();let g=null;try{g=new URL(e.billingApiUrl,window.location.href).origin}catch{g=null}try{let h=await new Promise((v,A)=>{let F=!1,m=0,w=0,ge=0,V=!1,C=()=>{window.clearTimeout(m),window.clearInterval(w),window.clearTimeout(ge),window.removeEventListener("message",de),S.removeEventListener("load",ne),e.signal?.removeEventListener("abort",ce)},pe=async()=>{if(!(F||V)){V=!0;try{let ve=await a();if(F||!Yl(ve))return;F=!0,C(),v(ve)}finally{V=!1}}},ne=()=>{window.clearTimeout(ge),ge=window.setTimeout(()=>{pe()},250)},ce=()=>{F||(F=!0,C(),A(new it("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"})))},de=ve=>{if(ve.source!==S.contentWindow||g&&ve.origin!==g)return;let Ve=ve.data;!Ve||typeof Ve!="object"||Ve.source!=="flopay-vault-3ds-return"||F||(F=!0,C(),v(null))};m=window.setTimeout(()=>{F||(F=!0,C(),A(new it("Card authentication timed out.","api_error",{code:"three_ds_timeout"})))},t),w=window.setInterval(()=>{pe()},n),S.addEventListener("load",ne),window.addEventListener("message",de),e.signal?.addEventListener("abort",ce),e.signal?.aborted&&ce()});return h||await a()}finally{l.parentNode?.removeChild(l),d?.isConnected&&d.focus()}}function Gl(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"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 ur(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,a=sr(o)??o;return Ba(new it(a,"api_error",{code:ns(e?.outcome)??ns(e?.type)??e?.gatewayErrorCode}),r)}function Ta(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function Ho(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}async function Wl(e){try{return await e()}catch(t){let n=t instanceof Error?t.message:String(t);if(!/failed to fetch|fetch failed/i.test(n))throw t;return e()}}function is(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let o of n)if(typeof o=="string"&&o.length>0&&(!t?.requirePaymentIntentClientSecret||Ho(o)))return o;let r=e?.data;if(r&&typeof r=="object"){let o=r,a=[o.threeDSecureToken,o.clientSecret,o.stripeClientSecret,o.id];for(let l of a)if(typeof l=="string"&&l.length>0&&(!t?.requirePaymentIntentClientSecret||Ho(l)))return l;let d=o.gateways;if(d&&typeof d=="object"){let l=d.stripe;if(l&&typeof l=="object"){let S=l,g=[S.stripeClientSecret,S.clientSecret];for(let h of g)if(typeof h=="string"&&h.length>0&&(!t?.requirePaymentIntentClientSecret||Ho(h)))return h}}}}async function Jl({billingApiUrl:e,sessionId:t,nonce:n,responseJson:r}){let o=is(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 rs(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(Ho(l))return{type:"3ds_required",threeDSecureToken:l}}catch{}return null}async function Kr({billingApiUrl:e,sessionId:t,session:n,nonce:r,tokenizedData:o,returnUrl:a,telemetry:d}){let l=e.replace(/\/+$/,""),S=t??n.id,g=r??n.clientSecret,h=n.customer?.id??n.accountData?.userId??"",v=n.customer?.email??n.accountData?.email??"",A=n.customer?.firstName??n.accountData?.firstName??"",F=n.customer?.lastName??n.accountData?.lastName??"",m=n.customer?.country??n.accountData?.country??void 0,w=n.customer?.zip??n.accountData?.zip??void 0,ge=new rs(l,d===!1?{telemetry:!1}:void 0),V=await Wl(()=>ge.processPayment(h,{sessionId:S,nonce:g,tokenizedData:o,accountData:{userId:h,email:v,firstName:A,lastName:F,country:m,zip:w},returnUrl:a??Ta(n)}));if(V.ok){let ne=typeof V.json=="function"?await V.json().catch(()=>null):null;return jl(n)||ne?.status==="authorized"?{type:"success",result:{status:"authorized",paymentId:typeof ne?.paymentId=="string"?ne.paymentId:n.paymentId,sessionId:typeof ne?.sessionId=="string"?ne.sessionId:S,authorizationExpiresAt:typeof ne?.authorizationExpiresAt=="string"?ne.authorizationExpiresAt:n.authorizationExpiresAt,paymentMethodId:uo(o),checkoutMethod:o?o.isPaypal?"paypal":"card":void 0}}:{type:"success",result:{status:"succeeded",paymentIntentId:o?.threeDSecureActionResultTokenId,paymentMethodId:uo(o),checkoutMethod:o?o.isPaypal?"paypal":"card":void 0}}}let C;try{C=await V.json()}catch{throw new it("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:V.status})}if(C?.type==="paypal_redirect_required"||C?.type==="3ds_required"){let ne=is(C);if(!ne)throw new it("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:V.status});return{type:C.type,threeDSecureToken:ne,paymentMethodId:C.paymentMethodId}}if(C?.gatewayErrorCode==="authentication_required"){let ne=await Jl({billingApiUrl:l,sessionId:S,nonce:g,responseJson:C});if(ne)return ne;throw Ba(new it("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}let pe=new it(C?.message??"Payment failed. Please try again.","api_error",{code:C?.code??C?.gatewayErrorCode,declineCode:C?.declineCode??C?.gatewayDeclineReason,statusCode:V.status});throw Object.assign(pe,{telemetryOutcome:$l(V.status,C)})}async function Yo(e,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:a,session:d,returnUrl:l,telemetry:S}){let g=t?.getRawProvider();if(!g)throw Qn(new it("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!r||!e.threeDSecureToken)throw Ba(new it("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let h=Kl(e.threeDSecureToken),v=null,A=e.paymentMethodId,F=await go(()=>Vl(g,e.threeDSecureToken,h),"card");if(F){if(F.error)throw Qn(new it(F.error.message??`Failed to retrieve 3DS ${h?"setup":"payment"} status.`,"api_error",{code:F.error.code}),"card");let w=F.intent;!A&&w?.payment_method&&(typeof w.payment_method=="string"?A=w.payment_method:"id"in w.payment_method&&(A=w.payment_method.id??void 0))}let m=A?await go(()=>Hl(g,e.threeDSecureToken,{payment_method:A,return_url:l??Ta(d)??window.location.href},h),"card"):null;if(m){if(m.error)throw Qn(new it(m.error.message??"3DS authentication failed.","api_error",{code:m.error.code}),"card");v=m.intent}else{let w=await go(()=>g.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(w.error)throw Qn(new it(w.error.message??"3DS authentication failed.","api_error",{code:w.error.code}),"card");v=(h?w.setupIntent:w.paymentIntent)??null}if(v&&(v.status==="requires_capture"||v.status==="succeeded"||v.status==="processing")){let w=await Kr({billingApiUrl:o,sessionId:a,session:d,telemetry:S,tokenizedData:{id:v.id,type:"card",threeDSecureActionResultTokenId:v.id},returnUrl:l});return w.type==="success"?{...w.result,paymentIntentId:w.result.paymentIntentId??v.id,paymentMethodId:w.result.paymentMethodId??A}:Yo(w,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:a,session:d,returnUrl:l,telemetry:S})}throw Qn(new it("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let h=(n??t)?.getRawProvider();if(!h)throw Qn(new it("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:A}=await go(()=>h.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(A)throw Qn(new it(A.message??"PayPal authorization failed.","api_error",{code:A.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:v}=await go(()=>h.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:l??Ta(d)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(v)throw Qn(new it(v.message??"PayPal authorization failed.","api_error",{code:v.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new it("Unsupported payment redirect state.","api_error")}function kr(e){if(e instanceof it){let r=sr(e.message);return r&&r!==e.message?Object.assign(new it(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=sr(t)??t;return new it(n,"api_error")}function Go(e){let t=e.data.stripe?.publishableKey,n=!!e.data.paypal?.publishableKey;if(!t&&!n)throw new it("Session advertises no supported gateways (expected `gateways.stripe` and/or `gateways.paypal`).","validation_error");return t?{publishableKey:t,paypalPublishableKey:e.data.stripe?.paypalPublishableKey??t}:{}}async function Wo({publishableKey:e,paypalPublishableKey:t,billingApiUrl:n,locale:r,telemetry:o}){if(!e)return{flopay:null,paypalFlopay:null};let a=!!t&&t!==e,[d,l]=await Promise.all([ts(e,{billingApiUrl:n,locale:r,telemetry:o}),a?ts(t,{billingApiUrl:n,locale:r,telemetry:o}).catch(S=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",S),null)):Promise.resolve(null)]);return{flopay:d,paypalFlopay:t?a?l:d:null}}import{PaymentAPI as Vr,toStripeAppearance as Xl}from"@flopay/js";import{COUNTRY_OPTIONS as Zl,classifyPaymentRejection as Ql,FloPayError as An,filterStripeMethodsByCountry as ec,getPostalCodeExample as tc,getPostalCodeLabel as Da,getStateFromPostalCode as cs,getStateLabel as ds,getStateOptions as nc,getStripeMethodDisplayName as Rr,hasVendoredStripeMethodLogo as rc,isAuthorizationOnlySession as Aa,isAVSFieldVisible as Ue,isPostalCodeSupported as oc,isSetupIntentClientSecret as ac,isValidEmail as Kt,isValidPostalCode as ic,needsStripeMethodExplicitConfirm as us,normalizeCheckoutFailureOutcome as sc,partitionStripeMethods as lc,resolveAVSConfig as cc,resolveButtonsLayoutTheme as dc,resolveStripeMethodBrandVariant as uc,resolveTheme as pc,stripeExpressMethodToOptionKey as ps}from"@flopay/shared";import{ExpressCheckoutElement as Cs,PaymentElement as mc,Elements as Ir,useElements as Oa,useStripe as za}from"@stripe/react-stripe-js";import yc,{useCallback as be,useContext as Yr,useEffect as ut,useMemo as st,useRef as we,useState as me}from"react";function ss(e){let t=e??(typeof navigator<"u"?navigator.userAgent:"");return t?!!(/FBAN|FBAV|FB_IAB|FBIOS|Instagram|musical_ly|BytedanceWebview|TikTok/i.test(t)||/Twitter|Snapchat|Pinterest|LinkedInApp|Line\/|MicroMessenger|GSA\//i.test(t)||/Android.*;\s?wv\)/.test(t)||/(iPhone|iPad|iPod).*AppleWebKit(?!.*Safari)/.test(t)):!1}var ls={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 Hr,jsx as u,jsxs as De}from"react/jsx-runtime";var $n="flopay_stripe_resume",ms="flopay_wallet_resume";function Ss(e){return e instanceof An&&(e.type==="validation_error"||e.statusCode===400||e.statusCode===422)}async function Xo(e,t,...n){let r=n[2].provider;t?.({class:"lifecycle",name:"payment.intent.started",provider:r});try{return await new Vr(e).createSessionIntent(...n)}catch(o){throw Ss(o)||t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"intent_create",provider:r}),o}}var bo="flopay_paypal_resume",fc=250,ys="Just a moment \u2014 we are finalizing your order. Please press pay again.";function Ua(e,t,n){e?.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:"provider_runtime",stage:"provider_load",provider:t,paymentMethodCategory:n,requestCategory:"provider_sdk"})}async function Zo({billingApiUrl:e,sessionId:t,nonce:n,request:r}){if(!(!t||!n))try{await new Vr(e,{telemetry:!1}).reportSessionIntentDecline(t,n,r)}catch{}}function gc(e){return e instanceof An&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function Ma(e){return e?.html?{html:e.html,...e.messageToken?{messageToken:e.messageToken}:{},...e.expectedOrigin?{expectedOrigin:e.expectedOrigin}:{}}:null}function hc({event:e,fallbackEmail:t,fallbackName:n}){let r=e.billingDetails,o=vr(r?.name),a=vr(n);return sn({email:(Kt(t?.trim())?t?.trim():void 0)??r?.email?.trim(),firstName:a.firstName??o.firstName,lastName:a.lastName??o.lastName})}async function ws({event:e,prepared:t,email:n,billingName:r,methodLabel:o,collect:a}){let d=hc({event:e,fallbackEmail:t?.accountPatch?.email??n,fallbackName:[t?.accountPatch?.firstName,t?.accountPatch?.lastName].filter(Boolean).join(" ")||r});return Kt(d.email)?d:a(o,d)}var bc=`
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 @@ ${Mt.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
- `,ra=44;function Ha(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 Sc={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"},_s={width:"100%",minHeight:ra,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 wc(e){switch(e){case"paypal":return"PayPal";case"apple_pay":return"Apple Pay";case"google_pay":return"Google Pay";default:return"Card"}}function vs(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function qa(e){return e==="paypal"?"PayPal":xr(e)}function kc(e,t){let n=`We couldn't open ${qa(e)}. Try again or choose another payment method.`;return t?`${n} Allow pop-ups for this site, then try again.`:n}function xs(e){let t=Ie(0),n=Ie(null),r=Ie(null),o=Pe((u=r.current)=>{let w=u;w?.timer&&(clearTimeout(w.timer),w.timer=null)},[]),a=Pe((u,w)=>{typeof document<"u"&&document.visibilityState!=="visible"||(o(u),u.timer=setTimeout(()=>{u.timer=null,r.current?.generation===u.generation&&(r.current=null,n.current=u.generation,e(u.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}))},w))},[o,e]),c=Pe(u=>{u.yieldedControl&&a(u,600)},[a]),s=Pe(u=>{o();let w=t.current+1;t.current=w,n.current=null;let ve={generation:w,method:u,timer:null,yieldedControl:!1};return r.current=ve,w},[o]),S=Pe(u=>{let w=r.current;return typeof u=="number"&&w?.generation!==u?!1:(o(w),r.current=null,(typeof u!="number"||n.current===u)&&(n.current=null),!0)},[o]),b=Pe(u=>{let w=r.current,ve=u??w?.generation??t.current;(!u||w?.generation===u)&&(o(w),r.current=null),n.current=ve},[o]),g=Pe(u=>n.current===(u??t.current),[]),m=Pe(u=>r.current?.generation===u&&n.current!==u,[]),M=Pe(()=>{let u=r.current;u&&c(u)},[c]),D=Pe(()=>{let u=r.current;u&&(u.yieldedControl=!0,o(u))},[o]);return ht(()=>{let u=()=>{document.visibilityState==="visible"?M():D()},w=()=>{D()};return document.addEventListener("visibilitychange",u),window.addEventListener("blur",w),window.addEventListener("focus",M),()=>{document.removeEventListener("visibilitychange",u),window.removeEventListener("blur",w),window.removeEventListener("focus",M),o()}},[o,D,M]),{startAttempt:s,finishAttempt:S,invalidateAttempt:b,isAttemptInvalidated:g,isAttemptCurrent:m}}function Ic(e){let t=oc(e);return`Enter a valid ${Ua(e)}${t?` (e.g. ${t})`:""}`}function Ec(e,t,n){let r=sc(e),o=t.trim(),a=n&&r,c=a&&!o,s=a&&!!o&&!cc(e,o);return{visible:n,supported:r,required:a,empty:c,malformed:s}}function Rc(e,t){let n=e.trim(),r=t&&!n,o=t&&!!n&&!en(n);return{required:t,empty:r,malformed:o,value:n}}function Ps(e,t){return t instanceof On?t:new On(t instanceof Error?t.message:`${wc(e)} before-click hook failed.`,"validation_error")}function za(){return l("style",{children:Cc})}function _c(e){return typeof e=="number"?`${e}px`:e}function Ts(e,t){let n=e.availablePaymentMethods;return n&&t.some(r=>n[r])?"ready":"unavailable"}function As({state:e,placeholderTestId:t,borderRadius:n=8,children:r}){return e==="unavailable"||e==="load_error"?null:ke("div",{style:{position:"relative",minHeight:44},children:[l("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"}}),l("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 Cs(e){return e!=="unavailable"&&e!=="load_error"}function Ya(e){return l(Tc,{...e})}function Ss({sessionId:e,nonce:t,email:n,billingApiUrl:r,onTokenizedBody:o,onErrorChange:a,isProcessing:c=!1,onButtonClick:s,onDecline:S,onTechnicalFailure:b,runBeforeButtonClick:g,billingName:m,onBuyerIdentityReady:M,onLoadStateChange:D,placeholderBorderRadius:u}){let w=ur(),{emitInstrument:ve}=Yr(In),H=Ka(),P=ja(),[fe,Q]=ye("loading");ht(()=>{D?.(fe)},[fe,D]);let[ce,oe]=ye(!1),Ce=!en(n?.trim())||!m?.trim(),{request:He,collect:be,finish:Rt}=qr(),De=Ie(!1),Te=Ie(null),Ae=Ie(null),[ee,J]=ye(0),[L,me]=ye(!1),et=Ie(!1),Ue=Ie(new Map),{startAttempt:Ye,finishAttempt:te,invalidateAttempt:T,isAttemptInvalidated:ae,isAttemptCurrent:Fe}=xs((G,Y,$)=>{b?.(G,Y,{...$,popupBlocked:$?.popupBlocked??dr(Y)}),me(!0),J(we=>we+1)});ht(()=>{L&&Ae.current?.focus()},[L,ee]);let ie=Pe(()=>{J(G=>G+1)},[]),j=Pe((G,Y,$)=>{T($),b?.("paypal",G,{code:Y,popupBlocked:dr(G)}),me(!0),ie()},[T,b,ie]),_e=Pe(()=>{window.setTimeout(()=>{(Te.current?.querySelector("iframe")??Te.current)?.focus()},0)},[]);ht(()=>{et.current&&(et.current=!1,_e())},[_e,ee]);let Je=Pe(()=>{me(!1),a?.(null),_e()},[_e,a]);ht(()=>{if(!H||De.current)return;let G=new URLSearchParams(window.location.search),Y=G.get("payment_intent"),$=G.get("payment_intent_client_secret"),we=G.get("redirect_status");if(!Y||!$)return;De.current=!0;let Me;try{let K=localStorage.getItem(Co);if(K){let I=JSON.parse(K);I.clientSecret===$&&(Me={...I.accountPatch?{accountPatch:I.accountPatch}:{},...I.sessionId?{sessionId:I.sessionId}:{},...I.nonce?{nonce:I.nonce}:{}})}}catch{}try{localStorage.removeItem(Co)}catch{}let x=new URL(window.location.href);x.searchParams.delete("payment_intent"),x.searchParams.delete("payment_intent_client_secret"),x.searchParams.delete("redirect_status"),window.history.replaceState({},"",x.toString()),(async()=>{try{if(oe(!0),we==="failed"){let C="PayPal payment was declined. Please try again.";a?.(C),S?.($t("paypal",C));return}let{paymentIntent:K,error:I}=await H.retrievePaymentIntent($);if(I){a?.(I.message??"Failed to retrieve PayPal payment status.");return}if(K&&(K.status==="requires_capture"||K.status==="succeeded")){let C=typeof K.payment_method=="string"?K.payment_method:K.payment_method?.id;o({id:C??K.id,type:"card",threeDSecureActionResultTokenId:K.id,isPaypal:!0},Me)}else{let C="PayPal payment was not completed. Please try again.";a?.(C),S?.($t("paypal",C))}}catch(K){a?.(K instanceof Error?K.message:"Failed to complete PayPal payment.")}finally{oe(!1)}})()},[H,o,a,S]);let We=Pe(async G=>{if(c||ce){G.reject();return}let Y=g?await g("paypal"):{proceed:!0};if(!Y.proceed){Ue.current.delete(ee),G.reject();return}let $=Ye("paypal");Ue.current.set(ee,{generation:$,accountPatch:Y.accountPatch,sessionId:Y.sessionId,nonce:Y.nonce}),me(!1),s?.("paypal"),G.resolve()},[Ue,c,s,g,Ye,ce,ee]),Se=Pe(async G=>{if(!H||!P)return;let Y=Ue.current.get(ee);if(Y&&!Fe(Y.generation)){Ue.current.delete(ee);return}if(!Y&&ae()||Y&&!te(Y.generation))return;Y||te();let $=Y??null;if(Ue.current.delete(ee),!$&&g){let C=await g("paypal");if(!C.proceed){G.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}$={accountPatch:C.accountPatch,sessionId:C.sessionId,nonce:C.nonce}}let we=$?.sessionId??e,Me=$?.nonce??t,x=await Rs({event:G,prepared:$,email:n,billingName:m,methodLabel:"PayPal",collect:be});if(!x){G.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let K=x.email,I={...$?.accountPatch,...x};try{if(oe(!0),a?.(null),!we||!en(K))throw new Error("Missing sessionId or email for PayPal payment");await M?.(x);let C=H.createPaymentMethod,{error:nt,paymentMethod:St}=await C({type:"paypal"});if(nt){j(nt,"stripe_paypal_create_payment_method_failed",Y?.generation),G.paymentFailed({reason:"fail"});return}let de=await oa(r,ve,we,Me??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:St?.id??null,intentKind:"payment"});if(de.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let ct=de.clientSecret,it={return_url:window.location.href};if(St?.id&&(it.payment_method=St.id),typeof window<"u")try{localStorage.setItem(Co,JSON.stringify({clientSecret:ct,sessionId:we,nonce:Me,accountPatch:I}))}catch{}let{error:rt,paymentIntent:je}=await H.confirmPayment({clientSecret:ct,confirmParams:it,redirect:"if_required"});if(rt){if(typeof window<"u")try{localStorage.removeItem(Co)}catch{}if(go(rt)){let U=rt.message??"Your payment was declined.";a?.(U),S?.($t("paypal",U,{code:tr(rt),declineCode:$r(rt)})),await aa({billingApiUrl:r,sessionId:we,nonce:Me,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:tr(rt)??"provider_declined"}})}else j(rt,"stripe_paypal_confirm_failed",Y?.generation);return}if(typeof window<"u")try{localStorage.removeItem(Co)}catch{}let y=typeof je?.payment_method=="string"?je.payment_method:je?.payment_method?.id;o({id:y??je?.id,type:"card",threeDSecureActionResultTokenId:je?.id,isPaypal:!0},{accountPatch:I,sessionId:we,nonce:Me});return}catch(C){j(C,"stripe_paypal_failed",Y?.generation)}finally{oe(!1)}},[H,P,e,t,n,m,be,M,r,ve,o,a,S,g,j,te,Fe,ae,ee]);return ke(fr,{children:[l(As,{state:fe,placeholderTestId:"flopay-paypal-placeholder",borderRadius:u,children:ke("div",{ref:Te,tabIndex:-1,"data-testid":"flopay-paypal-focus-target",role:"group","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[L&&l("button",{ref:Ae,type:"button","data-testid":"flopay-paypal-retry-button",onClick:Je,style:_s,children:"Try PayPal again"}),He&&l(Ir,{identity:He.identity,methodLabel:He.methodLabel,onComplete:Rt,onCancel:()=>Rt(null)},He.id),l("div",{style:{display:He?"none":void 0},children:l(Is,{onReady:G=>Q(Ts(G,["paypal"])),onLoadError:()=>{Q("load_error"),Va(jt(w),"paypal","paypal")},onClick:We,onConfirm:Se,onCancel:()=>{let G=Ue.current.get(ee);Ue.current.delete(ee),jt(w)?.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),T(G?.generation),me(!1),et.current=!0,ie()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:Ce,emailRequired:Ce,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},ee)})]})}),ce&&l(Yn,{status:"processing"})]})}function ws({sessionId:e,nonce:t,email:n,billingApiUrl:r,intentKind:o,expressMethods:a,onTokenizedBody:c,onErrorChange:s,onButtonClick:S,onDecline:b,onTechnicalFailure:g,runBeforeButtonClick:m,billingName:M,onBuyerIdentityReady:D,onLoadStateChange:u,placeholderBorderRadius:w}){let ve=ur(),{emitInstrument:H}=Yr(In),P=Ka(),fe=ja(),[Q,ce]=ye("loading");ht(()=>{u?.(Q)},[Q,u]);let[oe,Ce]=ye(!1),He=!en(n?.trim())||!M?.trim(),{request:be,collect:Rt,finish:De}=qr(),Te=Ie(null),Ae=Ie(null),[ee,J]=ye(0),[L,me]=ye(!1),[et,Ue]=ye("google_pay"),Ye=Ie(!1),te=Ie("google_pay"),T=Ie("google_pay"),ae=Ie(new Map),{startAttempt:Fe,finishAttempt:ie,invalidateAttempt:j,isAttemptInvalidated:_e,isAttemptCurrent:Je}=xs((x,K,I)=>{g?.(x,K,{...I,popupBlocked:I?.popupBlocked??dr(K)}),Ue(x),me(!0),J(C=>C+1)});ht(()=>{L&&Ae.current?.focus()},[L,ee]);let We=Pe(()=>{J(x=>x+1)},[]),Se=Pe((x,K,I,C)=>{j(C),g?.(x,K,{code:I,popupBlocked:dr(K)}),Ue(x),me(!0),We()},[j,g,We]),G=Pe(()=>{window.setTimeout(()=>{(Te.current?.querySelector("iframe")??Te.current)?.focus()},0)},[]);ht(()=>{Ye.current&&(Ye.current=!1,G())},[G,ee]);let Y=Pe(()=>{me(!1),s?.(null),G()},[G,s]),$=Pe(async x=>{if(!P||!fe)return;let K=ae.current.get(ee);if(K&&!Je(K.generation)){ae.current.delete(ee);return}if(!K&&_e()||K&&!ie(K.generation))return;K||ie();let I=x.expressPaymentType??K?.method??te.current,C=K??null;ae.current.delete(ee);let nt=vs(I);if(!C&&m){let y=await m(nt);if(!y.proceed){x.paymentFailed({reason:"fail",message:"Wallet checkout was cancelled."});return}C={accountPatch:y.accountPatch,sessionId:y.sessionId,nonce:y.nonce}}let St=nt,de=C?.sessionId??e,ct=C?.nonce??t,it=await Rs({event:x,prepared:C,email:n,billingName:M,methodLabel:qa(I),collect:Rt});if(!it){x.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let rt=it.email,je={...C?.accountPatch,...it};try{if(Ce(!0),s?.(null),!en(rt))throw new Error("Missing sessionId or email for wallet payment");await D?.(it);let{error:y}=await fe.submit();if(y){Se(I,y,"stripe_wallet_submit_failed",K?.generation);return}let{error:U,paymentMethod:Xe}=await P.createPaymentMethod({elements:fe});if(U||!Xe){Se(I,U??new Error("Failed to create payment method."),"stripe_wallet_create_payment_method_failed",K?.generation);return}if(!de)throw new Error("Missing sessionId or email for wallet payment");let dt=await oa(r,H,de,ct??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:I??nt,paymentMethodId:Xe.id,intentKind:o});if(dt.provider!=="stripe")throw new Error("Invalid provider returned for wallet intent");let Mt=dt.clientSecret,{error:Bt,intentId:W}=lc(Mt)?await P.confirmCardSetup(Mt,{payment_method:Xe.id}).then(Le=>({error:Le.error,intentId:Le.setupIntent?.id})):await P.confirmCardPayment(Mt,{payment_method:Xe.id}).then(Le=>({error:Le.error,intentId:Le.paymentIntent?.id}));if(Bt){if(go(Bt)){let Le=Bt.message??"Your payment was declined.";s?.(Le),b?.($t(St,Le,{code:tr(Bt),declineCode:$r(Bt)})),await aa({billingApiUrl:r,sessionId:de,nonce:ct,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:I??nt,providerDeclineReason:tr(Bt)??"provider_declined"}})}else Se(I,Bt,"stripe_wallet_confirm_failed",K?.generation);return}c({id:Xe.id,type:"card",threeDSecureActionResultTokenId:W},{accountPatch:je,sessionId:de,nonce:ct})}catch(y){Se(I,y,"stripe_wallet_failed",K?.generation)}finally{Ce(!1)}},[P,fe,e,t,n,M,Rt,D,r,H,o,c,s,b,m,Se,ie,Je,_e,ee]),we=gt(()=>{let x=["applePay","googlePay","paypal","link","amazonPay","klarna"],K=new Set(["applePay","googlePay"]),I=new Set(a.map(gs)),C={};for(let nt of x)I.has(nt)?C[nt]=K.has(nt)?"always":"auto":C[nt]="never";return C},[a]),Me=gt(()=>a.map(gs),[a]);return ke(fr,{children:[l(As,{state:Q,placeholderTestId:"flopay-wallet-placeholder",borderRadius:w,children:ke("div",{ref:Te,tabIndex:-1,"data-testid":"flopay-wallet-focus-target",role:"group","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[L&&ke("button",{ref:Ae,type:"button","data-testid":"flopay-wallet-retry-button",onClick:Y,style:_s,children:["Try ",qa(et)," again"]}),be&&l(Ir,{identity:be.identity,methodLabel:be.methodLabel,onComplete:De,onCancel:()=>De(null)},be.id),l("div",{style:{display:be?"none":void 0},children:l(Is,{onReady:x=>{ce(Ts(x,Me))},onLoadError:x=>{ce("load_error"),Va(jt(ve),"stripe","wallet")},onClick:async x=>{te.current=x.expressPaymentType,T.current=vs(x.expressPaymentType);let K=m?await m(T.current):{proceed:!0};if(!K.proceed){ae.current.delete(ee),x.reject();return}let I=Fe(x.expressPaymentType);ae.current.set(ee,{generation:I,method:x.expressPaymentType,accountPatch:K.accountPatch,sessionId:K.sessionId,nonce:K.nonce}),me(!1),S?.(T.current),x.resolve()},onConfirm:$,onCancel:()=>{let x=ae.current.get(ee);ae.current.delete(ee),jt(ve)?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet"}),j(x?.generation),me(!1),Ye.current=!0,We()},options:{buttonType:{applePay:"plain",googlePay:"plain"},paymentMethods:we,emailRequired:He,billingAddressRequired:He,layout:{maxColumns:1,overflow:"never"}}},ee)})]})}),oe&&l(Yn,{status:"processing"})]})}function xc({method:e,themeId:t,submitting:n=!1,disabled:r=!1,highlighted:o=!1,hasNextStep:a=!1,onClick:c,backgroundColor:s,borderColor:S,textColor:b,borderRadius:g,fontFamily:m}){let M=yc(e,t),D=ps[e],[u,w]=ye(!1),ve=M?.backgroundColor??s??"#ffffff",H=M?.borderColor??S??"#d1d5db",P=M?.textColor??b??"#262833";return l("button",{type:"button","data-testid":`flopay-stripe-method-button-${e}`,"data-method":e,onClick:()=>{!n&&!r&&c()},disabled:n||r,"aria-busy":n||void 0,style:{position:"relative",width:"100%",boxSizing:"border-box",height:ra,padding:"0 1rem",backgroundColor:ve,color:P,border:`1px solid ${H}`,borderRadius:g??8,fontSize:"0.95rem",fontWeight:600,fontFamily:m,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?l("span",{style:{margin:"0 auto"},children:`Connecting to ${xr(e)}\u2026`}):ke(fr,{children:[ke("span",{style:{display:"inline-flex",alignItems:"center",gap:ic(e)?8:0},children:[D&&!u?l("img",{src:D,alt:"","aria-hidden":"true",onError:()=>w(!0),loading:"lazy",decoding:"async",width:30,height:20,style:{width:30,height:20,flexShrink:0,borderRadius:3,objectFit:"contain",display:"inline-flex"}}):M?.logoSvg?l("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:M.logoSvg}}):null,l("span",{children:xr(e)})]}),a&&l("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:P,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:l("path",{d:"M9 18l6-6-6-6"})})]})})}function $a({method:e,sessionId:t,nonce:n,email:r,billingName:o,onBuyerIdentityReady:a,billingApiUrl:c,onTokenizedBody:s,onErrorChange:S,onDecline:b,onCancel:g,runBeforeButtonClick:m,onButtonClick:M,isProcessing:D,submitButtonColor:u,submitButtonBorderRadius:w,submitButtonStyle:ve,errorText:H}){let P=ur(),{emitInstrument:fe}=Yr(In),Q=Ka(),ce=ja(),[oe,Ce]=ye(!1),He=Ie(!1),[be,Rt]=ye(!1),[De,Te]=ye("loading"),[Ae,ee]=ye(""),[J,L]=ye(""),me=!en(r?.trim()),et=!o?.trim(),Ue=(!me||en(Ae.trim()))&&(!et||!!J.trim()),Ye=Pe(async()=>{if(!Q||!ce||D||He.current||!be)return;He.current=!0,Ce(!0);let te=m?await m("card"):{proceed:!0};if(!te.proceed){He.current=!1,Ce(!1);return}M?.("card");let T=te.sessionId??t,ae=te.nonce??n,Fe=kn(o?.trim()||J.trim()),ie={email:te.accountPatch?.email?.trim()||r?.trim()||Ae.trim(),firstName:te.accountPatch?.firstName?.trim()||Fe.firstName,lastName:te.accountPatch?.lastName?.trim()||Fe.lastName},j=ie.email,_e={...te.accountPatch,...ie};try{if(S?.(null),!en(j)||!fo(ie))throw new Error("A valid email address and full name are required for payment.");await a?.(ie);let Je=await ce.submit();if(Je.error){S?.(Je.error.message??"Payment failed.");return}let We=await Q.createPaymentMethod({elements:ce,params:{billing_details:{email:j,name:[ie.firstName,ie.lastName].filter(Boolean).join(" ")}}});if(We.error||!We.paymentMethod){S?.(We.error?.message??"Failed to create payment method.");return}let Se=We.paymentMethod;if(!T||!j)throw new Error("Missing sessionId or email for payment.");let G=Se.type||e,Y=await oa(c,fe,T,ae??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:G,paymentMethodId:null,intentKind:"payment"});if(Y.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let $=Y.clientSecret;if(typeof window<"u")try{localStorage.setItem(Gn,JSON.stringify({clientSecret:$,sessionId:T,nonce:ae,accountPatch:_e,paymentMethodId:Se.id,paymentMethodType:Se.type??e,gateway:"stripe"}))}catch{}let{error:we,paymentIntent:Me}=await Q.confirmPayment({clientSecret:$,confirmParams:{return_url:window.location.href,payment_method:Se.id},redirect:"if_required"});if(we){if(typeof window<"u")try{localStorage.removeItem(Gn)}catch{}let I=we.message??"Payment failed.";S?.(I),b?.($t("card",I,{code:we.code})),await aa({billingApiUrl:c,sessionId:T,nonce:ae,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:we.code??"provider_declined"}});return}let x=Me?.status;if(!jo(x)){if(typeof window<"u")try{localStorage.removeItem(Gn)}catch{}let I=x==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";S?.(I),b?.($t("card",I,{code:x??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(Gn)}catch{}let K=typeof Me?.payment_method=="string"?Me.payment_method:Me?.payment_method?.id;s({id:K??Se.id,type:"card",threeDSecureActionResultTokenId:Me?.id,gateway:"stripe",paymentMethodType:Se.type??e},{accountPatch:_e,sessionId:T,nonce:ae})}catch(Je){S?.(Je instanceof Error?Je.message:"Payment failed. Please try again.")}finally{He.current=!1,Ce(!1)}},[Q,ce,D,be,m,M,t,n,r,o,Ae,J,a,c,fe,e,s,S,b]);return ke("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[(me||et)&&ke("div",{"data-testid":"flopay-apm-identity-fields",style:{display:"flex",flexDirection:"column",gap:"0.75rem",marginBottom:"0.75rem"},children:[me&&ke("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",l("input",{type:"email",autoComplete:"email",required:!0,value:Ae,onChange:te=>ee(te.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]}),et&&ke("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Full name",l("input",{type:"text",autoComplete:"name",required:!0,value:J,onChange:te=>L(te.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]})]}),l(gc,{onReady:()=>Te("ready"),onLoadError:()=>{Te("load_error"),Va(jt(P),"stripe","apm")},onChange:te=>{Rt(!!te.complete)},options:{layout:{type:"accordion",defaultCollapsed:!1,radios:"never"},defaultValues:{billingDetails:{...o?.trim()?{name:o.trim()}:{},...en(r?.trim())?{email:r?.trim()}:{}}}}}),l("button",{type:"button","data-testid":`flopay-stripe-method-pay-${e}`,onClick:()=>{Ye()},disabled:!be||!Ue||oe||D||De!=="ready",style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:u,color:"white",border:"none",borderRadius:w,fontSize:"1rem",fontWeight:600,cursor:!be||!Ue||oe||D||De!=="ready"?"not-allowed":"pointer",opacity:!be||!Ue||oe||D||De!=="ready"?.5:1,transition:"opacity 120ms ease-out",...ve??{}},children:oe?"Processing\u2026":`Pay with ${xr(e)}`}),H&&l(Kr,{margin:"0.75rem 0 0",children:H})]})}function ks({sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:a,paymentElementMethods:c,stripeInstance:s,paymentElementBaseOptions:S,onTokenizedBody:b,onErrorChange:g,onButtonClick:m,onDecline:M,runBeforeButtonClick:D,onLoadStateChange:u,isProcessing:w=!1,submitButtonColor:ve="#4A49FF",submitButtonBorderRadius:H=8,submitButtonStyle:P,buttonAppearance:fe,themeId:Q,onExpandApm:ce,expandedApmMethod:oe}){let{emitInstrument:Ce}=Yr(In),[He,be]=ye(null),[Rt,De]=ye(null),Te=Ie(!1),{request:Ae,collect:ee,finish:J}=qr();ht(()=>{c.length>0&&s?u?.("ready"):s||u?.("loading")},[c.length,s,u]);let L=Pe(async T=>{if(!s||Te.current||w)return;Te.current=!0,De(T);let ae=D?await D("card"):{proceed:!0};if(!ae.proceed){Te.current=!1,De(null);return}m?.("card");let Fe=ae.sessionId??e,ie=ae.nonce??t,j=kn([ae.accountPatch?.firstName,ae.accountPatch?.lastName].filter(Boolean).join(" ")||r),_e={email:ae.accountPatch?.email?.trim()||n?.trim(),firstName:ae.accountPatch?.firstName?.trim()||j.firstName,lastName:ae.accountPatch?.lastName?.trim()||j.lastName};if(!en(_e.email)||!fo(_e)){De(null);let Se=await ee(xr(T),_e);if(!Se){Te.current=!1;return}_e=Se,De(T)}let Je=_e.email,We={...ae.accountPatch,..._e};try{if(g?.(null),!Fe||!en(Je)||!fo(_e))throw new Error("Missing sessionId or email for payment.");await o?.(_e);let Se=await oa(a,Ce,Fe,ie??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:T,paymentMethodId:null,intentKind:"payment"});if(Se.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let G=Se.clientSecret;if(typeof window<"u")try{localStorage.setItem(Gn,JSON.stringify({clientSecret:G,sessionId:Fe,nonce:ie,accountPatch:We,paymentMethodType:T,gateway:"stripe"}))}catch{}let{error:Y,paymentIntent:$}=await s.confirmPayment({clientSecret:G,confirmParams:{return_url:window.location.href,payment_method_data:{type:T,billing_details:{name:[_e.firstName,_e.lastName].filter(Boolean).join(" "),...Je?{email:Je}:{}}}},redirect:"if_required"});if(Y){if(typeof window<"u")try{localStorage.removeItem(Gn)}catch{}let x=Y.message??"Payment failed.";g?.(x),M?.($t("card",x,{code:Y.code})),await aa({billingApiUrl:a,sessionId:Fe,nonce:ie,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:T,providerDeclineReason:Y.code??"provider_declined"}});return}let we=$?.status;if(!jo(we)){if(typeof window<"u")try{localStorage.removeItem(Gn)}catch{}let x=we==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";g?.(x),M?.($t("card",x,{code:we??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(Gn)}catch{}let Me=typeof $?.payment_method=="string"?$.payment_method:$?.payment_method?.id;b({id:Me??$?.id,type:"card",threeDSecureActionResultTokenId:$?.id,gateway:"stripe",paymentMethodType:T},{accountPatch:We,sessionId:Fe,nonce:ie})}catch(Se){g?.(Se instanceof Error?Se.message:"Payment failed. Please try again.")}finally{Te.current=!1,De(null)}},[s,w,D,m,e,t,n,ee,a,Ce,r,o,b,g,M]),[me,et]=ye(null),Ue=ce?oe??null:me,Ye=Pe(T=>{Te.current||w||Ue&&Ue!==T||(fs(T)?ce?ce(T):et(T):L(T))},[Ue,w,L,ce]),te=gt(()=>me?{...S,paymentMethodTypes:[me]}:null,[me,S]);return l("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:Ae?l(Ir,{identity:Ae.identity,methodLabel:Ae.methodLabel,onComplete:J,onCancel:()=>J(null)},Ae.id):c.map(T=>{let ae=oe===T,Fe=Rt===T,ie=Rt!==null&&Rt!==T||oe!=null&&oe!==T;return ke(hc.Fragment,{children:[l(xc,{method:T,themeId:Q,submitting:Fe,disabled:ie,highlighted:ae,hasNextStep:fs(T),onClick:()=>Ye(T),backgroundColor:fe?.backgroundColor,borderColor:fe?.borderColor,textColor:fe?.textColor,borderRadius:fe?.borderRadius,fontFamily:fe?.fontFamily}),!ce&&me===T&&te&&s&&l(_r,{stripe:s,options:te,children:l($a,{method:T,sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:a,onTokenizedBody:b,onErrorChange:g,onDecline:M,onCancel:()=>et(null),runBeforeButtonClick:D,onButtonClick:m,isProcessing:w,submitButtonColor:ve,submitButtonBorderRadius:H,submitButtonStyle:P})},T)]},T)})})}function Tc({sessionId:e,nonce:t,billingApiUrl:n,email:r,userId:o,onComplete:a,onError:c,onDecline:s,onTokenizedBody:S,firstName:b,lastName:g,chv:m,className:M,isProcessing:D,error:u,onErrorChange:w,showPayPal:ve=!0,showStripe:H=!0,enabledPaymentMethods:P,enabledPaymentMethodCountries:fe,showApplePay:Q=!0,showGooglePay:ce=!0,layout:oe="default",theme:Ce,buttonsTheme:He,buttonsStyles:be,appearance:Rt,cardButtonContent:De,cardBackButtonContent:Te,cardTitleContent:Ae,showSecurityFooter:ee,onButtonClick:J,onBeforeButtonClick:L,onBuyerIdentityReady:me,enableAVS:et,cardFieldOrder:Ue,cardPreFormSlot:Ye,avsLayout:te="row",country:T,zip:ae,addressLine1:Fe,addressLine2:ie,city:j,state:_e,onCountryChange:Je,onZipChange:We,avsCheck:Se,checkoutType:G,checkoutLayout:Y,totalAmount:$=0,currency:we="usd",initialCardOpen:Me=!1,directPaypal:x,isSubscription:K=!1,session:I,dataAttachmentPending:C=!1,dataAttachmentRequiresIdentity:nt=!1,debug:St=!1}){let de=ur(),ct=_a(),it=Yr(Ln),{emitInstrument:rt}=Yr(In),je=C||it.claimPending===!0,y=nt||it.claimRequiresIdentity===!0,U=je&&!y,Xe=Ji(),[dt,Mt]=ye(!1),[Bt,W]=ye(null),[Le,Wt]=ye(T??"US"),[wt,Ot]=ye(ae??""),[Rn,_n]=ye(Fe??""),[Zn,Jt]=ye(ie??""),[cn,dn]=ye(j??""),[Ft,vn]=ye(_e??""),[bt,ir]=ye(""),[Ht,sr]=ye(""),[Nt,zn]=ye({}),ot=Ie(ae??""),_t=Ie(T??"US"),xt=Ie(Fe??""),tn=Ie(ie??""),un=Ie(j??""),pn=Ie(_e??""),Un=Ie(""),qn=Ie(""),zt=Ie({});ht(()=>{let i=(R,N,he,z,Re)=>{if(zt.current[R])return;let Ne=N?.trim();!Ne||Ne===he.current||(he.current=Ne,z(Ne),Re?.(Ne))};i("country",T,_t,Wt,Je),i("zip",ae,ot,Ot,We),i("addressLine1",Fe,xt,_n),i("addressLine2",ie,tn,Jt),i("city",j,un,dn),i("state",_e,pn,vn)},[T,ae,Fe,ie,j,_e,Je,We]);let X=gt(()=>pc(et),[et]),Pn=X!==null,xn=gt(()=>La(I),[I]),Qn=!!I?.vault?.html,br=!!I?.gateways?.pcivault,Tn=!!(I?.gateways?.stripe?.enabledPaymentMethods??P)?.includes("card"),mn=Qn||Tn||br,Be=!!(H&&mn&&de&&e),[Xt,Dt]=ye(()=>oe!=="buttons"||Me?e??null:null),[$n,v]=ye(0),ut=oe!=="buttons"||Me||!!e&&Xt===e,qe=gt(()=>!de||!Be||!e||!ut?null:de.cardCapture({sessionId:e,captureMethod:I?.captureMethod}),[de,Be,e,ut,I?.captureMethod]),yn=gt(()=>{let i=Le,R=X?ze(X.postal_code,i):!1;return Ec(i,wt,R)},[X,Le,wt]),{avsInvalid:Ze,invalidAvsFields:Ut}=gt(()=>{let i={line1:!1,city:!1,state:!1,zip:!1};if(!Be||!X)return{avsInvalid:!1,invalidAvsFields:i};let R=Le,N=(Re,Ne)=>ze(Re,R)&&!Ne.trim(),he={line1:N(X.address_line_1,Rn),city:N(X.city,cn),state:N(X.state,Ft),zip:yn.empty||yn.malformed};return{avsInvalid:he.line1||he.city||he.state||he.zip,invalidAvsFields:he}},[Be,X,Le,Rn,cn,Ft,yn]),[lr,jn]=ye(!1),[Cn,Zt]=ye(!1),[fn,gn]=ye(()=>Oa(I?.vault)),[xe,kt]=ye(Me&&mn?"card":"buttons"),[Tt,An]=ye(null),hn=xe==="expanding"||xe==="card",Mn=I?.gateways?.stripe?"stripe":void 0,Bn=Pe(()=>{rt?.({class:"card_surface",provider:Mn})},[Mn,rt]),qt=280,on=Ie(null),an=Pe(i=>{on.current&&clearTimeout(on.current),on.current=setTimeout(()=>{on.current=null,i()},qt)},[qt]);ht(()=>()=>{on.current&&clearTimeout(on.current)},[]);let er=Pe(()=>{Bn(),Dt(e??null),v(i=>i+1),kt("expanding"),an(()=>kt("card"))},[an,Bn,e]),Ar=Pe(()=>{kt("collapsing"),an(()=>kt("buttons"))},[an]),Fn=Pe(i=>{An(i),kt("apm-expanding"),an(()=>kt("apm-form"))},[an]),Kn=Pe(()=>{kt("apm-collapsing"),an(()=>{kt("buttons"),An(null)})},[an]);ht(()=>{oe==="buttons"&&Me&&mn&&(Dt(e??null),kt("card"))},[oe,Me,mn,e]);let[Qt,at]=ye(null),Yt=Ie(!1),_=Ie(null),E=Ie("idle"),[V,Z]=ye(null),$e=Ie(V);ht(()=>{$e.current=V},[V]);let ne=n||Xe,B=u??Bt,h=gt(()=>fc(Ce),[Ce]),f=gt(()=>{let i=h?.buttonsLayout??mc(He);return be?{...i,...be,cardButton:{...i.cardButton,...be.cardButton},cardFormContainer:{...i.cardFormContainer,...be.cardFormContainer},backButton:{...i.backButton,...be.backButton},backButtonIcon:{...i.backButtonIcon,...be.backButtonIcon},submitButton:{...i.submitButton,...be.submitButton},title:{...i.title,...be.title}}:i},[h,He,be]),O=Rt??h?.appearance,pt=gt(()=>zi({appearance:O,buttonsStyles:f,layout:oe}),[O,f,oe]),vt=it.inlineSessionPatchProcessing??!1,d=(D??dt)||vt,p=ne.replace(/\/+$/,""),k=gt(()=>Ia({userId:o,email:r,firstName:b,lastName:g,country:T,zip:ae},Nt),[o,r,b,g,T,ae,Nt]),Ee=[k.firstName,k.lastName].filter(i=>!!i?.trim()).join(" "),q=!en(k.email?.trim()),F=!Ee.trim(),Ge=Ie(null),Qe=Ie(null);Be&&(Ge.current===null&&(Ge.current=q),Qe.current===null&&(Qe.current=F));let se=Be&&(Ge.current??q),ue=Be&&(Qe.current??F),A=se||ue,le=gt(()=>Rc(bt,se),[bt,se]),st=le.empty||le.malformed,Lt=ue&&!Ht.trim(),ge=gt(()=>de?de.getRawProvider():null,[de]),bn=gt(()=>ct?ct.getRawProvider():null,[ct]),Qr=$||100,_o=gt(()=>O?ec(O):null,[O]),xo=_o?{appearance:_o}:null,li=gt(()=>{let i=_o??{},R=i.rules??{};return{...i,rules:{...R,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...R[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...R[".AccordionItemContents"]??{}}}}},[_o]),ci=gt(()=>{let i=Hi($);return{...i,currency:we.toLowerCase(),paymentMethodCreation:"manual",...i.mode==="payment"?{captureMethod:"manual"}:{},...xo}},[$,we,xo]),di=gt(()=>({mode:"payment",amount:Qr,currency:we.toLowerCase(),captureMethod:"manual",setupFutureUsage:"off_session",...xo}),[Qr,we,xo]),pe=Pe(i=>{W(i),w?.(i)},[w]),da=Ie(""),[ui,$s]=ye(!1),To=Pe(()=>{$s(!0)},[]);ht(()=>{if(!Be||!A||!me||!ui||st||Lt||da.current)return;let i=kn(qn.current),R={email:en(k.email?.trim())?k.email?.trim():Un.current.trim(),firstName:k.firstName?.trim()||i.firstName,lastName:k.lastName?.trim()||i.lastName};da.current=JSON.stringify(R),zn(N=>({...N,...R})),Promise.resolve(me(R)).catch(N=>{da.current="",pe(N instanceof Error?N.message:"Failed to attach buyer details.")})},[Be,A,me,ui,st,Lt,k.email,k.firstName,k.lastName,pe]),ht(()=>{!Be||!qe||qe.setCardFieldOrder?.(Ue??null,X==null&&!A)},[Be,qe,Ue,X,A]),ht(()=>{(xe==="expanding"||xe==="collapsing"||xe==="apm-expanding"||xe==="apm-collapsing")&&pe(null)},[xe,pe]);let Nn=Pe((i,R,N)=>{s?.($t(i,R,N))},[s]),Mr=Pe((i,R,N)=>{let he=N?.popupBlocked??dr(R),z=kc(i,he),Re=Er(N?.code)??tr(R)??"external_payment_method_failed",Ne=new On(z,"api_error",{code:"external_payment_method_failed",param:i});at(null),oe==="buttons"&&(kt("buttons"),An(null)),pe(z),c?.(Ne),console.error("[FloPay] External payment method failed:",{method:i,code:Re,popupBlocked:he})},[oe,c,pe]);ht(()=>{if(!Be||!e){gn(null);return}let i=Oa(I?.vault);if(i){gn(i);return}if(!ut){gn(null);return}gn(null);let R=!0;return new So(p).getVaultCapture(e,t).then(N=>{if(!R)return;let he=Oa(N);he?gn(he):pe("Failed to load the secure card form.")}).catch(N=>{R&&pe(N instanceof Error?N.message:"Failed to load the secure card form.")}),()=>{R=!1}},[Be,ut,$n,e,I?.vault?.html,I?.vault?.messageToken,I?.vault?.expectedOrigin,p,t,pe]);let Vn=Ie({onComplete:a,onError:c,updateError:pe,emitDecline:Nn,resolvedAccount:k,avsConfig:X,avsCheckProp:Se,sessionId:e,nonce:t,baseUrl:p,captureMethod:I?.captureMethod,paymentId:I?.paymentId,authorizationExpiresAt:I?.authorizationExpiresAt});Vn.current={onComplete:a,onError:c,updateError:pe,emitDecline:Nn,resolvedAccount:k,avsConfig:X,avsCheckProp:Se,sessionId:e,nonce:t,baseUrl:p,captureMethod:I?.captureMethod,paymentId:I?.paymentId,authorizationExpiresAt:I?.authorizationExpiresAt};let ua=Ie(!1),js=Pe(()=>{let{resolvedAccount:i,avsConfig:R,avsCheckProp:N}=Vn.current,he=i.email?.trim(),z=en(he)?he:Un.current.trim();if(!en(z))return null;let Re=kn(qn.current),Ne=i.firstName?.trim()||Re.firstName,It=i.lastName?.trim()||Re.lastName;if(!Ne&&!It)return null;let Ct=_t.current||i.country||"US",mt=R?ze(R.state,Ct):!1,yt=R?ze(R.address_line_1,Ct):!1,Ke=R?ze(R.postal_code,Ct):!1,nn=R?ze(R.city,Ct):!1,Oe=R?ze(R.address_line_2,Ct):!1,ln=yt&&!mt&&Ke?ms(Ct,(ot.current??"").trim()):null,rn=mt?pn.current:ln;return{accountData:{userId:i.userId??"",email:z,firstName:Ne??"",lastName:It??"",...Ke&&ot.current?{zip:ot.current}:{},...nn&&un.current?{city:un.current}:{},...rn?{state:rn}:{},...yt&&xt.current?{addressLine1:xt.current}:{},...Oe&&tn.current?{addressLine2:tn.current}:{},country:Ct},...N!==void 0?{avsCheck:N}:{},...R?{avsConfig:{country:ze(R.country,Ct),postal_code:Ke,address_line_1:yt,address_line_2:Oe,city:nn,state:mt}}:{}}},[]),pi=Ie(je);pi.current=je,ht(()=>{je||B!==bs||Vn.current.updateError(null)},[je,B]),ht(()=>{!Be||!qe||qe.setSubmitGate?.(Ze||je||st||Lt)},[Be,qe,Ze,je,st,Lt]),ht(()=>{if(!Be||!qe)return;ua.current=!1;let i=!1,R=qe.on("submitting",()=>{jn(!0),_.current&&clearTimeout(_.current),E.current="validation-window",_.current=setTimeout(()=>{_.current=null,E.current==="validation-window"&&(E.current="processing")},bc),at("processing");let{baseUrl:Ne,sessionId:It,nonce:Ct,updateError:mt,onError:yt}=Vn.current;if(!It||!Ct)return;let Ke=js();if(!Ke){mt("Enter a valid email address."),E.current="idle",at(null);return}new So(Ne).patchAccountSnapshot(It,Ct,Ke,{telemetryMode:"best_effort"}).catch(nn=>{if(!vc(nn))return;let Oe=nn instanceof Error?nn.message:"Please check your billing address and try again.";mt(Oe),E.current="idle",at(null),yt?.(nn instanceof On?nn:new On(Oe,"api_error"))})}),N=qe.on("complete",async Ne=>{if(Vr(Ne.sessionId??Vn.current.sessionId),E.current="terminal",at("success"),await new Promise(mt=>setTimeout(mt,1200)),ua.current)return;ua.current=!0;let It=Vn.current,Ct=La(It)||Ne.outcome==="authorized";Vn.current.onComplete?.(Ct?{status:"authorized",paymentIntentId:Ne.intentId,paymentId:Ne.paymentId??It.paymentId,sessionId:Ne.sessionId??It.sessionId,authorizationExpiresAt:Ne.authorizationExpiresAt??It.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",paymentIntentId:Ne.intentId,checkoutMethod:"card"})}),he=qe.on("decline",async Ne=>{let{updateError:It,emitDecline:Ct}=Vn.current,mt=Ne.message??"Your payment was declined. Please try another card or contact your bank.";E.current="terminal",It(mt),at("error");let yt=Ne.failureOutcome??dc(Ne.declineReason)??"authorization_declined";Ct("card",mt,{code:yt,declineCode:yt}),await new Promise(Ke=>setTimeout(Ke,1500)),!i&&(E.current="idle",at(null))}),z=qe.on("error",async Ne=>{let{updateError:It,onError:Ct}=Vn.current,mt=Ne.message??"There was a problem processing your payment. Please try again.";E.current="terminal",It(mt),at("error"),Ct?.(new On(mt,"api_error",{code:Ne.failureOutcome??"capture_failed"})),await new Promise(yt=>setTimeout(yt,1500)),!i&&(E.current="idle",at(null))}),Re=qe.on("blocked",()=>{if(!pi.current){jn(!0);return}To(),Vn.current.updateError(bs)});return()=>{i=!0,_.current&&(clearTimeout(_.current),_.current=null),E.current="idle",R(),N(),he(),z(),Re()}},[Be,qe,To]);let Hn=!!x?.clientId,eo=Array.isArray(P),Ao=eo&&P.length>0,Ks=eo&&P.includes("paypal"),{expressMethods:Mo,paymentElementMethods:to}=gt(()=>uc(P,{excludePaypal:Hn}),[P,Hn]),mi=Hn||!!ct,Vs=gt(()=>mi?Mo.filter(i=>i!=="paypal"):Mo,[Mo,mi]),Hs=gt(()=>{let i=[];return Q&&i.push("apple_pay"),ce&&i.push("google_pay"),i},[Q,ce]),Bo=eo?Vs:Hs,Ys=H&&Bo.length>0,pa=Pn?Le:T,Fo=gt(()=>{let i=pa?.trim().toUpperCase();return i?fe?to.filter(R=>{let N=fe[R];return!N||N.length===0||N.includes(i)}):rc(to,pa):to},[to,pa,fe]),ma=gt(()=>({mode:"payment",amount:Qr,currency:we.toLowerCase(),paymentMethodCreation:"manual",appearance:li}),[Qr,we,li]),[yi,fi]=ye("loading"),[gi,hi]=ye("loading"),[bi,vi]=ye("loading"),[Gs,ya]=ye(!1),[Pi,fa]=ye("loading"),[No,Ws]=ye();ht(()=>{Ws(us())},[]);let Ci=ve&&(Hn||(eo?Ks:No===!1)),Si=H&&Ys,no=!U&&Ci&&Hn,wi=Pi==="retrying"||Pi==="exhausted",ro=!U&&Ci&&!!bn&&(!Hn||wi),oo=!U&&Si&&!!ge,ao=!U&&H&&Ao&&Fo.length>0&&!!ge,Js=no&&!wi?Gs:ro&&Cs(yi),Xs=oo&&Cs(gi),Zs=ao&&bi!=="load_error",ki=i=>i==="loading"||i==="ready",Ii=no||ro&&ki(yi)||oo&&ki(gi)||ao&&bi!=="load_error",Do=Ie(!1);ht(()=>{if(!Do.current){if(!H&&!ve){Do.current=!0;let i=new On("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");c?.(i),pe(i.message)}else if(!H&&ve&&!Hn&&!bn){Do.current=!0;let i=new On("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");c?.(i),pe(i.message)}else if(No!==void 0&&!U&&!mn&&!Ii){Do.current=!0;let i=new On("FloPay: this checkout session has no vault card capability and no usable supported non-card payment methods. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});c?.(i),pe(i.message)}}},[H,ve,Hn,bn,No,U,mn,Ii,c,pe]);let Ei=Ie(!1);ht(()=>{if(Ei.current||!Ao)return;let i=[];Q!==!0&&i.push("showApplePay"),ce!==!0&&i.push("showGooglePay"),i.length!==0&&(Ei.current=!0,console.warn(`[FloPay] ${i.join(" / ")} ${i.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.`))},[Ao,Q,ce]);let Ri=Pe((i,R)=>it.applyInlineSessionPatch?it.applyInlineSessionPatch(i).then(N=>({error:null,sessionId:N.sessionId||e,nonce:N.session?.clientSecret||t})).catch(N=>{let he=Ps(R,N);return pe(he.message),c?.(he),{error:he,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[it.applyInlineSessionPatch,t,c,e,pe]),Dn=Pe(async i=>{if(!L)return{proceed:!0};try{let R=await L({method:i,sessionId:e||void 0,createSession:it.inlineSessionDraft});if(R===!1)return{proceed:!1};if(R&&typeof R=="object"){R.account&&zn(he=>({...he??{},...R.account}));let N=await Ri(R,i);return N.error?{proceed:!1,accountPatch:R.account}:{proceed:!0,accountPatch:R.account,sessionId:N.sessionId,nonce:N.nonce}}return{proceed:!0}}catch(R){let N=Ps(i,R);return pe(N.message),c?.(N),{proceed:!1}}},[Ri,it.inlineSessionDraft,L,c,e,pe]),_i=Pe(async(i,R)=>{if(Yt.current)return;Yt.current=!0,Mt(!0),at("processing"),pe(null);let N=R?.sessionId??e,he=R?.nonce??t,z=Ia(k,R?.accountPatch),Re=R?.completionPaymentMethodId??yo(i),Ne=i.originalPaymentMethodId?{...i,originalPaymentMethodId:void 0}:i,It=i.gateway==="stripe"?"stripe":i.gateway==="paypal"||i.isPaypal?"paypal":void 0,Ct=()=>{rt?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"process_payment",provider:It})};try{let yt=await new So(p).processPayment(z.userId??"",{sessionId:N,nonce:he,tokenizedData:Ne,accountData:{userId:z.userId??"",email:z.email??"",firstName:z.firstName??"",lastName:z.lastName??"",...X?(()=>{let Oe=_t.current,ln=ze(X.state,Oe),rn=ze(X.address_line_1,Oe),Gt=ze(X.postal_code,Oe),co=rn&&!ln&&Gt?ms(Oe,(ot.current??"").trim()):null,uo=ln?pn.current:co;return{country:Oe,...Gt&&ot.current?{zip:ot.current}:{},...ze(X.city,Oe)&&un.current?{city:un.current}:{},...uo?{state:uo}:{},...rn&&xt.current?{addressLine1:xt.current}:{},...ze(X.address_line_2,Oe)&&tn.current?{addressLine2:tn.current}:{}}})():{}},chv:m,avsCheck:Se??!1,checkoutType:G,checkoutLayout:Y,avsConfig:X?{country:ze(X.country,_t.current),postal_code:ze(X.postal_code,_t.current),address_line_1:ze(X.address_line_1,_t.current),address_line_2:ze(X.address_line_2,_t.current),city:ze(X.city,_t.current),state:ze(X.state,_t.current)}:void 0});if(yt.ok){let Oe=yt.status===204?null:await yt.json().catch(()=>null),ln=La(I)||Oe?.status==="authorized";Vr(N),at("success"),Z(null),await new Promise(rn=>setTimeout(rn,1200)),a?.(ln?{status:"authorized",...typeof Oe?.paymentId=="string"?{paymentId:Oe.paymentId}:I?.paymentId?{paymentId:I.paymentId}:{},sessionId:typeof Oe?.sessionId=="string"?Oe.sessionId:N,...typeof Oe?.authorizationExpiresAt=="string"?{authorizationExpiresAt:Oe.authorizationExpiresAt}:I?.authorizationExpiresAt?{authorizationExpiresAt:I.authorizationExpiresAt}:{},paymentIntentId:i.threeDSecureActionResultTokenId,paymentMethodId:Re,checkoutMethod:i.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:i.threeDSecureActionResultTokenId,paymentMethodId:Re,checkoutMethod:i.isPaypal?"paypal":"card"});return}let Ke=await yt.json().catch(()=>null);if(Ke?.type==="paypal_redirect_required"){let Oe=Ke.threeDSecureToken,ln=Ke.paymentMethodId||i.id||"";if(!de||!Oe){at("error"),pe("PayPal authorization required but no token provided.");return}try{let rn=ct?.getRawProvider();if(!rn){pe("PayPal is not available.");return}let Gt={return_url:window.location.href};ln&&(Gt.payment_method=ln);let{error:co}=await rn.confirmPayment({clientSecret:Oe,confirmParams:Gt,redirect:"if_required"});if(co){at("error");let uo=co.message??"PayPal payment failed.";pe(uo),Nn("paypal",uo,{code:co.code})}}catch(rn){at("error"),pe(rn instanceof Error?rn.message:"PayPal authorization failed.")}return}if(Ke?.type==="paypal_direct_required"){let Oe=Ke.orderId;if(!Oe){at("error"),pe("PayPal retry required but no order id provided.");return}let ln=$e.current?.attempts??0;if(ln>=2){at("error"),pe("PayPal payment could not be completed after multiple attempts."),Nn("paypal","paypal_direct_required retry limit exceeded");return}ya(!1),fa("loading"),Z({orderId:Oe,attempts:ln+1}),at(null);return}nc(yt.status,Ke)||Ct(),at("error");let nn=Ke?.message??"Payment failed. Please try again.";pe(nn),Nn(i.isPaypal?"paypal":"card",nn,{code:Ke?.code??Ke?.gatewayErrorCode,declineCode:Ke?.declineCode??Ke?.gatewayDeclineReason}),await new Promise(Oe=>setTimeout(Oe,1500))}catch(mt){Es(mt)||Ct(),at("error"),pe(mt instanceof Error?mt.message:"An unexpected error occurred"),await new Promise(yt=>setTimeout(yt,1500))}finally{Mt(!1),at(null),Yt.current=!1}},[p,e,t,k,Ee,m,de,ct,I,a,c,pe,Nn,rt]),Sn=Pe((i,R)=>{S?S(i):_i(i,R)},[S,_i]),xi=Ie(!1);ht(()=>{if(typeof window>"u"||xi.current)return;let i=new URLSearchParams(window.location.search),R=i.get("payment_intent"),N=i.get("payment_intent_client_secret"),he=i.get("redirect_status");if(!R||!N)return;let z=yt=>{let Ke=localStorage.getItem(yt);if(!Ke)return null;try{return JSON.parse(Ke)}catch{return localStorage.removeItem(yt),null}},Re=z(Gn)??z(hs),Ne;if(Re?.clientSecret){if(Re.clientSecret!==N)return;Ne={...Re.accountPatch?{accountPatch:Re.accountPatch}:{},...Re.sessionId?{sessionId:Re.sessionId}:{},...Re.nonce?{nonce:Re.nonce}:{}}}else if(Re?.sessionId&&Re.sessionId!==e)return;xi.current=!0,localStorage.removeItem(Gn),localStorage.removeItem(hs);let It=new URL(window.location.href);It.searchParams.delete("payment_intent"),It.searchParams.delete("payment_intent_client_secret"),It.searchParams.delete("redirect_status"),window.history.replaceState({},"",It.toString());let Ct=Re?.paymentMethodType??Re?.tokenType??"card",mt="card";(async()=>{let yt=de?.getRawProvider();if(!yt){let Gt="Payment is not available \u2014 please refresh and try again.";pe(Gt),Nn(mt,Gt);return}if(he==="failed"){let Gt="Payment was declined. Please try again.";pe(Gt),Nn(mt,Gt);return}let{paymentIntent:Ke,error:nn}=await yt.retrievePaymentIntent(N);if(nn){let Gt=nn.message??"Failed to retrieve payment status.";pe(Gt),Nn(mt,Gt,{code:nn.code});return}let Oe=Ke?.status,ln=jo(Oe);if(!Ke||!ln){let Gt=Oe==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";pe(Gt),Nn(mt,Gt,{code:Oe??"missing_payment_intent"});return}let rn=typeof Ke.payment_method=="string"?Ke.payment_method:Ke.payment_method?.id;Sn({id:rn??Re?.paymentMethodId??Re?.tokenId??Ke.id,type:"card",threeDSecureActionResultTokenId:Ke.id,gateway:Re?.gateway??"stripe",paymentMethodType:Ct},Ne)})()},[e,Sn,de,pe,Nn]);let ga=Pe(i=>{i.preventDefault()},[]);if(!(de!==null))return l("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let io=oe==="buttons",sn=O?.variables,Qs=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),ha=sn?.colorBackground,el=ha&&!Qs.has(ha)?ha:void 0,vr=f.cardInputBorder??(io?"#e5e7eb":"#A4A4FF"),ba=sn?.colorDanger??"#dc2626",Pr=i=>lr&&i?ba:vr,Lo=(yn.malformed||yn.empty)&&(Cn||lr),tl=Lo?ba:Pr(Ut.zip),va=f.cardFormContainer?.backgroundColor??el??(io?"white":"#EDEDFF"),Cr=f.cardInputBackground??sn?.colorBackground??"white",Pa=Nr(Te),Ti=Nr(Ae),Br=f.nameInput,Ai=f.cardInputFontSize??_c(Br?.fontSize)??sn?.fontSizeBase??"16px",Mi=typeof Br?.fontFamily=="string"?Br.fontFamily:sn?.fontFamily??"Poppins, sans-serif",Bi=Oi(Br?.fontWeight)??400,nl=f.cardInputColor??(typeof Br?.color=="string"?Br.color:void 0)??sn?.colorText??"#262833",rl=f.cardInputPlaceholderColor??"#9ca3af",Pt=sn?.borderRadius??"8px",Sr=sn?.borderRadius??f.cardButton?.borderRadius??Pt,wr=sn?.colorPrimary??"#4A49FF",ol=sn?.colorPrimaryHover??po(wr,.12),so=sn?.colorText??"#262833",Fr={fontSize:Ai,fontFamily:Mi,fontWeight:Bi,color:nl,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},al={"--flopay-input-placeholder-color":rl,"--flopay-input-font-size":Ai,"--flopay-input-font-family":Mi,"--flopay-input-font-weight":String(Bi)},lo=f.cardFormContainer??{},Ca=lo.padding??(io?"0":"1rem"),Sa=lo.borderRadius??Pt,il=qe&&fn?l(wa,{capture:qe,html:fn.html,messageToken:fn.messageToken,expectedOrigin:fn.expectedOrigin,theme:pt,onReady:()=>{if(!A&&!X||typeof document>"u")return;let i=()=>{(document.querySelector('[data-testid="flopay-vault-identity-fields"]')??document.querySelector('[data-testid="flopay-avs-fields"]'))?.querySelector("input:not([disabled]), select:not([disabled])")?.focus()};i();let R=0,N=window.setInterval(()=>{R+=1;let he=document.activeElement;!!he&&he.tagName==="IFRAME"&&he.id==="flopay_vault_form_iframe"?(i(),window.clearInterval(N)):R>=50&&window.clearInterval(N)},100)},onError:i=>pe(i),onValidation:i=>{let R=E.current;(R==="idle"||R==="validation-window")&&(pe(i),i&&E.current==="validation-window"&&(_.current&&(clearTimeout(_.current),_.current=null),E.current="idle",at(null)))}}):l("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"}),Fi=ke("div",{onFocusCapture:i=>{["INPUT","SELECT","TEXTAREA","IFRAME"].includes(i.target.tagName)&&Bn()},style:{backgroundColor:va,borderRadius:Sa,...lo,padding:Ca,...al,display:"flex",flexDirection:"column"},children:[l("style",{children:`
25
+ `,Jo=44;function qa(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 vc={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"},ks={width:"100%",minHeight:Jo,margin:"0 0 0.5rem",padding:"0.75rem 0.875rem",border:"1px solid #2563eb",borderRadius:8,background:"#eff6ff",color:"#1d4ed8",fontSize:"0.95rem",fontWeight:700,cursor:"pointer"};function Pc(e){switch(e){case"paypal":return"PayPal";case"apple_pay":return"Apple Pay";case"google_pay":return"Google Pay";default:return"Card"}}function fs(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function La(e){return e==="paypal"?"PayPal":Rr(e)}function Cc(e,t){let n=`We couldn't open ${La(e)}. Try again or choose another payment method.`;return t?`${n} Allow pop-ups for this site, then try again.`:n}function Is(e){let t=we(0),n=we(null),r=we(null),o=be((m=r.current)=>{let w=m;w?.timer&&(clearTimeout(w.timer),w.timer=null)},[]),a=be((m,w)=>{typeof document<"u"&&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"}))},w))},[o,e]),d=be(m=>{m.yieldedControl&&a(m,600)},[a]),l=be(m=>{o();let w=t.current+1;t.current=w,n.current=null;let ge={generation:w,method:m,timer:null,yieldedControl:!1};return r.current=ge,w},[o]),S=be(m=>{let w=r.current;return typeof m=="number"&&w?.generation!==m?!1:(o(w),r.current=null,(typeof m!="number"||n.current===m)&&(n.current=null),!0)},[o]),g=be(m=>{let w=r.current,ge=m??w?.generation??t.current;(!m||w?.generation===m)&&(o(w),r.current=null),n.current=ge},[o]),h=be(m=>n.current===(m??t.current),[]),v=be(m=>r.current?.generation===m&&n.current!==m,[]),A=be(()=>{let m=r.current;m&&d(m)},[d]),F=be(()=>{let m=r.current;m&&(m.yieldedControl=!0,o(m))},[o]);return ut(()=>{let m=()=>{document.visibilityState==="visible"?A():F()},w=()=>{F()};return document.addEventListener("visibilitychange",m),window.addEventListener("blur",w),window.addEventListener("focus",A),()=>{document.removeEventListener("visibilitychange",m),window.removeEventListener("blur",w),window.removeEventListener("focus",A),o()}},[o,F,A]),{startAttempt:l,finishAttempt:S,invalidateAttempt:g,isAttemptInvalidated:h,isAttemptCurrent:v}}function Sc(e){let t=tc(e);return`Enter a valid ${Da(e)}${t?` (e.g. ${t})`:""}`}function wc(e,t,n){let r=oc(e),o=t.trim(),a=n&&r,d=a&&!o,l=a&&!!o&&!ic(e,o);return{visible:n,supported:r,required:a,empty:d,malformed:l}}function kc(e,t){let n=e.trim(),r=t&&!n,o=t&&!!n&&!Kt(n);return{required:t,empty:r,malformed:o,value:n}}function gs(e,t){return t instanceof An?t:new An(t instanceof Error?t.message:`${Pc(e)} before-click hook failed.`,"validation_error")}function Fa(){return u("style",{children:bc})}function Ic(e){return typeof e=="number"?`${e}px`:e}function Rs(e,t){let n=e.availablePaymentMethods;return n&&t.some(r=>n[r])?"ready":"unavailable"}function Es({state:e,placeholderTestId:t,borderRadius:n=8,children:r}){return e==="unavailable"||e==="load_error"?null:De("div",{style:{position:"relative",minHeight:44},children:[u("div",{"data-testid":t,"aria-hidden":e==="ready",style:{position:"absolute",inset:0,height:44,borderRadius:n,background:"#e5e7eb",animation:e==="ready"?void 0:"flopay-pulse 1.5s ease-in-out infinite",opacity:e==="ready"?0:1,transform:e==="ready"?"scale(0.985)":"scale(1)",transition:"opacity 140ms ease-out, transform 140ms ease-out",pointerEvents:"none"}}),u("div",{style:{minHeight:44,opacity:e==="ready"?1:0,transform:e==="ready"?"translateY(0)":"translateY(2px)",transition:"opacity 140ms ease-out, transform 140ms ease-out",pointerEvents:e==="ready"?"auto":"none"},children:r})]})}function hs(e){return e!=="unavailable"&&e!=="load_error"}function $a(e){return u(Ec,{...e})}function bs({sessionId:e,nonce:t,email:n,billingApiUrl:r,onTokenizedBody:o,onErrorChange:a,isProcessing:d=!1,onButtonClick:l,onDecline:S,onTechnicalFailure:g,runBeforeButtonClick:h,billingName:v,onBuyerIdentityReady:A,onLoadStateChange:F,placeholderBorderRadius:m}){let w=cr(),{emitInstrument:ge}=Yr(In),V=za(),C=Oa(),[pe,ne]=me("loading");ut(()=>{F?.(pe)},[pe,F]);let[ce,de]=me(!1),ve=!Kt(n?.trim())||!v?.trim(),{request:Ve,collect:fe,finish:kt}=Or(),Le=we(!1),Ie=we(null),Re=we(null),[re,oe]=me(0),[D,_e]=me(!1),xe=we(!1),Te=we(new Map),{startAttempt:Ne,finishAttempt:Pe,invalidateAttempt:B,isAttemptInvalidated:se,isAttemptCurrent:Ae}=Is((Y,j,q)=>{g?.(Y,j,{...q,popupBlocked:q?.popupBlocked??lr(j)}),_e(!0),oe(Ce=>Ce+1)});ut(()=>{D&&Re.current?.focus()},[D,re]);let le=be(()=>{oe(Y=>Y+1)},[]),H=be((Y,j,q)=>{B(q),g?.("paypal",Y,{code:j,popupBlocked:lr(Y)}),_e(!0),le()},[B,g,le]),ke=be(()=>{window.setTimeout(()=>{(Ie.current?.querySelector("iframe")??Ie.current)?.focus()},0)},[]);ut(()=>{xe.current&&(xe.current=!1,ke())},[ke,re]);let We=be(()=>{_e(!1),a?.(null),ke()},[ke,a]);ut(()=>{if(!V||Le.current)return;let Y=new URLSearchParams(window.location.search),j=Y.get("payment_intent"),q=Y.get("payment_intent_client_secret"),Ce=Y.get("redirect_status");if(!j||!q)return;Le.current=!0;let qe;try{let G=localStorage.getItem(bo);if(G){let _=JSON.parse(G);_.clientSecret===q&&(qe={..._.accountPatch?{accountPatch:_.accountPatch}:{},..._.sessionId?{sessionId:_.sessionId}:{},..._.nonce?{nonce:_.nonce}:{}})}}catch{}try{localStorage.removeItem(bo)}catch{}let R=new URL(window.location.href);R.searchParams.delete("payment_intent"),R.searchParams.delete("payment_intent_client_secret"),R.searchParams.delete("redirect_status"),window.history.replaceState({},"",R.toString()),(async()=>{try{if(de(!0),Ce==="failed"){let P="PayPal payment was declined. Please try again.";a?.(P),S?.(Ft("paypal",P));return}let{paymentIntent:G,error:_}=await V.retrievePaymentIntent(q);if(_){a?.(_.message??"Failed to retrieve PayPal payment status.");return}if(G&&(G.status==="requires_capture"||G.status==="succeeded")){let P=typeof G.payment_method=="string"?G.payment_method:G.payment_method?.id;o({id:P??G.id,type:"card",threeDSecureActionResultTokenId:G.id,isPaypal:!0},qe)}else{let P="PayPal payment was not completed. Please try again.";a?.(P),S?.(Ft("paypal",P))}}catch(G){a?.(G instanceof Error?G.message:"Failed to complete PayPal payment.")}finally{de(!1)}})()},[V,o,a,S]);let nt=be(async Y=>{if(d||ce){Y.reject();return}let j=h?await h("paypal"):{proceed:!0};if(!j.proceed){Te.current.delete(re),Y.reject();return}let q=Ne("paypal");Te.current.set(re,{generation:q,accountPatch:j.accountPatch,sessionId:j.sessionId,nonce:j.nonce}),_e(!1),l?.("paypal"),Y.resolve()},[Te,d,l,h,Ne,ce,re]),Be=be(async Y=>{if(!V||!C)return;let j=Te.current.get(re);if(j&&!Ae(j.generation)){Te.current.delete(re);return}if(!j&&se()||j&&!Pe(j.generation))return;j||Pe();let q=j??null;if(Te.current.delete(re),!q&&h){let P=await h("paypal");if(!P.proceed){Y.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}q={accountPatch:P.accountPatch,sessionId:P.sessionId,nonce:P.nonce}}let Ce=q?.sessionId??e,qe=q?.nonce??t,R=await ws({event:Y,prepared:q,email:n,billingName:v,methodLabel:"PayPal",collect:fe});if(!R){Y.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let G=R.email,_=sn({...q?.accountPatch,...R});try{if(de(!0),a?.(null),!Ce||!Kt(G))throw new Error("Missing sessionId or email for PayPal payment");await A?.(R);let P=V.createPaymentMethod,{error:Ze,paymentMethod:pt}=await P({type:"paypal"});if(Ze){H(Ze,"stripe_paypal_create_payment_method_failed",j?.generation),Y.paymentFailed({reason:"fail"});return}let J=await Xo(r,ge,Ce,qe??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:pt?.id??null,intentKind:"payment"});if(J.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let Qe=J.clientSecret,Ke={return_url:window.location.href};if(pt?.id&&(Ke.payment_method=pt.id),typeof window<"u")try{localStorage.setItem(bo,JSON.stringify({clientSecret:Qe,sessionId:Ce,nonce:qe,accountPatch:_}))}catch{}let{error:mt,paymentIntent:vt}=await V.confirmPayment({clientSecret:Qe,confirmParams:Ke,redirect:"if_required"});if(mt){if(typeof window<"u")try{localStorage.removeItem(bo)}catch{}if(mo(mt)){let W=mt.message??"Your payment was declined.";a?.(W),S?.(Ft("paypal",W,{code:Zn(mt),declineCode:Ur(mt)})),await Zo({billingApiUrl:r,sessionId:Ce,nonce:qe,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:Zn(mt)??"provider_declined"}})}else H(mt,"stripe_paypal_confirm_failed",j?.generation);return}if(typeof window<"u")try{localStorage.removeItem(bo)}catch{}let b=typeof vt?.payment_method=="string"?vt.payment_method:vt?.payment_method?.id;o({id:b??vt?.id,type:"card",threeDSecureActionResultTokenId:vt?.id,isPaypal:!0},{accountPatch:_,sessionId:Ce,nonce:qe});return}catch(P){H(P,"stripe_paypal_failed",j?.generation)}finally{de(!1)}},[V,C,e,t,n,v,fe,A,r,ge,o,a,S,h,H,Pe,Ae,se,re]);return De(Hr,{children:[u(Es,{state:pe,placeholderTestId:"flopay-paypal-placeholder",borderRadius:m,children:De("div",{ref:Ie,tabIndex:-1,"data-testid":"flopay-paypal-focus-target",role:"group","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[D&&u("button",{ref:Re,type:"button","data-testid":"flopay-paypal-retry-button",onClick:We,style:ks,children:"Try PayPal again"}),Ve&&u(zr,{identity:Ve.identity,methodLabel:Ve.methodLabel,onComplete:kt,onCancel:()=>kt(null)},Ve.id),u("div",{style:{display:Ve?"none":void 0},children:u(Cs,{onReady:Y=>ne(Rs(Y,["paypal"])),onLoadError:()=>{ne("load_error"),Ua(Dt(w),"paypal","paypal")},onClick:nt,onConfirm:Be,onCancel:()=>{let Y=Te.current.get(re);Te.current.delete(re),Dt(w)?.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),B(Y?.generation),_e(!1),xe.current=!0,le()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:ve,emailRequired:ve,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},re)})]})}),ce&&u(qn,{status:"processing"})]})}function vs({sessionId:e,nonce:t,email:n,billingApiUrl:r,intentKind:o,expressMethods:a,onTokenizedBody:d,onErrorChange:l,onButtonClick:S,onDecline:g,onTechnicalFailure:h,runBeforeButtonClick:v,billingName:A,onBuyerIdentityReady:F,onLoadStateChange:m,placeholderBorderRadius:w}){let ge=cr(),{emitInstrument:V}=Yr(In),C=za(),pe=Oa(),[ne,ce]=me("loading");ut(()=>{m?.(ne)},[ne,m]);let[de,ve]=me(!1),Ve=!Kt(n?.trim())||!A?.trim(),{request:fe,collect:kt,finish:Le}=Or(),Ie=we(null),Re=we(null),[re,oe]=me(0),[D,_e]=me(!1),[xe,Te]=me("google_pay"),Ne=we(!1),Pe=we("google_pay"),B=we("google_pay"),se=we(new Map),{startAttempt:Ae,finishAttempt:le,invalidateAttempt:H,isAttemptInvalidated:ke,isAttemptCurrent:We}=Is((R,G,_)=>{h?.(R,G,{..._,popupBlocked:_?.popupBlocked??lr(G)}),Te(R),_e(!0),oe(P=>P+1)});ut(()=>{D&&Re.current?.focus()},[D,re]);let nt=be(()=>{oe(R=>R+1)},[]),Be=be((R,G,_,P)=>{H(P),h?.(R,G,{code:_,popupBlocked:lr(G)}),Te(R),_e(!0),nt()},[H,h,nt]),Y=be(()=>{window.setTimeout(()=>{(Ie.current?.querySelector("iframe")??Ie.current)?.focus()},0)},[]);ut(()=>{Ne.current&&(Ne.current=!1,Y())},[Y,re]);let j=be(()=>{_e(!1),l?.(null),Y()},[Y,l]),q=be(async R=>{if(!C||!pe)return;let G=se.current.get(re);if(G&&!We(G.generation)){se.current.delete(re);return}if(!G&&ke()||G&&!le(G.generation))return;G||le();let _=R.expressPaymentType??G?.method??Pe.current,P=G??null;se.current.delete(re);let Ze=fs(_);if(!P&&v){let b=await v(Ze);if(!b.proceed){R.paymentFailed({reason:"fail",message:"Wallet checkout was cancelled."});return}P={accountPatch:b.accountPatch,sessionId:b.sessionId,nonce:b.nonce}}let pt=Ze,J=P?.sessionId??e,Qe=P?.nonce??t,Ke=await ws({event:R,prepared:P,email:n,billingName:A,methodLabel:La(_),collect:kt});if(!Ke){R.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let mt=Ke.email,vt=sn({...P?.accountPatch,...Ke});try{if(ve(!0),l?.(null),!Kt(mt))throw new Error("Missing sessionId or email for wallet payment");await F?.(Ke);let{error:b}=await pe.submit();if(b){Be(_,b,"stripe_wallet_submit_failed",G?.generation);return}let{error:W,paymentMethod:X}=await C.createPaymentMethod({elements:pe});if(W||!X){Be(_,W??new Error("Failed to create payment method."),"stripe_wallet_create_payment_method_failed",G?.generation);return}if(!J)throw new Error("Missing sessionId or email for wallet payment");let rt=await Xo(r,V,J,Qe??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:_??Ze,paymentMethodId:X.id,intentKind:o});if(rt.provider!=="stripe")throw new Error("Invalid provider returned for wallet intent");let _t=rt.clientSecret,{error:ht,intentId:He}=ac(_t)?await C.confirmCardSetup(_t,{payment_method:X.id}).then($e=>({error:$e.error,intentId:$e.setupIntent?.id})):await C.confirmCardPayment(_t,{payment_method:X.id}).then($e=>({error:$e.error,intentId:$e.paymentIntent?.id}));if(ht){if(mo(ht)){let $e=ht.message??"Your payment was declined.";l?.($e),g?.(Ft(pt,$e,{code:Zn(ht),declineCode:Ur(ht)})),await Zo({billingApiUrl:r,sessionId:J,nonce:Qe,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:_??Ze,providerDeclineReason:Zn(ht)??"provider_declined"}})}else Be(_,ht,"stripe_wallet_confirm_failed",G?.generation);return}d({id:X.id,type:"card",threeDSecureActionResultTokenId:He},{accountPatch:vt,sessionId:J,nonce:Qe})}catch(b){Be(_,b,"stripe_wallet_failed",G?.generation)}finally{ve(!1)}},[C,pe,e,t,n,A,kt,F,r,V,o,d,l,g,v,Be,le,We,ke,re]),Ce=st(()=>{let R=["applePay","googlePay","paypal","link","amazonPay","klarna"],G=new Set(["applePay","googlePay"]),_=new Set(a.map(ps)),P={};for(let Ze of R)_.has(Ze)?P[Ze]=G.has(Ze)?"always":"auto":P[Ze]="never";return P},[a]),qe=st(()=>a.map(ps),[a]);return De(Hr,{children:[u(Es,{state:ne,placeholderTestId:"flopay-wallet-placeholder",borderRadius:w,children:De("div",{ref:Ie,tabIndex:-1,"data-testid":"flopay-wallet-focus-target",role:"group","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[D&&De("button",{ref:Re,type:"button","data-testid":"flopay-wallet-retry-button",onClick:j,style:ks,children:["Try ",La(xe)," again"]}),fe&&u(zr,{identity:fe.identity,methodLabel:fe.methodLabel,onComplete:Le,onCancel:()=>Le(null)},fe.id),u("div",{style:{display:fe?"none":void 0},children:u(Cs,{onReady:R=>{ce(Rs(R,qe))},onLoadError:R=>{ce("load_error"),Ua(Dt(ge),"stripe","wallet")},onClick:async R=>{Pe.current=R.expressPaymentType,B.current=fs(R.expressPaymentType);let G=v?await v(B.current):{proceed:!0};if(!G.proceed){se.current.delete(re),R.reject();return}let _=Ae(R.expressPaymentType);se.current.set(re,{generation:_,method:R.expressPaymentType,accountPatch:G.accountPatch,sessionId:G.sessionId,nonce:G.nonce}),_e(!1),S?.(B.current),R.resolve()},onConfirm:q,onCancel:()=>{let R=se.current.get(re);se.current.delete(re),Dt(ge)?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet"}),H(R?.generation),_e(!1),Ne.current=!0,nt()},options:{buttonType:{applePay:"plain",googlePay:"plain"},paymentMethods:Ce,emailRequired:Ve,billingAddressRequired:Ve,layout:{maxColumns:1,overflow:"never"}}},re)})]})}),de&&u(qn,{status:"processing"})]})}function Rc({method:e,themeId:t,submitting:n=!1,disabled:r=!1,highlighted:o=!1,hasNextStep:a=!1,onClick:d,backgroundColor:l,borderColor:S,textColor:g,borderRadius:h,fontFamily:v}){let A=uc(e,t),F=ls[e],[m,w]=me(!1),ge=A?.backgroundColor??l??"#ffffff",V=A?.borderColor??S??"#d1d5db",C=A?.textColor??g??"#262833";return u("button",{type:"button","data-testid":`flopay-stripe-method-button-${e}`,"data-method":e,onClick:()=>{!n&&!r&&d()},disabled:n||r,"aria-busy":n||void 0,style:{position:"relative",width:"100%",boxSizing:"border-box",height:Jo,padding:"0 1rem",backgroundColor:ge,color:C,border:`1px solid ${V}`,borderRadius:h??8,fontSize:"0.95rem",fontWeight:600,fontFamily:v,cursor:n||r?"not-allowed":"pointer",opacity:r&&!n?.55:1,animation:n?"flopay-pulse 1.5s ease-in-out infinite":void 0,display:"flex",alignItems:"center",justifyContent:"center",gap:8,transition:"transform 0.1s, opacity 140ms ease-out, border-color 140ms ease-out",boxShadow:o?"0 0 0 2px rgba(74, 73, 255, 0.15)":void 0},children:n?u("span",{style:{margin:"0 auto"},children:`Connecting to ${Rr(e)}\u2026`}):De(Hr,{children:[De("span",{style:{display:"inline-flex",alignItems:"center",gap:rc(e)?8:0},children:[F&&!m?u("img",{src:F,alt:"","aria-hidden":"true",onError:()=>w(!0),loading:"lazy",decoding:"async",width:30,height:20,style:{width:30,height:20,flexShrink:0,borderRadius:3,objectFit:"contain",display:"inline-flex"}}):A?.logoSvg?u("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:A.logoSvg}}):null,u("span",{children:Rr(e)})]}),a&&u("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:C,strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{position:"absolute",right:"1rem",top:"50%",transform:"translateY(-50%)",flexShrink:0,opacity:.7},"aria-hidden":"true",children:u("path",{d:"M9 18l6-6-6-6"})})]})})}function Na({method:e,sessionId:t,nonce:n,email:r,billingName:o,onBuyerIdentityReady:a,billingApiUrl:d,onTokenizedBody:l,onErrorChange:S,onDecline:g,onCancel:h,runBeforeButtonClick:v,onButtonClick:A,isProcessing:F,submitButtonColor:m,submitButtonBorderRadius:w,submitButtonStyle:ge,errorText:V}){let C=cr(),{emitInstrument:pe}=Yr(In),ne=za(),ce=Oa(),[de,ve]=me(!1),Ve=we(!1),[fe,kt]=me(!1),[Le,Ie]=me("loading"),[Re,re]=me(""),oe=!Kt(r?.trim()),D=!oe||Kt(Re.trim()),_e=be(async()=>{if(!ne||!ce||F||Ve.current||!fe)return;Ve.current=!0,ve(!0);let xe=v?await v("card"):{proceed:!0};if(!xe.proceed){Ve.current=!1,ve(!1);return}A?.("card");let Te=xe.sessionId??t,Ne=xe.nonce??n,Pe=vr(o?.trim()),B=sn({email:xe.accountPatch?.email?.trim()||r?.trim()||Re.trim(),firstName:xe.accountPatch?.firstName?.trim()||Pe.firstName,lastName:xe.accountPatch?.lastName?.trim()||Pe.lastName}),se=B.email,Ae=sn({...xe.accountPatch,...B});try{if(S?.(null),!Kt(se))throw new Error("A valid email address is required for payment.");await a?.(B);let le=await ce.submit();if(le.error){S?.(le.error.message??"Payment failed.");return}let H=[B.firstName,B.lastName].filter(Boolean).join(" "),ke=await ne.createPaymentMethod({elements:ce,params:{billing_details:{email:se,...H?{name:H}:{}}}});if(ke.error||!ke.paymentMethod){S?.(ke.error?.message??"Failed to create payment method.");return}let We=ke.paymentMethod;if(!Te||!se)throw new Error("Missing sessionId or email for payment.");let nt=We.type||e,Be=await Xo(d,pe,Te,Ne??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:nt,paymentMethodId:null,intentKind:"payment"});if(Be.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Y=Be.clientSecret;if(typeof window<"u")try{localStorage.setItem($n,JSON.stringify({clientSecret:Y,sessionId:Te,nonce:Ne,accountPatch:Ae,paymentMethodId:We.id,paymentMethodType:We.type??e,gateway:"stripe"}))}catch{}let{error:j,paymentIntent:q}=await ne.confirmPayment({clientSecret:Y,confirmParams:{return_url:window.location.href,payment_method:We.id},redirect:"if_required"});if(j){if(typeof window<"u")try{localStorage.removeItem($n)}catch{}let R=j.message??"Payment failed.";S?.(R),g?.(Ft("card",R,{code:j.code})),await Zo({billingApiUrl:d,sessionId:Te,nonce:Ne,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:j.code??"provider_declined"}});return}let Ce=q?.status;if(!Lo(Ce)){if(typeof window<"u")try{localStorage.removeItem($n)}catch{}let R=Ce==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";S?.(R),g?.(Ft("card",R,{code:Ce??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem($n)}catch{}let qe=typeof q?.payment_method=="string"?q.payment_method:q?.payment_method?.id;l({id:qe??We.id,type:"card",threeDSecureActionResultTokenId:q?.id,gateway:"stripe",paymentMethodType:We.type??e},{accountPatch:Ae,sessionId:Te,nonce:Ne})}catch(le){S?.(le instanceof Error?le.message:"Payment failed. Please try again.")}finally{Ve.current=!1,ve(!1)}},[ne,ce,F,fe,v,A,t,n,r,o,Re,a,d,pe,e,l,S,g]);return De("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[oe&&u("div",{"data-testid":"flopay-apm-identity-fields",style:{display:"flex",flexDirection:"column",gap:"0.75rem",marginBottom:"0.75rem"},children:oe&&De("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",u("input",{type:"email",autoComplete:"email",required:!0,value:Re,onChange:xe=>re(xe.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]})}),u(mc,{onReady:()=>Ie("ready"),onLoadError:()=>{Ie("load_error"),Ua(Dt(C),"stripe","apm")},onChange:xe=>{kt(!!xe.complete)},options:{layout:{type:"accordion",defaultCollapsed:!1,radios:"never"},fields:{billingDetails:{email:"never"}},defaultValues:{billingDetails:{...o?.trim()?{name:o.trim()}:{},...Kt(r?.trim())?{email:r?.trim()}:{}}}}}),u("button",{type:"button","data-testid":`flopay-stripe-method-pay-${e}`,onClick:()=>{_e()},disabled:!fe||!D||de||F||Le!=="ready",style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:m,color:"white",border:"none",borderRadius:w,fontSize:"1rem",fontWeight:600,cursor:!fe||!D||de||F||Le!=="ready"?"not-allowed":"pointer",opacity:!fe||!D||de||F||Le!=="ready"?.5:1,transition:"opacity 120ms ease-out",...ge??{}},children:de?"Processing\u2026":`Pay with ${Rr(e)}`}),V&&u($r,{margin:"0.75rem 0 0",children:V})]})}function Ps({sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:a,paymentElementMethods:d,stripeInstance:l,paymentElementBaseOptions:S,onTokenizedBody:g,onErrorChange:h,onButtonClick:v,onDecline:A,runBeforeButtonClick:F,onLoadStateChange:m,isProcessing:w=!1,submitButtonColor:ge="#4A49FF",submitButtonBorderRadius:V=8,submitButtonStyle:C,buttonAppearance:pe,themeId:ne,onExpandApm:ce,expandedApmMethod:de}){let{emitInstrument:ve}=Yr(In),[Ve,fe]=me(null),[kt,Le]=me(null),Ie=we(!1),{request:Re,collect:re,finish:oe}=Or();ut(()=>{d.length>0&&l?m?.("ready"):l||m?.("loading")},[d.length,l,m]);let D=be(async B=>{if(!l||Ie.current||w)return;Ie.current=!0,Le(B);let se=F?await F("card"):{proceed:!0};if(!se.proceed){Ie.current=!1,Le(null);return}v?.("card");let Ae=se.sessionId??e,le=se.nonce??t,H=vr([se.accountPatch?.firstName,se.accountPatch?.lastName].filter(Boolean).join(" ")||r),ke=sn({email:se.accountPatch?.email?.trim()||n?.trim(),firstName:se.accountPatch?.firstName?.trim()||H.firstName,lastName:se.accountPatch?.lastName?.trim()||H.lastName});if(!Kt(ke.email)){Le(null);let Be=await re(Rr(B),ke);if(!Be){Ie.current=!1;return}ke=Be,Le(B)}let We=ke.email,nt=sn({...se.accountPatch,...ke});try{if(h?.(null),!Ae||!Kt(We))throw new Error("Missing sessionId or email for payment.");await o?.(ke);let Be=await Xo(a,ve,Ae,le??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:B,paymentMethodId:null,intentKind:"payment"});if(Be.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Y=Be.clientSecret;if(typeof window<"u")try{localStorage.setItem($n,JSON.stringify({clientSecret:Y,sessionId:Ae,nonce:le,accountPatch:nt,paymentMethodType:B,gateway:"stripe"}))}catch{}let{error:j,paymentIntent:q}=await l.confirmPayment({clientSecret:Y,confirmParams:{return_url:window.location.href,payment_method_data:{type:B,billing_details:{name:[ke.firstName,ke.lastName].filter(Boolean).join(" "),...We?{email:We}:{}}}},redirect:"if_required"});if(j){if(typeof window<"u")try{localStorage.removeItem($n)}catch{}let R=j.message??"Payment failed.";h?.(R),A?.(Ft("card",R,{code:j.code})),await Zo({billingApiUrl:a,sessionId:Ae,nonce:le,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:B,providerDeclineReason:j.code??"provider_declined"}});return}let Ce=q?.status;if(!Lo(Ce)){if(typeof window<"u")try{localStorage.removeItem($n)}catch{}let R=Ce==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";h?.(R),A?.(Ft("card",R,{code:Ce??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem($n)}catch{}let qe=typeof q?.payment_method=="string"?q.payment_method:q?.payment_method?.id;g({id:qe??q?.id,type:"card",threeDSecureActionResultTokenId:q?.id,gateway:"stripe",paymentMethodType:B},{accountPatch:nt,sessionId:Ae,nonce:le})}catch(Be){h?.(Be instanceof Error?Be.message:"Payment failed. Please try again.")}finally{Ie.current=!1,Le(null)}},[l,w,F,v,e,t,n,re,a,ve,r,o,g,h,A]),[_e,xe]=me(null),Te=ce?de??null:_e,Ne=be(B=>{Ie.current||w||Te&&Te!==B||(us(B)?ce?ce(B):xe(B):D(B))},[Te,w,D,ce]),Pe=st(()=>_e?{...S,paymentMethodTypes:[_e]}:null,[_e,S]);return u("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:Re?u(zr,{identity:Re.identity,methodLabel:Re.methodLabel,onComplete:oe,onCancel:()=>oe(null)},Re.id):d.map(B=>{let se=de===B,Ae=kt===B,le=kt!==null&&kt!==B||de!=null&&de!==B;return De(yc.Fragment,{children:[u(Rc,{method:B,themeId:ne,submitting:Ae,disabled:le,highlighted:se,hasNextStep:us(B),onClick:()=>Ne(B),backgroundColor:pe?.backgroundColor,borderColor:pe?.borderColor,textColor:pe?.textColor,borderRadius:pe?.borderRadius,fontFamily:pe?.fontFamily}),!ce&&_e===B&&Pe&&l&&u(Ir,{stripe:l,options:Pe,children:u(Na,{method:B,sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:a,onTokenizedBody:g,onErrorChange:h,onDecline:A,onCancel:()=>xe(null),runBeforeButtonClick:F,onButtonClick:v,isProcessing:w,submitButtonColor:ge,submitButtonBorderRadius:V,submitButtonStyle:C})},B)]},B)})})}function Ec({sessionId:e,nonce:t,billingApiUrl:n,email:r,userId:o,onComplete:a,onError:d,onDecline:l,onTokenizedBody:S,firstName:g,lastName:h,chv:v,className:A,isProcessing:F,error:m,onErrorChange:w,showPayPal:ge=!0,showStripe:V=!0,enabledPaymentMethods:C,enabledPaymentMethodCountries:pe,showApplePay:ne=!0,showGooglePay:ce=!0,layout:de="default",theme:ve,buttonsTheme:Ve,buttonsStyles:fe,appearance:kt,cardButtonContent:Le,cardBackButtonContent:Ie,cardTitleContent:Re,showSecurityFooter:re,onButtonClick:oe,onBeforeButtonClick:D,onBuyerIdentityReady:_e,enableAVS:xe,cardFieldOrder:Te,cardPreFormSlot:Ne,avsLayout:Pe="row",country:B,zip:se,addressLine1:Ae,addressLine2:le,city:H,state:ke,onCountryChange:We,onZipChange:nt,avsCheck:Be,checkoutType:Y,checkoutLayout:j,totalAmount:q=0,currency:Ce="usd",initialCardOpen:qe=!1,directPaypal:R,isSubscription:G=!1,session:_,dataAttachmentPending:P=!1,dataAttachmentRequiresIdentity:Ze=!1,debug:pt=!1}){let J=cr(),Qe=wa(),Ke=Yr(Bn),{emitInstrument:mt}=Yr(In),vt=P||Ke.claimPending===!0,b=Ze||Ke.claimRequiresIdentity===!0,W=vt&&!b,X=Hi(),[rt,_t]=me(!1),[ht,He]=me(null),[$e,Vt]=me(B??"US"),[Ot,xt]=me(se??""),[mn,En]=me(Ae??""),[Mn,en]=me(le??""),[_n,Gt]=me(H??""),[et,yn]=me(ke??""),[Oe,Fn]=me(""),[ot,nr]=me({}),zt=we(se??""),Ht=we(B??"US"),fn=we(Ae??""),ln=we(le??""),gn=we(H??""),Bt=we(ke??""),rr=we(""),Ut=we({});ut(()=>{let i=(I,z,ye,U,Se)=>{if(Ut.current[I])return;let Fe=z?.trim();!Fe||Fe===ye.current||(ye.current=Fe,U(Fe),Se?.(Fe))};i("country",B,Ht,Vt,We),i("zip",se,zt,xt,nt),i("addressLine1",Ae,fn,En),i("addressLine2",le,ln,en),i("city",H,gn,Gt),i("state",ke,Bt,yn)},[B,se,Ae,le,H,ke,We,nt]);let Q=st(()=>cc(xe),[xe]),or=Q!==null,hn=st(()=>Aa(_),[_]),tn=!!_?.vault?.html,Dn=!!_?.gateways?.pcivault,Hn=!!(_?.gateways?.stripe?.enabledPaymentMethods??C)?.includes("card"),vn=tn||Hn||Dn,f=!!(V&&vn&&J&&e),[yt,Yt]=me(()=>de!=="buttons"||qe?e??null:null),[Yn,Me]=me(0),Pt=de!=="buttons"||qe||!!e&&yt===e,lt=st(()=>!J||!f||!e||!Pt?null:J.cardCapture({sessionId:e,captureMethod:_?.captureMethod}),[J,f,e,Pt,_?.captureMethod]),Wt=st(()=>{let i=$e,I=Q?Ue(Q.postal_code,i):!1;return wc(i,Ot,I)},[Q,$e,Ot]),{avsInvalid:Gn,invalidAvsFields:nn}=st(()=>{let i={line1:!1,city:!1,state:!1,zip:!1};if(!f||!Q)return{avsInvalid:!1,invalidAvsFields:i};let I=$e,z=(Se,Fe)=>Ue(Se,I)&&!Fe.trim(),ye={line1:z(Q.address_line_1,mn),city:z(Q.city,_n),state:z(Q.state,et),zip:Wt.empty||Wt.malformed};return{avsInvalid:ye.line1||ye.city||ye.state||ye.zip,invalidAvsFields:ye}},[f,Q,$e,mn,_n,et,Wt]),[ar,yr]=me(!1),[Pn,Wn]=me(!1),[cn,At]=me(()=>Ma(_?.vault)),[ae,It]=me(qe&&vn?"card":"buttons"),[bt,Jt]=me(null),dn=ae==="expanding"||ae==="card",Jn=_?.gateways?.stripe?"stripe":void 0,ir=be(()=>{mt?.({class:"card_surface",provider:Jn})},[Jn,mt]),Xt=280,rn=we(null),on=be(i=>{rn.current&&clearTimeout(rn.current),rn.current=setTimeout(()=>{rn.current=null,i()},Xt)},[Xt]);ut(()=>()=>{rn.current&&clearTimeout(rn.current)},[]);let fr=be(()=>{ir(),Yt(e??null),Me(i=>i+1),It("expanding"),on(()=>It("card"))},[on,ir,e]),Xn=be(()=>{It("collapsing"),on(()=>It("buttons"))},[on]),Ln=be(i=>{Jt(i),It("apm-expanding"),on(()=>It("apm-form"))},[on]),Cn=be(()=>{It("apm-collapsing"),on(()=>{It("buttons"),Jt(null)})},[on]);ut(()=>{de==="buttons"&&qe&&vn&&(Yt(e??null),It("card"))},[de,qe,vn,e]);let[un,Xe]=me(null),pn=we(!1),Tt=we(null),Rt=we("idle"),[Ct,M]=me(null),N=we(Ct);ut(()=>{N.current=Ct},[Ct]);let T=n||X,Z=we(null),ze=st(()=>{if(_e||Ke.claimBuyerIdentity||_?.buyerIdentified!==!1||!e||!t)return;let i=`${T}|${e}|${t}`;Z.current?.key!==i&&(Z.current={key:i,claim:Lr(new Vr(T,{telemetry:!1}),e,t,{...o?{userId:o}:{},...g?{firstName:g}:{},...h?{lastName:h}:{}})});let I=Z.current.claim;return async z=>{await I(z)}},[_e,Ke.claimBuyerIdentity,_?.buyerIdentified,e,t,T,o,g,h]),y=_e??Ke.claimBuyerIdentity??ze,s=m??ht,c=st(()=>pc(ve),[ve]),p=st(()=>{let i=c?.buttonsLayout??dc(Ve);return fe?{...i,...fe,cardButton:{...i.cardButton,...fe.cardButton},cardFormContainer:{...i.cardFormContainer,...fe.cardFormContainer},backButton:{...i.backButton,...fe.backButton},backButtonIcon:{...i.backButtonIcon,...fe.backButtonIcon},submitButton:{...i.submitButton,...fe.submitButton},title:{...i.title,...fe.title}}:i},[c,Ve,fe]),x=kt??c?.appearance,ie=st(()=>Fi({appearance:x,buttonsStyles:p,layout:de}),[x,p,de]),Je=Ke.inlineSessionPatchProcessing??!1,L=(F??rt)||Je,$=T.replace(/\/+$/,""),k=st(()=>Sa({userId:o,email:r,firstName:g,lastName:h,country:B,zip:se},ot),[o,r,g,h,B,se,ot]),O=[k.firstName,k.lastName].filter(i=>!!i?.trim()).join(" "),E=!Kt(k.email?.trim()),K=we(null);f&&K.current===null&&(K.current=E);let he=f&&(K.current??E),ee=st(()=>kc(Oe,he),[Oe,he]),Ee=ee.empty||ee.malformed,Mt=st(()=>J?J.getRawProvider():null,[J]),Nn=st(()=>Qe?Qe.getRawProvider():null,[Qe]),ft=q||100,qt=st(()=>x?Xl(x):null,[x]),On=qt?{appearance:qt}:null,ri=st(()=>{let i=qt??{},I=i.rules??{};return{...i,rules:{...I,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...I[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...I[".AccordionItemContents"]??{}}}}},[qt]),oi=st(()=>{let i=Ui(q);return{...i,currency:Ce.toLowerCase(),paymentMethodCreation:"manual",...i.mode==="payment"?{captureMethod:"manual"}:{},...On}},[q,Ce,On]),ai=st(()=>({mode:"payment",amount:ft,currency:Ce.toLowerCase(),captureMethod:"manual",setupFutureUsage:"off_session",...On}),[ft,Ce,On]),ue=be(i=>{He(i),w?.(i)},[w]),ra=we(""),[ii,Os]=me(!1),oa=be(()=>{Os(!0)},[]);ut(()=>{if(!f||!he||!y||!ii||Ee||ra.current)return;let i=sn({email:Kt(k.email?.trim())?k.email?.trim():rr.current.trim(),firstName:k.firstName?.trim(),lastName:k.lastName?.trim()});ra.current=JSON.stringify(i),nr(I=>({...I,...i})),Promise.resolve(y(i)).catch(I=>{ra.current="",ue(I instanceof Error?I.message:"Failed to attach buyer details.")})},[f,he,y,ii,Ee,k.email,k.firstName,k.lastName,ue]),ut(()=>{!f||!lt||lt.setCardFieldOrder?.(Te??null,Q==null&&!he)},[f,lt,Te,Q,he]),ut(()=>{(ae==="expanding"||ae==="collapsing"||ae==="apm-expanding"||ae==="apm-collapsing")&&ue(null)},[ae,ue]);let xn=be((i,I,z)=>{l?.(Ft(i,I,z))},[l]),_r=be((i,I,z)=>{let ye=z?.popupBlocked??lr(I),U=Cc(i,ye),Se=Cr(z?.code)??Zn(I)??"external_payment_method_failed",Fe=new An(U,"api_error",{code:"external_payment_method_failed",param:i});Xe(null),de==="buttons"&&(It("buttons"),Jt(null)),ue(U),d?.(Fe),console.error("[FloPay] External payment method failed:",{method:i,code:Se,popupBlocked:ye})},[de,d,ue]);ut(()=>{if(!f||!e){At(null);return}let i=Ma(_?.vault);if(i){At(i);return}if(!Pt){At(null);return}At(null);let I=!0;return new Vr($).getVaultCapture(e,t).then(z=>{if(!I)return;let ye=Ma(z);ye?At(ye):ue("Failed to load the secure card form.")}).catch(z=>{I&&ue(z instanceof Error?z.message:"Failed to load the secure card form.")}),()=>{I=!1}},[f,Pt,Yn,e,_?.vault?.html,_?.vault?.messageToken,_?.vault?.expectedOrigin,$,t,ue]);let zn=we({onComplete:a,onError:d,updateError:ue,emitDecline:xn,resolvedAccount:k,avsConfig:Q,avsCheckProp:Be,sessionId:e,nonce:t,baseUrl:$,captureMethod:_?.captureMethod,paymentId:_?.paymentId,authorizationExpiresAt:_?.authorizationExpiresAt});zn.current={onComplete:a,onError:d,updateError:ue,emitDecline:xn,resolvedAccount:k,avsConfig:Q,avsCheckProp:Be,sessionId:e,nonce:t,baseUrl:$,captureMethod:_?.captureMethod,paymentId:_?.paymentId,authorizationExpiresAt:_?.authorizationExpiresAt};let aa=we(!1),zs=be(()=>{let{resolvedAccount:i,avsConfig:I,avsCheckProp:z}=zn.current,ye=i.email?.trim(),U=Kt(ye)?ye:rr.current.trim();if(!Kt(U))return null;let Se=i.firstName?.trim(),Fe=i.lastName?.trim(),tt=Ht.current||i.country||"US",$t=I?Ue(I.state,tt):!1,ct=I?Ue(I.address_line_1,tt):!1,dt=I?Ue(I.postal_code,tt):!1,Ye=I?Ue(I.city,tt):!1,Zt=I?Ue(I.address_line_2,tt):!1,je=ct&&!$t&&dt?cs(tt,(zt.current??"").trim()):null,Qt=$t?Bt.current:je;return{accountData:{userId:i.userId??"",email:U,...Se?{firstName:Se}:{},...Fe?{lastName:Fe}:{},...dt&&zt.current?{zip:zt.current}:{},...Ye&&gn.current?{city:gn.current}:{},...Qt?{state:Qt}:{},...ct&&fn.current?{addressLine1:fn.current}:{},...Zt&&ln.current?{addressLine2:ln.current}:{},country:tt},...z!==void 0?{avsCheck:z}:{},...I?{avsConfig:{country:Ue(I.country,tt),postal_code:dt,address_line_1:ct,address_line_2:Zt,city:Ye,state:$t}}:{}}},[]),si=we(vt);si.current=vt,ut(()=>{vt||s!==ys||zn.current.updateError(null)},[vt,s]),ut(()=>{!f||!lt||lt.setSubmitGate?.(Gn||vt||Ee)},[f,lt,Gn,vt,Ee]),ut(()=>{if(!f||!lt)return;aa.current=!1;let i=!1,I=lt.on("submitting",()=>{yr(!0),Tt.current&&clearTimeout(Tt.current),Rt.current="validation-window",Tt.current=setTimeout(()=>{Tt.current=null,Rt.current==="validation-window"&&(Rt.current="processing")},fc),Xe("processing");let{baseUrl:Fe,sessionId:tt,nonce:$t,updateError:ct,onError:dt}=zn.current;if(!tt||!$t)return;let Ye=zs();if(!Ye){ct("Enter a valid email address."),Rt.current="idle",Xe(null);return}new Vr(Fe).patchAccountSnapshot(tt,$t,Ye,{telemetryMode:"best_effort"}).catch(Zt=>{if(!gc(Zt))return;let je=Zt instanceof Error?Zt.message:"Please check your billing address and try again.";ct(je),Rt.current="idle",Xe(null),dt?.(Zt instanceof An?Zt:new An(je,"api_error"))})}),z=lt.on("complete",async Fe=>{if(jr(Fe.sessionId??zn.current.sessionId),Rt.current="terminal",Xe("success"),await new Promise(ct=>setTimeout(ct,1200)),aa.current)return;aa.current=!0;let tt=zn.current,$t=Aa(tt)||Fe.outcome==="authorized";zn.current.onComplete?.($t?{status:"authorized",paymentIntentId:Fe.intentId,paymentId:Fe.paymentId??tt.paymentId,sessionId:Fe.sessionId??tt.sessionId,authorizationExpiresAt:Fe.authorizationExpiresAt??tt.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",paymentIntentId:Fe.intentId,checkoutMethod:"card"})}),ye=lt.on("decline",async Fe=>{let{updateError:tt,emitDecline:$t}=zn.current,ct=Fe.message??"Your payment was declined. Please try another card or contact your bank.";Rt.current="terminal",tt(ct),Xe("error");let dt=Fe.failureOutcome??sc(Fe.declineReason)??"authorization_declined";$t("card",ct,{code:dt,declineCode:dt}),await new Promise(Ye=>setTimeout(Ye,1500)),!i&&(Rt.current="idle",Xe(null))}),U=lt.on("error",async Fe=>{let{updateError:tt,onError:$t}=zn.current,ct=Fe.message??"There was a problem processing your payment. Please try again.";Rt.current="terminal",tt(ct),Xe("error"),$t?.(new An(ct,"api_error",{code:Fe.failureOutcome??"capture_failed"})),await new Promise(dt=>setTimeout(dt,1500)),!i&&(Rt.current="idle",Xe(null))}),Se=lt.on("blocked",()=>{if(!si.current){yr(!0);return}oa(),zn.current.updateError(ys)});return()=>{i=!0,Tt.current&&(clearTimeout(Tt.current),Tt.current=null),Rt.current="idle",I(),z(),ye(),U(),Se()}},[f,lt,oa]);let Un=!!R?.clientId,Zr=Array.isArray(C),ko=Zr&&C.length>0,Us=Zr&&C.includes("paypal"),{expressMethods:Io,paymentElementMethods:Qr}=st(()=>lc(C,{excludePaypal:Un}),[C,Un]),li=Un||!!Qe,qs=st(()=>li?Io.filter(i=>i!=="paypal"):Io,[Io,li]),$s=st(()=>{let i=[];return ne&&i.push("apple_pay"),ce&&i.push("google_pay"),i},[ne,ce]),Ro=Zr?qs:$s,js=V&&Ro.length>0,ia=or?$e:B,Eo=st(()=>{let i=ia?.trim().toUpperCase();return i?pe?Qr.filter(I=>{let z=pe[I];return!z||z.length===0||z.includes(i)}):ec(Qr,ia):Qr},[Qr,ia,pe]),sa=st(()=>({mode:"payment",amount:ft,currency:Ce.toLowerCase(),paymentMethodCreation:"manual",appearance:ri}),[ft,Ce,ri]),[ci,di]=me("loading"),[ui,pi]=me("loading"),[mi,yi]=me("loading"),[Ks,la]=me(!1),[fi,ca]=me("loading"),[_o,Vs]=me();ut(()=>{Vs(ss())},[]);let gi=ge&&(Un||(Zr?Us:_o===!1)),hi=V&&js,eo=!W&&gi&&Un,bi=fi==="retrying"||fi==="exhausted",to=!W&&gi&&!!Nn&&(!Un||bi),no=!W&&hi&&!!Mt,ro=!W&&V&&ko&&Eo.length>0&&!!Mt,Hs=eo&&!bi?Ks:to&&hs(ci),Ys=no&&hs(ui),Gs=ro&&mi!=="load_error",vi=i=>i==="loading"||i==="ready",Pi=eo||to&&vi(ci)||no&&vi(ui)||ro&&mi!=="load_error",xo=we(!1);ut(()=>{if(!xo.current){if(!V&&!ge){xo.current=!0;let i=new An("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");d?.(i),ue(i.message)}else if(!V&&ge&&!Un&&!Nn){xo.current=!0;let i=new An("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");d?.(i),ue(i.message)}else if(_o!==void 0&&!W&&!vn&&!Pi){xo.current=!0;let i=new An("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"});d?.(i),ue(i.message)}}},[V,ge,Un,Nn,_o,W,vn,Pi,d,ue]);let Ci=we(!1);ut(()=>{if(Ci.current||!ko)return;let i=[];ne!==!0&&i.push("showApplePay"),ce!==!0&&i.push("showGooglePay"),i.length!==0&&(Ci.current=!0,console.warn(`[FloPay] ${i.join(" / ")} ${i.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.`))},[ko,ne,ce]);let Si=be((i,I)=>Ke.applyInlineSessionPatch?Ke.applyInlineSessionPatch(i).then(z=>({error:null,sessionId:z.sessionId||e,nonce:z.session?.clientSecret||t})).catch(z=>{let ye=gs(I,z);return ue(ye.message),d?.(ye),{error:ye,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[Ke.applyInlineSessionPatch,t,d,e,ue]),Tn=be(async i=>{if(!D)return{proceed:!0};try{let I=await D({method:i,sessionId:e||void 0,createSession:Ke.inlineSessionDraft});if(I===!1)return{proceed:!1};if(I&&typeof I=="object"){I.account&&nr(ye=>({...ye??{},...I.account}));let z=await Si(I,i);return z.error?{proceed:!1,accountPatch:I.account}:{proceed:!0,accountPatch:I.account,sessionId:z.sessionId,nonce:z.nonce}}return{proceed:!0}}catch(I){let z=gs(i,I);return ue(z.message),d?.(z),{proceed:!1}}},[Si,Ke.inlineSessionDraft,D,d,e,ue]),wi=be(async(i,I)=>{if(pn.current)return;pn.current=!0,_t(!0),Xe("processing"),ue(null);let z=I?.sessionId??e,ye=I?.nonce??t,U=Sa(k,I?.accountPatch),Se=I?.completionPaymentMethodId??uo(i),Fe=i.originalPaymentMethodId?{...i,originalPaymentMethodId:void 0}:i,tt=i.gateway==="stripe"?"stripe":i.gateway==="paypal"||i.isPaypal?"paypal":void 0,$t=()=>{mt?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"process_payment",provider:tt})};try{let dt=await new Vr($).processPayment(U.userId??"",{sessionId:z,nonce:ye,tokenizedData:Fe,accountData:{userId:U.userId??"",email:U.email??"",...U.firstName?{firstName:U.firstName}:{},...U.lastName?{lastName:U.lastName}:{},...Q?(()=>{let je=Ht.current,Qt=Ue(Q.state,je),wn=Ue(Q.address_line_1,je),jt=Ue(Q.postal_code,je),io=wn&&!Qt&&jt?cs(je,(zt.current??"").trim()):null,so=Qt?Bt.current:io;return{country:je,...jt&&zt.current?{zip:zt.current}:{},...Ue(Q.city,je)&&gn.current?{city:gn.current}:{},...so?{state:so}:{},...wn&&fn.current?{addressLine1:fn.current}:{},...Ue(Q.address_line_2,je)&&ln.current?{addressLine2:ln.current}:{}}})():{}},chv:v,avsCheck:Be??!1,checkoutType:Y,checkoutLayout:j,avsConfig:Q?{country:Ue(Q.country,Ht.current),postal_code:Ue(Q.postal_code,Ht.current),address_line_1:Ue(Q.address_line_1,Ht.current),address_line_2:Ue(Q.address_line_2,Ht.current),city:Ue(Q.city,Ht.current),state:Ue(Q.state,Ht.current)}:void 0});if(dt.ok){let je=dt.status===204?null:await dt.json().catch(()=>null),Qt=Aa(_)||je?.status==="authorized";jr(z),Xe("success"),M(null),await new Promise(wn=>setTimeout(wn,1200)),a?.(Qt?{status:"authorized",...typeof je?.paymentId=="string"?{paymentId:je.paymentId}:_?.paymentId?{paymentId:_.paymentId}:{},sessionId:typeof je?.sessionId=="string"?je.sessionId:z,...typeof je?.authorizationExpiresAt=="string"?{authorizationExpiresAt:je.authorizationExpiresAt}:_?.authorizationExpiresAt?{authorizationExpiresAt:_.authorizationExpiresAt}:{},paymentIntentId:i.threeDSecureActionResultTokenId,paymentMethodId:Se,checkoutMethod:i.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:i.threeDSecureActionResultTokenId,paymentMethodId:Se,checkoutMethod:i.isPaypal?"paypal":"card"});return}let Ye=await dt.json().catch(()=>null);if(Ye?.type==="paypal_redirect_required"){let je=Ye.threeDSecureToken,Qt=Ye.paymentMethodId||i.id||"";if(!J||!je){Xe("error"),ue("PayPal authorization required but no token provided.");return}try{let wn=Qe?.getRawProvider();if(!wn){ue("PayPal is not available.");return}let jt={return_url:window.location.href};Qt&&(jt.payment_method=Qt);let{error:io}=await wn.confirmPayment({clientSecret:je,confirmParams:jt,redirect:"if_required"});if(io){Xe("error");let so=io.message??"PayPal payment failed.";ue(so),xn("paypal",so,{code:io.code})}}catch(wn){Xe("error"),ue(wn instanceof Error?wn.message:"PayPal authorization failed.")}return}if(Ye?.type==="paypal_direct_required"){let je=Ye.orderId;if(!je){Xe("error"),ue("PayPal retry required but no order id provided.");return}let Qt=N.current?.attempts??0;if(Qt>=2){Xe("error"),ue("PayPal payment could not be completed after multiple attempts."),xn("paypal","paypal_direct_required retry limit exceeded");return}la(!1),ca("loading"),M({orderId:je,attempts:Qt+1}),Xe(null);return}Ql(dt.status,Ye)||$t(),Xe("error");let Zt=Ye?.message??"Payment failed. Please try again.";ue(Zt),xn(i.isPaypal?"paypal":"card",Zt,{code:Ye?.code??Ye?.gatewayErrorCode,declineCode:Ye?.declineCode??Ye?.gatewayDeclineReason}),await new Promise(je=>setTimeout(je,1500))}catch(ct){Ss(ct)||$t(),Xe("error"),ue(ct instanceof Error?ct.message:"An unexpected error occurred"),await new Promise(dt=>setTimeout(dt,1500))}finally{_t(!1),Xe(null),pn.current=!1}},[$,e,t,k,O,v,J,Qe,_,a,d,ue,xn,mt]),Sn=be((i,I)=>{S?S(i):wi(i,I)},[S,wi]),ki=we(!1);ut(()=>{if(typeof window>"u"||ki.current)return;let i=new URLSearchParams(window.location.search),I=i.get("payment_intent"),z=i.get("payment_intent_client_secret"),ye=i.get("redirect_status");if(!I||!z)return;let U=dt=>{let Ye=localStorage.getItem(dt);if(!Ye)return null;try{return JSON.parse(Ye)}catch{return localStorage.removeItem(dt),null}},Se=U($n)??U(ms),Fe;if(Se?.clientSecret){if(Se.clientSecret!==z)return;Fe={...Se.accountPatch?{accountPatch:Se.accountPatch}:{},...Se.sessionId?{sessionId:Se.sessionId}:{},...Se.nonce?{nonce:Se.nonce}:{}}}else if(Se?.sessionId&&Se.sessionId!==e)return;ki.current=!0,localStorage.removeItem($n),localStorage.removeItem(ms);let tt=new URL(window.location.href);tt.searchParams.delete("payment_intent"),tt.searchParams.delete("payment_intent_client_secret"),tt.searchParams.delete("redirect_status"),window.history.replaceState({},"",tt.toString());let $t=Se?.paymentMethodType??Se?.tokenType??"card",ct="card";(async()=>{let dt=J?.getRawProvider();if(!dt){let jt="Payment is not available \u2014 please refresh and try again.";ue(jt),xn(ct,jt);return}if(ye==="failed"){let jt="Payment was declined. Please try again.";ue(jt),xn(ct,jt);return}let{paymentIntent:Ye,error:Zt}=await dt.retrievePaymentIntent(z);if(Zt){let jt=Zt.message??"Failed to retrieve payment status.";ue(jt),xn(ct,jt,{code:Zt.code});return}let je=Ye?.status,Qt=Lo(je);if(!Ye||!Qt){let jt=je==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";ue(jt),xn(ct,jt,{code:je??"missing_payment_intent"});return}let wn=typeof Ye.payment_method=="string"?Ye.payment_method:Ye.payment_method?.id;Sn({id:wn??Se?.paymentMethodId??Se?.tokenId??Ye.id,type:"card",threeDSecureActionResultTokenId:Ye.id,gateway:Se?.gateway??"stripe",paymentMethodType:$t},Fe)})()},[e,Sn,J,ue,xn]);let da=be(i=>{i.preventDefault()},[]);if(!(J!==null))return u("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let oo=de==="buttons",an=x?.variables,Ws=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),ua=an?.colorBackground,Js=ua&&!Ws.has(ua)?ua:void 0,xr=p.cardInputBorder??(oo?"#e5e7eb":"#A4A4FF"),pa=an?.colorDanger??"#dc2626",gr=i=>ar&&i?pa:xr,To=(Wt.malformed||Wt.empty)&&(Pn||ar),Xs=To?pa:gr(nn.zip),ma=p.cardFormContainer?.backgroundColor??Js??(oo?"white":"#EDEDFF"),Tr=p.cardInputBackground??an?.colorBackground??"white",ya=Ar(Ie),Ii=Ar(Re),Br=p.nameInput,Ri=p.cardInputFontSize??Ic(Br?.fontSize)??an?.fontSizeBase??"16px",Ei=typeof Br?.fontFamily=="string"?Br.fontFamily:an?.fontFamily??"Poppins, sans-serif",_i=Mi(Br?.fontWeight)??400,Zs=p.cardInputColor??(typeof Br?.color=="string"?Br.color:void 0)??an?.colorText??"#262833",Qs=p.cardInputPlaceholderColor??"#9ca3af",St=an?.borderRadius??"8px",hr=an?.borderRadius??p.cardButton?.borderRadius??St,br=an?.colorPrimary??"#4A49FF",el=an?.colorPrimaryHover??lo(br,.12),fa=an?.colorText??"#262833",ga={fontSize:Ri,fontFamily:Ei,fontWeight:_i,color:Zs,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},tl={"--flopay-input-placeholder-color":Qs,"--flopay-input-font-size":Ri,"--flopay-input-font-family":Ei,"--flopay-input-font-weight":String(_i)},ao=p.cardFormContainer??{},ha=ao.padding??(oo?"0":"1rem"),ba=ao.borderRadius??St,nl=lt&&cn?u(va,{capture:lt,html:cn.html,messageToken:cn.messageToken,expectedOrigin:cn.expectedOrigin,theme:ie,onReady:()=>{if(!he&&!Q||typeof document>"u")return;let i=()=>{(document.querySelector('[data-testid="flopay-vault-identity-fields"]')??document.querySelector('[data-testid="flopay-avs-fields"]'))?.querySelector("input:not([disabled]), select:not([disabled])")?.focus()};i();let I=0,z=window.setInterval(()=>{I+=1;let ye=document.activeElement;!!ye&&ye.tagName==="IFRAME"&&ye.id==="flopay_vault_form_iframe"?(i(),window.clearInterval(z)):I>=50&&window.clearInterval(z)},100)},onError:i=>ue(i),onValidation:i=>{let I=Rt.current;(I==="idle"||I==="validation-window")&&(ue(i),i&&Rt.current==="validation-window"&&(Tt.current&&(clearTimeout(Tt.current),Tt.current=null),Rt.current="idle",Xe(null)))}}):u("div",{"data-testid":"flopay-vault-loading",style:{minHeight:120,display:"flex",alignItems:"center",justifyContent:"center",color:"#6b7280",fontSize:14},children:"Loading secure card form\u2026"}),xi=De("div",{onFocusCapture:i=>{["INPUT","SELECT","TEXTAREA","IFRAME"].includes(i.target.tagName)&&ir()},style:{backgroundColor:ma,borderRadius:ba,...ao,padding:ha,...tl,display:"flex",flexDirection:"column"},children:[u("style",{children:`
26
26
  .flopay-shared-input::placeholder {
27
27
  color: var(--flopay-input-placeholder-color);
28
28
  opacity: 1;
@@ -30,13 +30,13 @@ ${Mt.join(`
30
30
  font-family: var(--flopay-input-font-family);
31
31
  font-weight: var(--flopay-input-font-weight);
32
32
  }
33
- `}),io&&hn&&ke("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:Be?-2:0},children:[ke("button",{type:"button",onClick:Ar,style:{display:"inline-flex",alignItems:"center",gap:Pa?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:f.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...f.backButton},"aria-label":"Back to payment methods",children:[l("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...f.backButtonIcon},children:l("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:l("path",{d:"M15 18l-6-6 6-6"})})}),l(Lr,{content:Te})]}),Ti?l("div",{style:{flex:1}}):l("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:f.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...f.title},children:l(mo,{content:Ae})})]}),!io&&!Ti&&l("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:so,order:Be?-3:0,...f.title},children:l(mo,{content:Ae})}),Be&&A&&ke("div",{"data-testid":"flopay-vault-identity-fields",style:{order:-1,marginTop:"0.5rem"},children:[se&&ke(fr,{children:[l("label",{htmlFor:"flopay-buyer-email",style:{display:"block",color:so,...Fr},children:"Email address"}),l("div",{style:{backgroundColor:Cr,border:`1px solid ${vr}`,borderRadius:Pt,marginTop:"0.375rem",padding:"10px"},children:l("input",{className:"flopay-shared-input",id:"flopay-buyer-email",name:"email",type:"email",autoComplete:"email",value:bt,onChange:i=>{Un.current=i.target.value,ir(i.target.value)},onBlur:To,disabled:d,required:!0,"data-testid":"flopay-email",style:{width:"100%",border:"none",outline:"none",background:"transparent",...Fr}})})]}),ue&&ke(fr,{children:[l("label",{htmlFor:"flopay-buyer-name",style:{display:"block",marginTop:se?"0.75rem":void 0,color:so,...Fr},children:"Full name"}),l("div",{style:{backgroundColor:Cr,border:`1px solid ${vr}`,borderRadius:Pt,marginTop:"0.375rem",padding:"10px"},children:l("input",{className:"flopay-shared-input",id:"flopay-buyer-name",name:"name",autoComplete:"name",value:Ht,onChange:i=>{qn.current=i.target.value,sr(i.target.value)},onBlur:To,disabled:d,required:!0,"data-testid":"flopay-name",style:{width:"100%",border:"none",outline:"none",background:"transparent",...Fr}})})]})]}),X&&l("div",{style:{order:Be?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let i=Le,R=(z=!1)=>({backgroundColor:Cr,border:`1px solid ${Pr(z)}`,borderRadius:Pt,marginTop:"0.5rem",padding:"10px"}),N=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...Fr}),he=ac(i);return ke(fr,{children:[ze(X.address_line_1,i)&&l("div",{style:R(Ut.line1),children:l("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:Rn,onChange:z=>{zt.current.addressLine1=!0,xt.current=z.target.value,_n(z.target.value)},disabled:d,required:!0,"data-testid":"flopay-address-line1",style:N()})}),ze(X.address_line_2,i)&&l("div",{style:R(),children:l("input",{className:"flopay-shared-input",id:"flopay-billing-address-line2",name:"billing-address-line2",placeholder:"Apt, Suite, Unit (optional)",autoComplete:"billing address-line2",value:Zn,onChange:z=>{zt.current.addressLine2=!0,tn.current=z.target.value,Jt(z.target.value)},disabled:d,"data-testid":"flopay-address-line2",style:N()})}),(ze(X.city,i)||ze(X.state,i))&&ke("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[ze(X.city,i)&&l("div",{style:{flex:1,backgroundColor:Cr,borderTop:`1px solid ${Pr(Ut.city)}`,borderRight:`1px solid ${Pr(Ut.city)}`,borderBottom:`1px solid ${Pr(Ut.city)}`,borderLeft:`1px solid ${Pr(Ut.city)}`,padding:"10px",borderTopLeftRadius:Pt,borderBottomLeftRadius:Pt,...ze(X.state,i)?{borderRight:"none",borderTopRightRadius:0,borderBottomRightRadius:0}:{borderRadius:Pt}},children:l("input",{className:"flopay-shared-input",id:"flopay-billing-city",name:"billing-city",placeholder:"City",autoComplete:"billing address-level2",value:cn,onChange:z=>{zt.current.city=!0,un.current=z.target.value,dn(z.target.value)},disabled:d,required:!0,"data-testid":"flopay-city",style:N()})}),ze(X.state,i)&&l("div",{style:{flex:1,backgroundColor:Cr,border:`1px solid ${Pr(Ut.state)}`,padding:"10px",borderTopRightRadius:Pt,borderBottomRightRadius:Pt,...ze(X.city,i)?{borderTopLeftRadius:0,borderBottomLeftRadius:0}:{borderRadius:Pt}},children:he?ke("select",{id:"flopay-billing-state",name:"billing-state",value:Ft,onChange:z=>{zt.current.state=!0,pn.current=z.target.value,vn(z.target.value)},disabled:d,autoComplete:"billing address-level1",required:!0,"data-testid":"flopay-state",style:{...N(),cursor:"pointer"},children:[l("option",{value:"",children:ys(i)}),he.map(z=>l("option",{value:z.code,children:z.name},z.code))]}):l("input",{className:"flopay-shared-input",id:"flopay-billing-state",name:"billing-state",placeholder:ys(i),autoComplete:"billing address-level1",value:Ft,onChange:z=>{zt.current.state=!0,pn.current=z.target.value,vn(z.target.value)},disabled:d,required:!0,"data-testid":"flopay-state",style:N()})})]}),(ze(X.country,i)||ze(X.postal_code,i))&&ke("div",{style:{display:"flex",flexDirection:te==="column"?"column":"row",gap:te==="column"?"0.5rem":"0",marginTop:"0.5rem"},children:[ze(X.country,i)&&l("div",{style:{flex:te==="row"?1:void 0,backgroundColor:Cr,borderTop:`1px solid ${vr}`,borderRight:`1px solid ${vr}`,borderBottom:`1px solid ${vr}`,borderLeft:`1px solid ${vr}`,padding:"10px",...te==="row"&&ze(X.postal_code,i)?{borderRadius:"0",borderTopLeftRadius:Pt,borderBottomLeftRadius:Pt,borderRight:"none"}:{borderRadius:Pt}},children:l("select",{id:"flopay-billing-country",name:"billing-country",value:Le,onChange:z=>{zt.current.country=!0,_t.current=z.target.value,Wt(z.target.value),Je?.(z.target.value),pn.current="",vn("")},disabled:d,autoComplete:"billing country","data-testid":"flopay-country",style:{...N(),cursor:"pointer"},children:tc.map(z=>ke("option",{value:z.code,children:[z.flag," ",z.name]},z.code))})}),ze(X.postal_code,i)&&l("div",{style:{flex:te==="row"?1:void 0,backgroundColor:Cr,border:`1px solid ${tl}`,padding:"10px",...te==="row"&&ze(X.country,i)?{borderRadius:"0",borderTopRightRadius:Pt,borderBottomRightRadius:Pt}:{borderRadius:Pt}},children:l("input",{className:"flopay-shared-input",id:"flopay-billing-postal-code",name:"billing-postal-code",placeholder:Ua(Le),autoComplete:"billing postal-code",value:wt,onChange:z=>{zt.current.zip=!0,ot.current=z.target.value,Ot(z.target.value),We?.(z.target.value)},onBlur:()=>Zt(!0),disabled:d,required:yn.required,"aria-invalid":Lo||void 0,"aria-describedby":Lo?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:N()})})]}),Lo&&l("div",{id:"flopay-billing-postal-code-error",role:"alert","data-testid":"flopay-zip-error",style:{marginTop:"0.375rem",color:ba,...Fr,fontSize:"0.75rem"},children:yn.empty?`${Ua(i)} is required`:Ic(i)})]})})()}),Be&&Ye&&l("div",{style:{order:-2,width:"100%"},children:Ye}),Be&&il,B&&l(Kr,{margin:"0.75rem 0",styleOverride:f.errorBanner,children:B})]}),Oo={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"},Ni=i=>St?!ve||!Hn?l("pre",{"data-testid":i,style:Oo,children:"FloPay/DirectPayPal-debug - not enabled"}):l("pre",{"data-testid":i,style:Oo,children:["FloPay/DirectPayPal-debug (parent gate)",` showPayPal=${ve}`,` directPaypalConfigured=${Hn}`,` inAppBrowserDetected=${String(No)}`,` shouldRenderDirectPayPal=${no}`,` shouldRenderStripePayPal=${ro}`,` hasPaypalStripeInstance=${!!bn}`].join(`
34
- `)}):null,Di=i=>St?!H||!ge?l("pre",{"data-testid":i,style:Oo,children:"FloPay/Stripe-debug - not enabled"}):l("pre",{"data-testid":i,style:Oo,children:["FloPay/Stripe-debug (parent gate)",` showStripe=${H}`,` currency=${we}`,` amountInCents=${Qr}`,` enabledPaymentMethods: ${JSON.stringify(P??[])}`,` enabledPaymentMethodsProvided=${eo}`,` hasEnabledMethods=${Ao}`,` expressMethods: ${JSON.stringify(Mo)}`,` walletExpressMethods: ${JSON.stringify(Bo)}`,` paymentElementMethods: ${JSON.stringify(to)}`,` paymentElementMethodsForCurrency: ${JSON.stringify(Fo)}`,` hasStripeInstance=${!!ge}`,` shouldRenderWallets=${oo}`,` shouldRenderPaymentElement=${ao}`].join(`
35
- `)}):null,Li=xe==="apm-expanding"||xe==="apm-form"||xe==="apm-collapsing",zo=xe==="apm-expanding"?`flopay-card-enter ${qt}ms cubic-bezier(0, 0, 0.2, 1) both`:xe==="apm-collapsing"?`flopay-card-exit ${qt}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0,Uo=Tt?{...ma,paymentMethodTypes:[Tt]}:null;if(oe==="buttons"){let i=xe==="buttons"||xe==="expanding"||xe==="apm-expanding",R=xe==="expanding"||xe==="card"||xe==="collapsing",N=De===void 0?{boxSizing:"border-box",height:ra,padding:"0 1rem"}:{padding:"0.9rem 1rem"},he=xe==="expanding"||xe==="apm-expanding"?`flopay-buttons-exit ${qt}ms cubic-bezier(0.4, 0, 0.2, 1) both`:xe==="collapsing"||xe==="apm-collapsing"?`flopay-buttons-enter ${qt}ms cubic-bezier(0, 0, 0.2, 1) both`:void 0,z=xe==="expanding"?`flopay-card-enter ${qt}ms cubic-bezier(0, 0, 0.2, 1) both`:xe==="collapsing"?`flopay-card-exit ${qt}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0;return ke("form",{onSubmit:ga,className:M,style:{position:"relative"},children:[l(za,{}),Qt&&l(Yn,{status:Qt,errorMessage:B,authorized:xn}),ke("div",{style:{display:"grid"},children:[ke("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!i&&!he?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!i&&!he?Sc:{},...he?{animation:he,pointerEvents:"none"}:{}},children:[Ni("flopay-direct-paypal-gate-debug"),Di("flopay-stripe-gate-debug"),no&&x&&ke(fr,{children:[V&&l("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."}),l(Jo,{sessionId:e,nonce:t,billingApiUrl:ne,email:k.email,billingName:Ee||void 0,onBuyerIdentityReady:me,clientId:x.clientId,environment:x.environment,currency:we.toUpperCase(),isSubscription:K,providerObjectType:x.providerObjectType,onTokenizedBody:Sn,onComplete:a,onErrorChange:pe,onDecline:s,onTechnicalFailure:Mr,onButtonClick:J,runBeforeButtonClick:Dn,isProcessing:d,onLoadStateChange:ya,onInitializationStateChange:fa,session:I??null,existingOrderId:V?.orderId,debug:St},V?.orderId??"fresh")]}),ro&&l(_r,{stripe:bn,options:di,children:l(Ss,{sessionId:e,nonce:t,email:k.email,billingName:Ee||void 0,onBuyerIdentityReady:me,billingApiUrl:ne,onTokenizedBody:Sn,onErrorChange:pe,isProcessing:d,onButtonClick:J,onDecline:s,onTechnicalFailure:Mr,runBeforeButtonClick:Dn,onLoadStateChange:fi,placeholderBorderRadius:Sr})}),oo?l(_r,{stripe:ge,options:ci,children:l(ws,{sessionId:e,nonce:t,email:k.email,billingName:Ee||void 0,onBuyerIdentityReady:me,billingApiUrl:ne,intentKind:$>0?"payment":"setup",expressMethods:Bo,onTokenizedBody:Sn,onErrorChange:pe,onButtonClick:J,onDecline:s,onTechnicalFailure:Mr,runBeforeButtonClick:Dn,onLoadStateChange:hi,placeholderBorderRadius:Sr})}):Si?l("div",{style:{height:ra,borderRadius:Sr,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,ao&&l(ks,{sessionId:e,nonce:t,email:k.email,billingName:[k.firstName,k.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:me,billingApiUrl:ne,paymentElementMethods:Fo,stripeInstance:ge,paymentElementBaseOptions:ma,onTokenizedBody:Sn,onErrorChange:pe,onButtonClick:J,onDecline:s,runBeforeButtonClick:Dn,onLoadStateChange:vi,isProcessing:d,submitButtonColor:wr,submitButtonBorderRadius:Pt,submitButtonStyle:f.submitButton,onExpandApm:Fn,expandedApmMethod:Tt,themeId:Ce,buttonAppearance:{backgroundColor:f.cardButton?.backgroundColor,borderColor:f.cardInputBorder,textColor:f.cardButton?.color,borderRadius:Sr}}),Be&&l("button",{type:"button",onClick:async()=>{d||!(await Dn("card")).proceed||(J?.("card"),er())},disabled:d,style:{width:"100%",...N,...f.cardButton,...Ha({themeBundle:h,resolvedPrimaryColor:wr,resolvedBorderRadius:Pt,submitButtonStyle:f.submitButton,explicitPrimaryColor:sn?.colorPrimary}),fontSize:f.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:d?"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:d?.6:1},onMouseEnter:Re=>{!d&&(h||sn?.colorPrimary)&&(Re.currentTarget.style.backgroundColor=ol)},onMouseLeave:Re=>{(h||sn?.colorPrimary)&&(Re.currentTarget.style.backgroundColor=wr)},onMouseDown:Re=>{Re.currentTarget.style.transform="scale(0.985)"},onMouseUp:Re=>{Re.currentTarget.style.transform="scale(1)"},children:l(Dr,{content:De})}),B&&xe==="buttons"&&l(Kr,{margin:"0.25rem 0",styleOverride:f.errorBanner,children:B})]}),Be&&R&&l("div",{style:{gridArea:"1 / 1",...z?{animation:z}:{},...xe==="collapsing"?{pointerEvents:"none"}:{}},children:Fi}),H&&Li&&Tt&&Uo&&ge&&l("div",{style:{gridArea:"1 / 1",...zo?{animation:zo}:{},...xe==="apm-collapsing"?{pointerEvents:"none"}:{}},children:ke("div",{style:{backgroundColor:va,borderRadius:Sa,...lo,padding:Ca},children:[ke("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[ke("button",{type:"button","data-testid":"flopay-apm-back-button",onClick:Kn,style:{display:"inline-flex",alignItems:"center",gap:Pa?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:f.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...f.backButton},"aria-label":"Back to payment methods",children:[l("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...f.backButtonIcon},children:l("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:l("path",{d:"M15 18l-6-6 6-6"})})}),l(Lr,{content:Te})]}),l("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:f.titleFontSize??"1.05rem",color:so,paddingRight:80,...f.title},children:`Pay with ${xr(Tt)}`})]}),l(_r,{stripe:ge,options:Uo,children:l($a,{method:Tt,sessionId:e,nonce:t,email:k.email,billingName:[k.firstName,k.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:me,billingApiUrl:ne,onTokenizedBody:Sn,onErrorChange:pe,onDecline:s,onCancel:Kn,runBeforeButtonClick:Dn,onButtonClick:J,isProcessing:d,submitButtonColor:wr,submitButtonBorderRadius:Pt,submitButtonStyle:f.submitButton,errorText:B})},Tt)]})})]})]})}return Li&&Tt&&Uo&&ge&&H?ke("form",{onSubmit:ga,className:M,style:{position:"relative"},children:[l(za,{}),Qt&&l(Yn,{status:Qt,errorMessage:B,authorized:xn}),l("div",{style:{...zo?{animation:zo}:{},...xe==="apm-collapsing"?{pointerEvents:"none"}:{}},children:ke("div",{style:{backgroundColor:va,borderRadius:Sa,...lo,padding:Ca},children:[ke("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[ke("button",{type:"button","data-testid":"flopay-apm-back-button-default",onClick:Kn,style:{display:"inline-flex",alignItems:"center",gap:Pa?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:f.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...f.backButton},"aria-label":"Back to payment methods",children:[l("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...f.backButtonIcon},children:l("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:l("path",{d:"M15 18l-6-6 6-6"})})}),l(Lr,{content:Te})]}),l("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:f.titleFontSize??"1.05rem",color:so,paddingRight:80,...f.title},children:`Pay with ${xr(Tt)}`})]}),l(_r,{stripe:ge,options:Uo,children:l($a,{method:Tt,sessionId:e,nonce:t,email:k.email,billingName:[k.firstName,k.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:me,billingApiUrl:ne,onTokenizedBody:Sn,onErrorChange:pe,onDecline:s,onCancel:Kn,runBeforeButtonClick:Dn,onButtonClick:J,isProcessing:d,submitButtonColor:wr,submitButtonBorderRadius:Pt,submitButtonStyle:f.submitButton,errorText:B})},Tt)]})})]}):ke("form",{onSubmit:ga,className:M,style:{position:"relative"},children:[l(za,{}),Qt&&l(Yn,{status:Qt,errorMessage:B,authorized:xn}),ke("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Ni("flopay-direct-paypal-gate-debug-default"),Di("flopay-stripe-gate-debug-default"),no&&x&&ke(fr,{children:[V&&l("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."}),l(Jo,{sessionId:e,nonce:t,billingApiUrl:ne,email:k.email,clientId:x.clientId,environment:x.environment,currency:we.toUpperCase(),isSubscription:K,providerObjectType:x.providerObjectType,onTokenizedBody:Sn,onComplete:a,onErrorChange:pe,onDecline:s,onTechnicalFailure:Mr,onButtonClick:J,runBeforeButtonClick:Dn,isProcessing:d,onLoadStateChange:ya,onInitializationStateChange:fa,session:I??null,existingOrderId:V?.orderId,debug:St},V?.orderId??"fresh")]}),ro&&l(_r,{stripe:bn,options:di,children:l(Ss,{sessionId:e,nonce:t,email:k.email,billingName:Ee||void 0,onBuyerIdentityReady:me,billingApiUrl:ne,onTokenizedBody:Sn,onErrorChange:pe,isProcessing:d,onButtonClick:J,onDecline:s,onTechnicalFailure:Mr,runBeforeButtonClick:Dn,onLoadStateChange:fi,placeholderBorderRadius:Sr})}),oo&&l(_r,{stripe:ge,options:ci,children:l(ws,{sessionId:e,nonce:t,email:k.email,billingName:Ee||void 0,onBuyerIdentityReady:me,billingApiUrl:ne,intentKind:$>0?"payment":"setup",expressMethods:Bo,onTokenizedBody:Sn,onErrorChange:pe,onButtonClick:J,onDecline:s,onTechnicalFailure:Mr,runBeforeButtonClick:Dn,onLoadStateChange:hi,placeholderBorderRadius:Sr})}),ao&&l(ks,{sessionId:e,nonce:t,email:k.email,billingName:[k.firstName,k.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:ne,paymentElementMethods:Fo,stripeInstance:ge,paymentElementBaseOptions:ma,onTokenizedBody:Sn,onErrorChange:pe,onButtonClick:J,onDecline:s,runBeforeButtonClick:Dn,onLoadStateChange:vi,isProcessing:d,submitButtonColor:wr,submitButtonBorderRadius:Pt,submitButtonStyle:f.submitButton,themeId:Ce,onExpandApm:Fn,expandedApmMethod:Tt,buttonAppearance:{backgroundColor:f.cardButton?.backgroundColor,borderColor:f.cardInputBorder,textColor:f.cardButton?.color,borderRadius:Sr}})]}),Be&&(Xs||Js||Zs)&&ke("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem",margin:"0.5rem 0 0.75rem",color:"#999",fontSize:"0.85rem"},children:[l("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}}),l("span",{children:"or pay with card"}),l("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}})]}),Be&&Fi]})}import{Fragment as Xn,jsx as re,jsxs as Vt}from"react/jsx-runtime";var Gr=44,oi="flopay_checkout_saved_payment_resume",ca=new Map,sa=new Map;function Fs(e,t){t.settled&&t.consumers===0&&ca.get(e)===t&&ca.delete(e)}function zc(e,t,n){let r=sa.get(e);if(r&&(!r.sdkGeneratedIdempotencyKey||!t||r.sdkGeneratedIdempotencyKey===t))return r.attempt;let o=n(),a={attempt:o,sdkGeneratedIdempotencyKey:t};sa.set(e,a);let c=()=>{sa.get(e)===a&&sa.delete(e)};return o.then(c,c),o}function wo(e){return new Promise(t=>setTimeout(t,e))}function la(e,t,n){let r=Yo({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:Os,enabled:t!==!1});return r.beginCheckout(n),r}function ko(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function Wa(e,t,n,r,o){let a=la(e,t,n);a.error({errorCode:r,stage:o,paymentMethodCategory:"unknown",...o==="session_read"?{requestCategory:"session_read"}:{}}),ko(a)}function Uc(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 ni(e){let t=e?.data.paypal?.publishableKey;if(t)return{clientId:t,environment:e?.data.paypal?.environment,providerObjectType:e?.data.paypal?.providerObjectType}}function Ja(e){return!e||e.data.stripe?.publishableKey?!1:!!ni(e)?.clientId}function ar(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function qc(){if(!ar())return null;try{let e=window.sessionStorage.getItem(oi);return e?JSON.parse(e):null}catch{return null}}function Ns(e){if(ar())try{window.sessionStorage.setItem(oi,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function Xa(){if(ar())try{window.sessionStorage.removeItem(oi)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}var ai=":idempotency-key";function zs(e,t){if(!ar())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 Za(e,t,n,r){if(ar())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 ri(e,t){if(ar())try{zs(e,t)&&window.sessionStorage.removeItem(e)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout session cache.",n)}}function Us(e,t){if(!ar())return null;try{let n=window.sessionStorage.getItem(e+ai);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 Qa(e,t,n){if(ar())try{window.sessionStorage.setItem(e+ai,JSON.stringify({canonicalIdentity:t,idempotencyKey:n}))}catch(r){console.warn("[FloPayCheckout] Failed to persist checkout idempotency key.",r)}}function ei(e,t){if(ri(e,t),!!ar())try{Us(e,t)&&window.sessionStorage.removeItem(e+ai)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout idempotency key.",n)}}function $c(){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 Ds(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 jc(e){return e?!!(e.account&&Object.keys(e.account).length>0||e.couponCodes!==void 0||e.tagsData!==void 0||e.utmMetadata!==void 0):!1}function ti(e,t){return`${e}:${t.totalAmount??""}:${t.overrideAmount??""}:${t.quantity??1}:${t.currency??""}`}function Io(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=>ti(`${o.type??""}:${o.code??o.providerItemId??o.providerPlanId??""}`,o)).sort(),i:e?.items?.map(o=>ti(o.code??o.providerItemId??"",o)).sort(),s:e?.subscriptions?.map(o=>ti(o.code??o.providerPlanId??"",o)).sort(),couponCodes:e?.couponCodes?[...e.couponCodes].sort():void 0,...t?{tagsData:e?.tagsData,utmMetadata:e?.utmMetadata,tokenizedData:e?.tokenizedData,checkoutMode:e?.checkoutMode??"full"}:{}};return JSON.stringify(r)}function Kc(e,t=!1){let n=Io(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 Vc(e,t){if(!e?.customer||!e.products)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=Lc(t.currency,t.items,t.subscriptions,t.products);if(!o||e.currency.toUpperCase()!==o.toUpperCase())return!1;let a=(t.products??Bc(t.items,t.subscriptions)).map(b=>({type:b.type,code:b.code??b.providerItemId??b.providerPlanId??"",quantity:b.quantity??1,totalAmount:b.totalAmount,overrideAmount:b.overrideAmount??null,currency:(b.currency??o).toUpperCase()})).sort((b,g)=>`${b.code}:${b.type??""}`.localeCompare(`${g.code}:${g.type??""}`)),c=e.products.map(b=>({type:b.type,code:b.code??"",quantity:b.quantity??1,totalAmount:b.totalAmount,overrideAmount:b.overrideAmount??null,currency:(b.currency??e.currency).toUpperCase()})).sort((b,g)=>`${b.code}:${b.type??""}`.localeCompare(`${g.code}:${g.type??""}`));if(a.length!==c.length)return!1;for(let b=0;b<a.length;b+=1){let g=a[b],m=c[b];if(g.code!==m.code||g.type!==void 0&&g.type!==m.type||g.quantity!==m.quantity||g.totalAmount!==m.totalAmount||g.overrideAmount!==m.overrideAmount||g.currency!==m.currency)return!1}let s=[...t.couponCodes??[]].sort(),S=[...e.coupons??[]].sort();return s.length===S.length&&s.every((b,g)=>b===S[g])}function ii({sessionId:e,nonce:t,createSession:n,billingApiUrl:r,telemetry:o,appearance:a,locale:c,loading:s,error:S,onComplete:b,onError:g,onInstrument:m,onDecline:M,onCountryChange:D,onZipChange:u,showPayPal:w=!0,showStripe:ve=!0,enabledPaymentMethods:H,showApplePay:P=!0,showGooglePay:fe=!0,debug:Q=!1,layout:ce,theme:oe,buttonsTheme:Ce,buttonsStyles:He,cardButtonContent:be,cardBackButtonContent:Rt,cardTitleContent:De,showSecurityFooter:Te,onButtonClick:Ae,onBeforeButtonClick:ee,enableAVS:J,cardFieldOrder:L,cardPreFormSlot:me,avsLayout:et,className:Ue,initialErrorMessage:Ye=null,children:te,checkoutMode:T,confirmLabel:ae,renderConfirmButton:Fe,onSessionCompleted:ie}){let j=Nc(r),_e=En(()=>Ls(oe),[oe]),Je=a??_e?.appearance,We=n?"embedded_checkout":"standard_checkout",Se=te?"custom_layout":ce==="buttons"?"buttons_layout":"default_layout",[G,Y]=Et(null),[$,we]=Et(null),Me=At(null),[x,K]=Et(null),I=At(null),[C,nt]=Et(null),St=En(()=>n?Io(n):"",[n]),de=n?`create:${St}`:`session:${e??""}`,ct=C?.gateways?.stripe?"stripe":C?.gateways?.paypal?"paypal":void 0,it=At(new Set),rt=At(de),je=At(de);Vo(()=>{je.current=de,rt.current!==de&&(rt.current=de,it.current.clear())},[de]);let y=Wn(_=>{if(je.current===de){if(xa.has(_.name)){if(it.current.has(_.name))return;it.current.add(_.name)}tt(()=>m?.(_))}},[de,m]),U=jr(y,de),Xe=At(!1),dt=Wn(_=>{if(Xe.current)return;let E=_.gateway||!ct?_:{..._,gateway:ct};y(E)},[y,ct]);Jn(()=>{U({class:"lifecycle",name:"checkout.mount"})},[U]);let[Mt,Bt]=Et(e??""),W=e??Mt,Le=n?"":W,[Wt,wt]=Et(!0),[Ot,Rn]=Et(null),[_n,Zn]=Et("full"),[Jt,cn]=Et(!1),[dn,Ft]=Et(Ye),[vn,bt]=Et(null),[ir,Ht]=Et(null),[sr,Nt]=Et(!1),[zn,ot]=Et(void 0),[_t,xt]=Et(""),[tn,un]=Et(!1),[pn,Un]=Et(!1),[qn,zt]=Et(!1),X=At(0),Pn=At(void 0),[xn,Qn]=Et("loading"),[br,Tr]=Et(0),Tn=At(!1),mn=At(!1),Be=At(!1),Xt=At(null),Dt=En(()=>({checkoutMode:T??_n,layout:te?"unknown":ce==="buttons"?"buttons":"embedded"}),[T,te,_n,ce]),$n=At(b);$n.current=b;let v=At(g);v.current=g;let ut=At(M);ut.current=M,Jn(()=>{jt($)?.setCheckoutContext(Dt),x&&x!==$&&jt(x)?.setCheckoutContext(Dt)},[$,x,Dt]);let qe=At(ie);qe.current=ie;let yn=Wn(_=>{Qn(_),!(_!=="exhausted"||Be.current)&&(Be.current=!0,v.current?.(new Kt("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),Ze=Wn(()=>{Qn("retrying"),Tr(_=>_+1)},[]);Jn(()=>{Qn("loading"),Tr(0),Be.current=!1},[W]),Jn(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:Os,checkout_type:We,checkout_layout:Se,billing_api_url:j})},[Se,We,j]);let Ut=En(()=>n?Io(n,!0):"",[n]),lr=En(()=>_t===Ut?zn:void 0,[zn,_t,Ut]),jn=En(()=>n?ka(n,lr):void 0,[n,lr]),Cn=T??jn?.checkoutMode??"full",Zt=En(()=>jn?{...jn,checkoutMode:Cn}:void 0,[jn,Cn]);Jn(()=>{ot(void 0),xt(Ut),Pn.current=void 0,zt(!1)},[Ut]),Jn(()=>{Ft(Ye)},[Ye]);let fn=Wn((_,E,V)=>{tt(()=>{ut.current?.($t(_,E,V))})},[tt]),gn=Wn(async(_,E)=>{Ft(null),Ht(null),Nt(!1),bt("processing");let V=E?.sessionId??_.id,Z=_.gateways?.stripe?"stripe":_.gateways?.paypal?"paypal":void 0,$e=Me.current??I.current,ne=jt($e),B=$e?null:la(j,o,Dt),h={log:q=>{ne?ne.log(q):B?.log(q)},error:q=>{ne?ne.error(q):B?.error(q)},terminal:q=>{ne?ne.terminal(q):B?.terminal(q)},performance:q=>{ne?ne.performance(q):B?.performance(q)},now:()=>ne?.now()??B?.now()??0,elapsed:q=>ne?.elapsed(q)??Math.max(0,(B?.now()??q)-q)},f=h.now(),O=!!(E?.initialAutoProcessingError||E?.initialAutoProcessingPending),pt=!1,vt,d=()=>{pt||(pt=!0,O=!0,vt=h.now(),h.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),h.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},p=!1,k=()=>{p||(p=!0,h.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),h.performance({stage:"processing",durationMs:h.elapsed(f),durationMode:"machine",paymentMethodCategory:"saved"}),vt!==void 0&&h.performance({stage:"recovery",durationMs:h.elapsed(vt),durationMode:"machine",paymentMethodCategory:"saved"}))};h.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),Xe.current=!0;try{h.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"})}finally{Xe.current=!1}U({class:"lifecycle",name:"payment.processing.started",provider:Z}),O&&d();let Ee;try{let q=ls(E?.initialAutoProcessingError),F;if(q)d(),q.type==="paypal_redirect_required"&&Xt.current?.publishableKey&&Ns({sessionId:V,publishableKey:Xt.current.publishableKey,paypalPublishableKey:Xt.current.paypalPublishableKey}),F=await ea(q,{flopay:Me.current,paypalFlopay:I.current,attempt3DS:E?.attempt3DS,billingApiUrl:j,sessionId:V,session:_,telemetry:!1}),q.type==="paypal_redirect_required"&&Xa();else if(E?.initialAutoProcessingPending){let se=(await new ia(j,{telemetry:!1}).waitForCheckoutSessionCompletion(E.initialAutoProcessingPending.sessionId,{initialDelayMs:E.initialAutoProcessingPending.retryAfterMs})).data.session;if(!zr(se))throw $o(se);F=kr(se,V)}else{if(E?.initialAutoProcessingError)throw yr(E.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:E.initialAutoProcessingError.checkoutMethod});if(E?.fromCreateSession)return E?.fallbackToFull&&(Zn("full"),Ds("full")),!1;{let Ge=await Hr({billingApiUrl:j,sessionId:V,session:_,telemetry:!1});Ge.type==="success"?F=Ge.result:(d(),Ge.type==="paypal_redirect_required"&&Xt.current?.publishableKey&&Ns({sessionId:V,publishableKey:Xt.current.publishableKey,paypalPublishableKey:Xt.current.paypalPublishableKey}),F=await ea(Ge,{flopay:Me.current,paypalFlopay:I.current,attempt3DS:E?.attempt3DS,billingApiUrl:j,sessionId:V,session:_,telemetry:!1}),Ge.type==="paypal_redirect_required"&&Xa())}}V&&Vr(V),k(),O&&(h.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),h.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),h.terminal({outcome:F.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),Nt(F.status==="authorized"),bt("success"),await wo(1200),Ee=()=>$n.current?.(F)}catch(q){let F=Rr(q),Ge=F.checkoutMethod??Po;Ft(F.message),Ht(F.message),Nt(!1),E?.fallbackToFull&&(h.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),Zn("full"),Ds("full")),k();let Qe=F.statusCode!==void 0?Oc(F.statusCode,"unknown"):void 0,se=Qe==="4xx"?{requestCategory:"process_payment",statusClass:Qe}:{},ue=Qe===void 0||Qe==="4xx";if(ue&&(F.telemetryOutcome==="payment_declined"||!!(F.declineCode||F.code?.toLowerCase().includes("declin"))))h.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...se});else if(ue&&(F.telemetryOutcome==="validation_rejected"||F.type==="validation_error"))h.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...se});else{let st=Ms(q,O?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown"),Lt=F.telemetryRequestCategory??"process_payment";Xe.current=!0;try{h.error({...st,...F.telemetryFailureCategory?{failureCategory:F.telemetryFailureCategory}:{},stage:O?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:Lt})}finally{Xe.current=!1}U({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:Lt,provider:Z})}return tt(()=>v.current?.(F)),fn(Ge,F,{code:F.code,declineCode:F.declineCode}),bt("error"),await Promise.allSettled([wo(1500),E?.ensureProvidersReady?E.ensureProvidersReady():Promise.resolve()]),O&&(h.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),h.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{k(),B&&ko(B),bt(null),Ht(null)}return tt(Ee),!0},[fn,U,tt,Rr,j,o,Dt]);Jn(()=>{if(typeof window>"u"||mn.current)return;let _=new URLSearchParams(window.location.search),E=_.get("payment_intent_client_secret");if(!E)return;let V=qc();V&&(mn.current=!0,(async()=>{let Z,$e=0;Ft(null),Ht(null),bt("processing"),cn(!0);try{if(_.get("redirect_status")==="failed")throw Object.assign(new Kt("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:ne,paypalFlopay:B}=await na({publishableKey:V.publishableKey,paypalPublishableKey:V.paypalPublishableKey,billingApiUrl:j,locale:c,telemetry:o});Z=jt(B??ne),$e=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 h=(B??ne)?.getRawProvider();if(!h)throw Object.assign(new Kt("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:f,error:O}=await h.retrievePaymentIntent(E);if(O)throw Object.assign(new Kt(O.message??"Failed to retrieve PayPal payment status.","api_error",{code:O.code}),{checkoutMethod:"paypal"});let pt=Vi(f?.status);if(!f||pt==="failed")throw Object.assign(new Kt("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let vt=typeof f.payment_method=="string"?f.payment_method:f.payment_method?.id,d=pt;if(V.sessionId){let Ee=(await new ia(j,{telemetry:!1}).getUnifiedCheckoutSession(V.sessionId)).data.session;if(Ee&&Ee.status!=="complete"){let q=await Hr({billingApiUrl:j,sessionId:V.sessionId,session:Ee,telemetry:!1,tokenizedData:{id:vt??f.id,type:"card",threeDSecureActionResultTokenId:f.id,isPaypal:!0}});if(q.type!=="success")throw Object.assign(new Kt("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});d=q.result.status}}V.sessionId&&Vr(V.sessionId),Z?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),Z?.performance({stage:"redirect_resume",durationMs:Z.elapsed($e),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),Z?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),bt("success"),await wo(1200),tt(()=>$n.current?.({status:d,paymentIntentId:f.id,paymentMethodId:vt,checkoutMethod:"paypal"}))}catch(ne){let B=Rr(ne),h=B.checkoutMethod??"paypal",f=!!(B.declineCode||B.code?.toLowerCase().includes("declin"));if(Z)Z.performance({stage:"redirect_resume",durationMs:Z.elapsed($e),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),f?Z.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):Z.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(f){let O=la(j,o,Dt);O.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),ko(O)}else Wa(j,o,Dt,"REDIRECT_RESUME_FAILED","redirect_resume");Ft(B.message),Ht(B.message),tt(()=>v.current?.(B)),fn(h,B,{code:B.code,declineCode:B.declineCode}),bt("error"),await wo(1500)}finally{Xa(),$c(),bt(null),Ht(null),cn(!1)}})())},[fn,tt,c,Rr,j,o]);let xe=At(null),kt=En(()=>Zt?Io(Zt):"",[Zt]),Tt=At(Zt);Tt.current=Zt,Jn(()=>{Bt(e??"")},[e]),Jn(()=>{Tn.current=!1,Ft(Ye),Ht(null),Nt(!1),bt(null)},[kt,Ye,e]);async function An(_,E,V){let Z=la(j,o,Dt),$e=new ia(j,{telemetry:!1}),ne=!1;try{let B=_.idempotencyKey!==void 0?Bs(_.idempotencyKey):void 0,h=zs(E,V),f=Us(E,V);h?.canonicalIdentity===V&&f&&f.canonicalIdentity===void 0&&(Qa(E,V,f.idempotencyKey),f={...f,canonicalIdentity:V});let O=B??(f?.canonicalIdentity===V?f.idempotencyKey:void 0),pt,vt=!1;Z.log({name:h?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let d=h?.sid??null,p=null,k,Ee,q=!1;if(d)try{p=await $e.getUnifiedCheckoutSession(d,h?.nonce),h&&h.canonicalIdentity===void 0&&(Vc(p.data.session,_)?(Za(E,V,d,h.nonce??p.data.session?.clientSecret),f&&f.canonicalIdentity===void 0&&(Qa(E,V,f.idempotencyKey),O??(O=f.idempotencyKey))):(ei(E,V),f=null,O=B,d=null,p=null));let F=p?.data.session?.status;if(d&&p&&F==="complete"){if(Fa(d))return{sid:d,result:p};ei(E,V),d=null,p=null,vt=!0}}catch{Z.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),h?.canonicalIdentity===void 0?(ei(E,V),O=B):ri(E,V),d=null}if(!d){!B&&(vt||!O)&&(O=Bs(),pt=O),O&&Qa(E,V,O);let F=Z.now(),Ge=0;Z.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let Qe={..._,idempotencyKey:O,avsCheck:!!J,avsConfig:typeof J=="object"?J:void 0,checkoutType:"embedded_checkout",checkoutLayout:te?"custom_layout":ce==="buttons"?"buttons_layout":"default_layout"};Object.defineProperty(Qe,Ac,{configurable:!1,enumerable:!1,value:{onAttempt:A=>{Ge=Math.max(Ge,A)}}});let se=()=>{Z.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:"2xx"}),Z.performance({stage:"session_create",durationMs:Z.now()-F,durationMode:"machine",requestCategory:"session_create",attempt:Ge,statusClass:"2xx"})},ue=A=>{let le=Ms(A,"CHECKOUT_SESSION_CREATE_FAILED","unknown");Z.performance({stage:"session_create",durationMs:Z.now()-F,durationMode:"machine",requestCategory:"session_create",attempt:Ge,statusClass:le.statusClass}),A instanceof Kt&&A.type==="validation_error"?Z.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown"}):le.statusClass==="4xx"?Z.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create",statusClass:"4xx"}):(Z.error({...le,stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create"}),U({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_create"}))};try{if(Fc(Qe)){let A=await $e.createDetachedSession(Qe);A.claimed.catch(()=>{}),p=A.shell,d=A.sessionId,Ee=A.claim,q=!Qe.account.email?.trim(),k=A.claimed.then(le=>{let st=le.data.session?.id??A.sessionId;return st&&Za(E,V,st,le.data.session?.clientSecret??A.nonce),se(),le},le=>{throw ri(E,V),ue(le),le}).finally(()=>ko(Z)),k.catch(()=>{}),ne=!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()-F,durationMode:"machine",requestCategory:"session_create",attempt:Ge,statusClass:"2xx",paymentMethodCategory:"card"})}else p=await $e.createAndFetchSession(Qe),se()}catch(A){throw ue(A),A}d=p.data.session?.id??d??"",d&&!k&&Za(E,V,d,p.data.session?.clientSecret)}return{sid:d??"",result:p,sdkGeneratedIdempotencyKey:pt,...k?{claimed:k}:{},...Ee?{claim:Ee}:{},...q?{claimRequiresIdentity:!0}:{}}}finally{ne||ko(Z)}}let hn=Wn(async(_,E)=>{let V=Tt.current;if(!V)throw new Kt("createSession is required to bootstrap checkout.","validation_error");let Z=ka(V,_),$e=Io(Z),ne=Kc(Z),B=ca.get($e);if(!B){let O={canonicalIdentity:$e,promise:An(Z,ne,$e),consumers:0,settled:!1};B=O,ca.set($e,O);let pt=()=>{O.settled=!0,Fs($e,O)};O.promise.then(pt,pt)}B.consumers+=1;let h=!1,f=()=>{h||(h=!0,B.consumers-=1,Fs($e,B))};E?.(f);try{let O=await B.promise;xe.current=$e,_&&(xt(Ut),ot(Qe=>$i(Qe,_)));let{sid:pt,result:vt,claimed:d,claim:p,claimRequiresIdentity:k}=O;if(Pn.current=p,zt(k===!0),Y(vt),vt.data.session&&nt(vt.data.session),pt&&Bt(pt),d){X.current+=1;let Qe=X.current;Un(!0),d.then(se=>{X.current===Qe&&(Y(se),se.data.session&&nt(se.data.session),Un(!1),zt(!1))},se=>{X.current===Qe&&(Un(!1),zt(!1),Rn(se instanceof Kt?se:new Kt(se instanceof Error?se.message:"Failed to create session","api_error")))})}else X.current+=1,Un(!1),zt(!1);let{publishableKey:Ee,paypalPublishableKey:q}=ta(vt),{flopay:F,paypalFlopay:Ge}=await na({publishableKey:Ee,paypalPublishableKey:q,billingApiUrl:j,locale:c,telemetry:o});return Me.current=F,we(F),I.current=Ge,K(Ge),wt(!1),O}catch(O){throw xe.current===$e&&(xe.current=null),O}finally{E||f()}},[Ut,c,j,o,Dt]),Mn=At(gn);Mn.current=gn;let Bn=At(hn);Bn.current=hn;let qt=Wn(async _=>{if(!jc(_)||tn)return{sessionId:Mt,session:C};un(!0);try{let E=await hn(_);return{sessionId:E.sid,session:E.result.data.session??null}}finally{un(!1)}},[hn,tn,Mt,C]),on=Wn(async _=>{let E=Pn.current;E&&await E(_)},[]);Jn(()=>{let _=!1,E;if(Rn(null),kt){let $e=Tt.current;return Zn(Cn),wt(!1),xe.current===kt?()=>{_=!0}:(nt(ji($e,T)),(async()=>{let ne=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),B=Cn==="auto"&&!Tn.current&&!ne;B&&(Ft(null),Ht(null),bt("processing"));try{let h=await Bn.current(void 0,vt=>{E=vt}),f=h.result.data.session??null;Xt.current=ta(h.result);let O=Ja(h.result),pt=Fa(h.sid||f?.id);if(!_&&B&&f&&!O&&!pt){Tn.current=!0,await zc(kt,h.sdkGeneratedIdempotencyKey,()=>Mn.current(f,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:h.result.autoProcessingError,initialAutoProcessingPending:h.result.autoProcessingPending,autoProcessingAttempted:h.result.autoProcessingAttempted,sessionId:h.sid||f.id}));return}!_&&B&&((O||pt)&&(Tn.current=!0),bt(null),Ht(null))}catch(h){if(_)return;let f=h instanceof Kt||typeof h=="object"&&h!==null&&"code"in h?h.code:void 0;if(B&&f==="session_auto_completed"){Tn.current=!0,bt("success"),await wo(1200),_||(tt(()=>{$n.current?.({status:"succeeded"})}),bt(null),Ht(null));return}B&&(bt(null),Ht(null));let O=h instanceof Kt?h:new Kt(h instanceof Error?h.message:"Failed to create session","api_error");Rn(O)}finally{E?.(),E=void 0}})(),()=>{_=!0,E?.()})}wt(!0);async function V(){let $e=!1;try{let B=await new ia(j,{telemetry:!1}).getUnifiedCheckoutSession(W,t);if(_)return;Y(B);let h=B.data.session??null;if(nt(h),!h)throw new Kt("No session data returned","api_error");let f=h.checkoutMode;if(f==="setup")throw new Kt("This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.","validation_error",{code:"InvalidCardSetupSurface",param:"sessionId"});if(h.status==="authorized"){wt(!1),tt(()=>{$n.current?.(kr(h,W)),qe.current?.(h.successUrl??"")});return}if(h.status==="complete"){wt(!1),tt(()=>{qe.current?.(h.successUrl??"")});return}if(h.status==="expired")throw qo(h);$e=!0;let O=T??f??"full";Zn(O);let pt=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),vt=Ja(B);if(O==="auto"&&!Tn.current&&!pt&&!vt){Tn.current=!0;let d=Z(B);try{if(await Mn.current(h,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>d,sessionId:W||h.id}),_)return;await d,_||wt(!1);return}catch{if(_)return;await d,_||wt(!1);return}}await Z(B),_||wt(!1)}catch(ne){if(_)return;$e&&U({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"}),ne instanceof Kt?!$e&&!Uc(ne)&&Wa(j,o,Dt,"NETWORK_REQUEST_FAILED","session_read"):Wa(j,o,Dt,"INTERNAL_SDK_ERROR","checkout_mount");let B=ne instanceof Kt?ne:new Kt(ne instanceof Error?ne.message:"Failed to initialize checkout","api_error");Rn(B),wt(!1)}}async function Z($e){let{publishableKey:ne,paypalPublishableKey:B}=ta($e);Xt.current={publishableKey:ne,paypalPublishableKey:B};let{flopay:h,paypalFlopay:f}=await na({publishableKey:ne,paypalPublishableKey:B,billingApiUrl:j,locale:c,telemetry:o});Me.current=h,we(h),I.current=f,K(f)}return V(),()=>{_=!0}},[T,kt,Cn,Le,tt,t]);let an=Wn(async()=>{if(!(Jt||!C)){cn(!0),Ft(null);try{await gn(C,{attempt3DS:!0,fallbackToFull:!0,sessionId:W||C.id})}finally{cn(!1)}}},[W,Jt,gn,C]),er=ni(G),Ar=Ja(G),Fn=En(()=>{if(!(!G||!C||!G.data.stripe?.publishableKey))return{billingApiUrl:j}},[G,C,j]),Kn=!!(n&&!te&&ce==="buttons"&&ee&&Cn==="full"),Qt=En(()=>({session:C,loading:Wt,error:Ot,checkoutMode:_n,inlineSessionDraft:Zt,applyInlineSessionPatch:Kn?qt:void 0,inlineSessionPatchProcessing:tn,claimPending:pn,claimRequiresIdentity:qn}),[C,Wt,Ot,_n,Zt,Kn,qt,tn,pn,qn]),at=!!n&&ce==="buttons"&&!Ar&&(!$||!Fn),Yt=vn?re(Yn,{status:vn,errorMessage:ir,authorized:sr}):null;if(Wt){if(s)return Vt(Xn,{children:[s,Yt]});if(ce==="buttons"){let _=_e?.buttonsLayout?.cardButton?.borderRadius??_e?.appearance.variables?.borderRadius??8,E=V=>re("div",{style:{height:V,borderRadius:_,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return Vt(Xn,{children:[Vt("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[w&&E(Gr),ve&&(P||fe)&&E(Gr),ve&&E(Gr),re("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),Yt]})}return Vt(Xn,{children:[Vt("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); } }"})]}),Yt]})}return Ot?S?re(Ln.Provider,{value:Qt,children:S(Ot)}):re(Ln.Provider,{value:Qt,children:re("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:Ot.message})}):at?Vt(Xn,{children:[re(Ln.Provider,{value:Qt,children:re(Yc,{onButtonClick:Ae,showPayPal:w,showStripe:ve,showApplePay:P,showGooglePay:fe,theme:oe,buttonsTheme:Ce,buttonsStyles:He,cardButtonContent:be,cardBackButtonContent:Rt,cardTitleContent:De})}),Yt]}):Ar&&C&&er?Vt(Xn,{children:[re(Ln.Provider,{value:Qt,children:Vt("div",{className:Ue,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[dn&&re(Kr,{icon:!1,children:dn}),xn==="retrying"&&re("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),xn==="exhausted"&&Vt("div",{role:"alert",children:[re("div",{children:"PayPal is temporarily unavailable. Please try again."}),re("button",{type:"button",onClick:Ze,children:"Retry PayPal"})]}),xn!=="exhausted"&&re("div",{"aria-hidden":xn==="retrying"?!0:void 0,style:xn==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:re(ts,{sessionId:W,nonce:C.clientSecret||void 0,billingApiUrl:j,email:C.customer?.email,clientId:er.clientId,environment:er.environment,currency:(C.currency??"usd").toUpperCase(),isSubscription:C.mode==="subscription",providerObjectType:er.providerObjectType,onComplete:b,onErrorChange:Ft,onDecline:M,onButtonClick:Ae,onInitializationStateChange:yn,allowAutomaticRetry:br===0,session:C,telemetry:o,telemetryContext:Dt,onInstrument:dt,debug:Q},`${de}:paypal-init-${br}`)})]})}),Yt]}):!$||!Fn?re(Xn,{children:Yt}):_n==="confirm"?Vt(Xn,{children:[re(Ln.Provider,{value:Qt,children:re(Xo,{flopay:$,paypalFlopay:x,options:Fn,onInstrument:dt,children:Vt("div",{className:Ue,children:[dn&&re("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:dn}),Fe?Fe({onConfirm:an,isProcessing:Jt}):re("button",{type:"button",onClick:an,disabled:Jt,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:Jt?"not-allowed":"pointer",opacity:Jt?.6:1},children:Jt?"Processing...":ae??"Confirm Purchase"})]})},de)}),Yt]}):Vt(Xn,{children:[re(Ln.Provider,{value:Qt,children:re(Xo,{flopay:$,paypalFlopay:x,options:Fn,onInstrument:dt,children:te?Vt(Xn,{children:[dn&&re("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:dn}),re(Hc,{sessionId:W,nonce:C?.clientSecret||void 0,billingApiUrl:j,session:C,children:te})]}):re(Ya,{sessionId:W,nonce:C?.clientSecret||void 0,email:C?.customer?.email||Zt?.account?.email,userId:C?.customer?.id||Zt?.account?.userId,firstName:C?.customer?.firstName||Zt?.account?.firstName,lastName:C?.customer?.lastName||Zt?.account?.lastName,totalAmount:C?Math.round(Mc(C).total*100):0,currency:C?.currency?.toLowerCase()??"usd",onComplete:b,onError:g,onDecline:M,error:dn,onErrorChange:Ft,showPayPal:w,showStripe:ve,enabledPaymentMethods:H??G?.data.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:G?.data.stripe?.enabledPaymentMethodCountries,showApplePay:P,showGooglePay:fe,layout:ce,theme:oe,buttonsTheme:Ce,buttonsStyles:He,appearance:Je,cardButtonContent:be,cardBackButtonContent:Rt,cardTitleContent:De,onButtonClick:Ae,onBeforeButtonClick:ee,onBuyerIdentityReady:on,enableAVS:J,...L?{cardFieldOrder:L}:{},...me?{cardPreFormSlot:me}:{},avsLayout:et,country:C?.customer?.country,city:C?.customer?.city,state:C?.customer?.state,onCountryChange:D,onZipChange:u,avsCheck:!!J,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:te?"custom_layout":ce==="buttons"?"buttons_layout":"default_layout",className:Ue,directPaypal:ni(G),isSubscription:C?.mode==="subscription",session:C,dataAttachmentPending:pn,dataAttachmentRequiresIdentity:qn,debug:Q})},de)}),Yt]})}function Hc({sessionId:e,nonce:t,billingApiUrl:n,session:r,children:o}){return re(Xn,{children:Ga.Children.map(o,a=>{if(!Ga.isValidElement(a))return a;let c=a.props,s={};return c.sessionId||(s.sessionId=e),!c.nonce&&t&&(s.nonce=t),c.billingApiUrl||(s.billingApiUrl=n),r?.customer&&(c.email||(s.email=r.customer.email),c.userId||(s.userId=r.customer.id),c.firstName||(s.firstName=r.customer.firstName),c.lastName||(s.lastName=r.customer.lastName)),Object.keys(s).length===0?a:Ga.cloneElement(a,s)})})}function Yc({onButtonClick:e,showPayPal:t,showStripe:n=!0,showApplePay:r,showGooglePay:o,theme:a,buttonsTheme:c,buttonsStyles:s,cardButtonContent:S,cardBackButtonContent:b,cardTitleContent:g}){let[m,M]=Et(!1),D=En(()=>Ls(a),[a]),u=En(()=>{let P=D?.buttonsLayout??Dc(c);return s?{...P,...s,cardButton:{...P.cardButton,...s.cardButton},cardFormContainer:{...P.cardFormContainer,...s.cardFormContainer},backButton:{...P.backButton,...s.backButton},backButtonIcon:{...P.backButtonIcon,...s.backButtonIcon},submitButton:{...P.submitButton,...s.submitButton},title:{...P.title,...s.title}}:P},[D,c,s]),w=D?.buttonsLayout?.cardButton?.borderRadius??D?.appearance.variables?.borderRadius??8,ve=P=>re("div",{style:{height:P,borderRadius:w,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),H=S===void 0?{boxSizing:"border-box",height:Gr,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(m){let P=u.cardInputBorder??"#e5e7eb",fe=u.cardInputBackground??"white",Q=Nr(b),ce=Nr(g);return Vt("div",{style:{backgroundColor:u.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",...u.cardFormContainer},children:[Vt("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[Vt("button",{type:"button",onClick:()=>M(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:Q?0:"0.5rem",background:"none",border:"none",color:"#4b5563",fontSize:"0.85rem",fontWeight:500,padding:0,flexShrink:0,opacity:1,cursor:"pointer",...u.backButton},children:[re("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...u.backButtonIcon},children:re("svg",{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(Lr,{content:b})]}),ce?re("div",{style:{flex:1}}):re("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...u.title},children:re(mo,{content:g})})]}),re("div",{style:{backgroundColor:fe,border:`1px solid ${P}`,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"}})}),Vt("div",{style:{display:"flex"},children:[re("div",{style:{flex:1,backgroundColor:fe,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${P}`,borderLeft:`1px solid ${P}`,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:fe,borderTop:"none",borderRight:`1px solid ${P}`,borderBottom:`1px solid ${P}`,borderLeft:`1px solid ${P}`,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:fe,border:`1px solid ${P}`,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",...u.submitButton,opacity:.5}}),re("style",{children:`
33
+ `}),oo&&dn&&De("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:f?-2:0},children:[De("button",{type:"button",onClick:Xn,style:{display:"inline-flex",alignItems:"center",gap:ya?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:p.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...p.backButton},"aria-label":"Back to payment methods",children:[u("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...p.backButtonIcon},children:u("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:u("path",{d:"M15 18l-6-6 6-6"})})}),u(Fr,{content:Ie})]}),Ii?u("div",{style:{flex:1}}):u("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:p.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...p.title},children:u(co,{content:Re})})]}),!oo&&!Ii&&u("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:fa,order:f?-3:0,...p.title},children:u(co,{content:Re})}),f&&he&&u("div",{"data-testid":"flopay-vault-identity-fields",style:{order:-1,marginTop:"0.5rem"},children:u("div",{style:{backgroundColor:Tr,border:`1px solid ${xr}`,borderRadius:St,padding:"10px"},children:u("input",{className:"flopay-shared-input",id:"flopay-buyer-email",name:"email",type:"email",autoComplete:"email","aria-label":"Email address",placeholder:"Email address",value:Oe,onChange:i=>{rr.current=i.target.value,Fn(i.target.value)},onBlur:oa,disabled:L,required:!0,"data-testid":"flopay-email",style:{width:"100%",border:"none",outline:"none",background:"transparent",...ga}})})}),Q&&u("div",{style:{order:f?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let i=$e,I=(U=!1)=>({backgroundColor:Tr,border:`1px solid ${gr(U)}`,borderRadius:St,marginTop:"0.5rem",padding:"10px"}),z=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...ga}),ye=nc(i);return De(Hr,{children:[Ue(Q.address_line_1,i)&&u("div",{style:I(nn.line1),children:u("input",{className:"flopay-shared-input",id:"flopay-billing-address-line1",name:"billing-address-line1",placeholder:"Street Address (e.g. 123 Main St)",autoComplete:"billing address-line1",value:mn,onChange:U=>{Ut.current.addressLine1=!0,fn.current=U.target.value,En(U.target.value)},disabled:L,required:!0,"data-testid":"flopay-address-line1",style:z()})}),Ue(Q.address_line_2,i)&&u("div",{style:I(),children:u("input",{className:"flopay-shared-input",id:"flopay-billing-address-line2",name:"billing-address-line2",placeholder:"Apt, Suite, Unit (optional)",autoComplete:"billing address-line2",value:Mn,onChange:U=>{Ut.current.addressLine2=!0,ln.current=U.target.value,en(U.target.value)},disabled:L,"data-testid":"flopay-address-line2",style:z()})}),(Ue(Q.city,i)||Ue(Q.state,i))&&De("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[Ue(Q.city,i)&&u("div",{style:{flex:1,backgroundColor:Tr,borderTop:`1px solid ${gr(nn.city)}`,borderRight:`1px solid ${gr(nn.city)}`,borderBottom:`1px solid ${gr(nn.city)}`,borderLeft:`1px solid ${gr(nn.city)}`,padding:"10px",borderTopLeftRadius:St,borderBottomLeftRadius:St,...Ue(Q.state,i)?{borderRight:"none",borderTopRightRadius:0,borderBottomRightRadius:0}:{borderRadius:St}},children:u("input",{className:"flopay-shared-input",id:"flopay-billing-city",name:"billing-city",placeholder:"City",autoComplete:"billing address-level2",value:_n,onChange:U=>{Ut.current.city=!0,gn.current=U.target.value,Gt(U.target.value)},disabled:L,required:!0,"data-testid":"flopay-city",style:z()})}),Ue(Q.state,i)&&u("div",{style:{flex:1,backgroundColor:Tr,border:`1px solid ${gr(nn.state)}`,padding:"10px",borderTopRightRadius:St,borderBottomRightRadius:St,...Ue(Q.city,i)?{borderTopLeftRadius:0,borderBottomLeftRadius:0}:{borderRadius:St}},children:ye?De("select",{id:"flopay-billing-state",name:"billing-state",value:et,onChange:U=>{Ut.current.state=!0,Bt.current=U.target.value,yn(U.target.value)},disabled:L,autoComplete:"billing address-level1",required:!0,"data-testid":"flopay-state",style:{...z(),cursor:"pointer"},children:[u("option",{value:"",children:ds(i)}),ye.map(U=>u("option",{value:U.code,children:U.name},U.code))]}):u("input",{className:"flopay-shared-input",id:"flopay-billing-state",name:"billing-state",placeholder:ds(i),autoComplete:"billing address-level1",value:et,onChange:U=>{Ut.current.state=!0,Bt.current=U.target.value,yn(U.target.value)},disabled:L,required:!0,"data-testid":"flopay-state",style:z()})})]}),(Ue(Q.country,i)||Ue(Q.postal_code,i))&&De("div",{style:{display:"flex",flexDirection:Pe==="column"?"column":"row",gap:Pe==="column"?"0.5rem":"0",marginTop:"0.5rem"},children:[Ue(Q.country,i)&&u("div",{style:{flex:Pe==="row"?1:void 0,backgroundColor:Tr,borderTop:`1px solid ${xr}`,borderRight:`1px solid ${xr}`,borderBottom:`1px solid ${xr}`,borderLeft:`1px solid ${xr}`,padding:"10px",...Pe==="row"&&Ue(Q.postal_code,i)?{borderRadius:"0",borderTopLeftRadius:St,borderBottomLeftRadius:St,borderRight:"none"}:{borderRadius:St}},children:u("select",{id:"flopay-billing-country",name:"billing-country",value:$e,onChange:U=>{Ut.current.country=!0,Ht.current=U.target.value,Vt(U.target.value),We?.(U.target.value),Bt.current="",yn("")},disabled:L,autoComplete:"billing country","data-testid":"flopay-country",style:{...z(),cursor:"pointer"},children:Zl.map(U=>De("option",{value:U.code,children:[U.flag," ",U.name]},U.code))})}),Ue(Q.postal_code,i)&&u("div",{style:{flex:Pe==="row"?1:void 0,backgroundColor:Tr,border:`1px solid ${Xs}`,padding:"10px",...Pe==="row"&&Ue(Q.country,i)?{borderRadius:"0",borderTopRightRadius:St,borderBottomRightRadius:St}:{borderRadius:St}},children:u("input",{className:"flopay-shared-input",id:"flopay-billing-postal-code",name:"billing-postal-code",placeholder:Da($e),autoComplete:"billing postal-code",value:Ot,onChange:U=>{Ut.current.zip=!0,zt.current=U.target.value,xt(U.target.value),nt?.(U.target.value)},onBlur:()=>Wn(!0),disabled:L,required:Wt.required,"aria-invalid":To||void 0,"aria-describedby":To?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:z()})})]}),To&&u("div",{id:"flopay-billing-postal-code-error",role:"alert","data-testid":"flopay-zip-error",style:{marginTop:"0.375rem",color:pa,...ga,fontSize:"0.75rem"},children:Wt.empty?`${Da(i)} is required`:Sc(i)})]})})()}),f&&Ne&&u("div",{style:{order:-2,width:"100%"},children:Ne}),f&&nl,s&&u($r,{margin:"0.75rem 0",styleOverride:p.errorBanner,children:s})]}),Bo={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"},Ti=i=>pt?!ge||!Un?u("pre",{"data-testid":i,style:Bo,children:"FloPay/DirectPayPal-debug - not enabled"}):u("pre",{"data-testid":i,style:Bo,children:["FloPay/DirectPayPal-debug (parent gate)",` showPayPal=${ge}`,` directPaypalConfigured=${Un}`,` inAppBrowserDetected=${String(_o)}`,` shouldRenderDirectPayPal=${eo}`,` shouldRenderStripePayPal=${to}`,` hasPaypalStripeInstance=${!!Nn}`].join(`
34
+ `)}):null,Bi=i=>pt?!V||!Mt?u("pre",{"data-testid":i,style:Bo,children:"FloPay/Stripe-debug - not enabled"}):u("pre",{"data-testid":i,style:Bo,children:["FloPay/Stripe-debug (parent gate)",` showStripe=${V}`,` currency=${Ce}`,` amountInCents=${ft}`,` enabledPaymentMethods: ${JSON.stringify(C??[])}`,` enabledPaymentMethodsProvided=${Zr}`,` hasEnabledMethods=${ko}`,` expressMethods: ${JSON.stringify(Io)}`,` walletExpressMethods: ${JSON.stringify(Ro)}`,` paymentElementMethods: ${JSON.stringify(Qr)}`,` paymentElementMethodsForCurrency: ${JSON.stringify(Eo)}`,` hasStripeInstance=${!!Mt}`,` shouldRenderWallets=${no}`,` shouldRenderPaymentElement=${ro}`].join(`
35
+ `)}):null,Ai=ae==="apm-expanding"||ae==="apm-form"||ae==="apm-collapsing",Ao=ae==="apm-expanding"?`flopay-card-enter ${Xt}ms cubic-bezier(0, 0, 0.2, 1) both`:ae==="apm-collapsing"?`flopay-card-exit ${Xt}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0,Mo=bt?{...sa,paymentMethodTypes:[bt]}:null;if(de==="buttons"){let i=ae==="buttons"||ae==="expanding"||ae==="apm-expanding",I=ae==="expanding"||ae==="card"||ae==="collapsing",z=Le===void 0?{boxSizing:"border-box",height:Jo,padding:"0 1rem"}:{padding:"0.9rem 1rem"},ye=ae==="expanding"||ae==="apm-expanding"?`flopay-buttons-exit ${Xt}ms cubic-bezier(0.4, 0, 0.2, 1) both`:ae==="collapsing"||ae==="apm-collapsing"?`flopay-buttons-enter ${Xt}ms cubic-bezier(0, 0, 0.2, 1) both`:void 0,U=ae==="expanding"?`flopay-card-enter ${Xt}ms cubic-bezier(0, 0, 0.2, 1) both`:ae==="collapsing"?`flopay-card-exit ${Xt}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0;return De("form",{onSubmit:da,className:A,style:{position:"relative"},children:[u(Fa,{}),un&&u(qn,{status:un,errorMessage:s,authorized:hn}),De("div",{style:{display:"grid"},children:[De("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!i&&!ye?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!i&&!ye?vc:{},...ye?{animation:ye,pointerEvents:"none"}:{}},children:[Ti("flopay-direct-paypal-gate-debug"),Bi("flopay-stripe-gate-debug"),eo&&R&&De(Hr,{children:[Ct&&u("div",{"data-testid":"flopay-paypal-direct-retry-notice",style:{padding:"8px 10px",background:"#fef3c7",border:"1px solid #fcd34d",borderRadius:6,color:"#78350f",fontSize:13,lineHeight:1.4},children:"Please confirm your PayPal payment to complete checkout."}),u(jo,{sessionId:e,nonce:t,billingApiUrl:T,email:k.email,billingName:O||void 0,onBuyerIdentityReady:y,clientId:R.clientId,environment:R.environment,currency:Ce.toUpperCase(),isSubscription:G,providerObjectType:R.providerObjectType,onTokenizedBody:Sn,onComplete:a,onErrorChange:ue,onDecline:l,onTechnicalFailure:_r,onButtonClick:oe,runBeforeButtonClick:Tn,isProcessing:L,onLoadStateChange:la,onInitializationStateChange:ca,session:_??null,existingOrderId:Ct?.orderId,debug:pt},Ct?.orderId??"fresh")]}),to&&u(Ir,{stripe:Nn,options:ai,children:u(bs,{sessionId:e,nonce:t,email:k.email,billingName:O||void 0,onBuyerIdentityReady:y,billingApiUrl:T,onTokenizedBody:Sn,onErrorChange:ue,isProcessing:L,onButtonClick:oe,onDecline:l,onTechnicalFailure:_r,runBeforeButtonClick:Tn,onLoadStateChange:di,placeholderBorderRadius:hr})}),no?u(Ir,{stripe:Mt,options:oi,children:u(vs,{sessionId:e,nonce:t,email:k.email,billingName:O||void 0,onBuyerIdentityReady:y,billingApiUrl:T,intentKind:q>0?"payment":"setup",expressMethods:Ro,onTokenizedBody:Sn,onErrorChange:ue,onButtonClick:oe,onDecline:l,onTechnicalFailure:_r,runBeforeButtonClick:Tn,onLoadStateChange:pi,placeholderBorderRadius:hr})}):hi?u("div",{style:{height:Jo,borderRadius:hr,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,ro&&u(Ps,{sessionId:e,nonce:t,email:k.email,billingName:[k.firstName,k.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:y,billingApiUrl:T,paymentElementMethods:Eo,stripeInstance:Mt,paymentElementBaseOptions:sa,onTokenizedBody:Sn,onErrorChange:ue,onButtonClick:oe,onDecline:l,runBeforeButtonClick:Tn,onLoadStateChange:yi,isProcessing:L,submitButtonColor:br,submitButtonBorderRadius:St,submitButtonStyle:p.submitButton,onExpandApm:Ln,expandedApmMethod:bt,themeId:ve,buttonAppearance:{backgroundColor:p.cardButton?.backgroundColor,borderColor:p.cardInputBorder,textColor:p.cardButton?.color,borderRadius:hr}}),f&&u("button",{type:"button",onClick:async()=>{L||!(await Tn("card")).proceed||(oe?.("card"),fr())},disabled:L,style:{width:"100%",...z,...p.cardButton,...qa({themeBundle:c,resolvedPrimaryColor:br,resolvedBorderRadius:St,submitButtonStyle:p.submitButton,explicitPrimaryColor:an?.colorPrimary}),fontSize:p.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:L?"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:L?.6:1},onMouseEnter:Se=>{!L&&(c||an?.colorPrimary)&&(Se.currentTarget.style.backgroundColor=el)},onMouseLeave:Se=>{(c||an?.colorPrimary)&&(Se.currentTarget.style.backgroundColor=br)},onMouseDown:Se=>{Se.currentTarget.style.transform="scale(0.985)"},onMouseUp:Se=>{Se.currentTarget.style.transform="scale(1)"},children:u(Mr,{content:Le})}),s&&ae==="buttons"&&u($r,{margin:"0.25rem 0",styleOverride:p.errorBanner,children:s})]}),f&&I&&u("div",{style:{gridArea:"1 / 1",...U?{animation:U}:{},...ae==="collapsing"?{pointerEvents:"none"}:{}},children:xi}),V&&Ai&&bt&&Mo&&Mt&&u("div",{style:{gridArea:"1 / 1",...Ao?{animation:Ao}:{},...ae==="apm-collapsing"?{pointerEvents:"none"}:{}},children:De("div",{style:{backgroundColor:ma,borderRadius:ba,...ao,padding:ha},children:[De("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[De("button",{type:"button","data-testid":"flopay-apm-back-button",onClick:Cn,style:{display:"inline-flex",alignItems:"center",gap:ya?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:p.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...p.backButton},"aria-label":"Back to payment methods",children:[u("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...p.backButtonIcon},children:u("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:u("path",{d:"M15 18l-6-6 6-6"})})}),u(Fr,{content:Ie})]}),u("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:p.titleFontSize??"1.05rem",color:fa,paddingRight:80,...p.title},children:`Pay with ${Rr(bt)}`})]}),u(Ir,{stripe:Mt,options:Mo,children:u(Na,{method:bt,sessionId:e,nonce:t,email:k.email,billingName:[k.firstName,k.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:y,billingApiUrl:T,onTokenizedBody:Sn,onErrorChange:ue,onDecline:l,onCancel:Cn,runBeforeButtonClick:Tn,onButtonClick:oe,isProcessing:L,submitButtonColor:br,submitButtonBorderRadius:St,submitButtonStyle:p.submitButton,errorText:s})},bt)]})})]})]})}return Ai&&bt&&Mo&&Mt&&V?De("form",{onSubmit:da,className:A,style:{position:"relative"},children:[u(Fa,{}),un&&u(qn,{status:un,errorMessage:s,authorized:hn}),u("div",{style:{...Ao?{animation:Ao}:{},...ae==="apm-collapsing"?{pointerEvents:"none"}:{}},children:De("div",{style:{backgroundColor:ma,borderRadius:ba,...ao,padding:ha},children:[De("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[De("button",{type:"button","data-testid":"flopay-apm-back-button-default",onClick:Cn,style:{display:"inline-flex",alignItems:"center",gap:ya?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:p.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...p.backButton},"aria-label":"Back to payment methods",children:[u("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...p.backButtonIcon},children:u("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:u("path",{d:"M15 18l-6-6 6-6"})})}),u(Fr,{content:Ie})]}),u("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:p.titleFontSize??"1.05rem",color:fa,paddingRight:80,...p.title},children:`Pay with ${Rr(bt)}`})]}),u(Ir,{stripe:Mt,options:Mo,children:u(Na,{method:bt,sessionId:e,nonce:t,email:k.email,billingName:[k.firstName,k.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:y,billingApiUrl:T,onTokenizedBody:Sn,onErrorChange:ue,onDecline:l,onCancel:Cn,runBeforeButtonClick:Tn,onButtonClick:oe,isProcessing:L,submitButtonColor:br,submitButtonBorderRadius:St,submitButtonStyle:p.submitButton,errorText:s})},bt)]})})]}):De("form",{onSubmit:da,className:A,style:{position:"relative"},children:[u(Fa,{}),un&&u(qn,{status:un,errorMessage:s,authorized:hn}),De("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Ti("flopay-direct-paypal-gate-debug-default"),Bi("flopay-stripe-gate-debug-default"),eo&&R&&De(Hr,{children:[Ct&&u("div",{"data-testid":"flopay-paypal-direct-retry-notice-default",style:{padding:"8px 10px",background:"#fef3c7",border:"1px solid #fcd34d",borderRadius:6,color:"#78350f",fontSize:13,lineHeight:1.4},children:"Please confirm your PayPal payment to complete checkout."}),u(jo,{sessionId:e,nonce:t,billingApiUrl:T,email:k.email,billingName:O||void 0,onBuyerIdentityReady:y,clientId:R.clientId,environment:R.environment,currency:Ce.toUpperCase(),isSubscription:G,providerObjectType:R.providerObjectType,onTokenizedBody:Sn,onComplete:a,onErrorChange:ue,onDecline:l,onTechnicalFailure:_r,onButtonClick:oe,runBeforeButtonClick:Tn,isProcessing:L,onLoadStateChange:la,onInitializationStateChange:ca,session:_??null,existingOrderId:Ct?.orderId,debug:pt},Ct?.orderId??"fresh")]}),to&&u(Ir,{stripe:Nn,options:ai,children:u(bs,{sessionId:e,nonce:t,email:k.email,billingName:O||void 0,onBuyerIdentityReady:y,billingApiUrl:T,onTokenizedBody:Sn,onErrorChange:ue,isProcessing:L,onButtonClick:oe,onDecline:l,onTechnicalFailure:_r,runBeforeButtonClick:Tn,onLoadStateChange:di,placeholderBorderRadius:hr})}),no&&u(Ir,{stripe:Mt,options:oi,children:u(vs,{sessionId:e,nonce:t,email:k.email,billingName:O||void 0,onBuyerIdentityReady:y,billingApiUrl:T,intentKind:q>0?"payment":"setup",expressMethods:Ro,onTokenizedBody:Sn,onErrorChange:ue,onButtonClick:oe,onDecline:l,onTechnicalFailure:_r,runBeforeButtonClick:Tn,onLoadStateChange:pi,placeholderBorderRadius:hr})}),ro&&u(Ps,{sessionId:e,nonce:t,email:k.email,billingName:[k.firstName,k.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:T,paymentElementMethods:Eo,stripeInstance:Mt,paymentElementBaseOptions:sa,onTokenizedBody:Sn,onErrorChange:ue,onButtonClick:oe,onDecline:l,runBeforeButtonClick:Tn,onLoadStateChange:yi,isProcessing:L,submitButtonColor:br,submitButtonBorderRadius:St,submitButtonStyle:p.submitButton,themeId:ve,onExpandApm:Ln,expandedApmMethod:bt,buttonAppearance:{backgroundColor:p.cardButton?.backgroundColor,borderColor:p.cardInputBorder,textColor:p.cardButton?.color,borderRadius:hr}})]}),f&&(Ys||Hs||Gs)&&De("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem",margin:"0.5rem 0 0.75rem",color:"#999",fontSize:"0.85rem"},children:[u("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}}),u("span",{children:"or pay with card"}),u("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}})]}),f&&xi]})}import{Fragment as Vn,jsx as te,jsxs as Nt}from"react/jsx-runtime";var Er=44,Qa="flopay_checkout_saved_payment_resume",na=new Map,ea=new Map;function Ts(e,t){t.settled&&t.consumers===0&&na.get(e)===t&&na.delete(e)}function Lc(e,t,n){let r=ea.get(e);if(r&&(!r.sdkGeneratedIdempotencyKey||!t||r.sdkGeneratedIdempotencyKey===t))return r.attempt;let o=n(),a={attempt:o,sdkGeneratedIdempotencyKey:t};ea.set(e,a);let d=()=>{ea.get(e)===a&&ea.delete(e)};return o.then(d,d),o}function vo(e){return new Promise(t=>setTimeout(t,e))}function ta(e,t,n){let r=Uo({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:Fs,enabled:t!==!1});return r.beginCheckout(n),r}function Po(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function Ka(e,t,n,r,o){let a=ta(e,t,n);a.error({errorCode:r,stage:o,paymentMethodCategory:"unknown",...o==="session_read"?{requestCategory:"session_read"}:{}}),Po(a)}function Nc(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 Xa(e){let t=e?.data.paypal?.publishableKey;if(t)return{clientId:t,environment:e?.data.paypal?.environment,providerObjectType:e?.data.paypal?.providerObjectType}}function Va(e){return!e||e.data.stripe?.publishableKey?!1:!!Xa(e)?.clientId}function tr(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function Oc(){if(!tr())return null;try{let e=window.sessionStorage.getItem(Qa);return e?JSON.parse(e):null}catch{return null}}function Bs(e){if(tr())try{window.sessionStorage.setItem(Qa,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function Ha(){if(tr())try{window.sessionStorage.removeItem(Qa)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}var ei=":idempotency-key";function Ds(e,t){if(!tr())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 Ya(e,t,n,r){if(tr())try{window.sessionStorage.setItem(e,JSON.stringify(r?{canonicalIdentity:t,sid:n,nonce:r}:{canonicalIdentity:t,sid:n}))}catch(o){console.warn("[FloPayCheckout] Failed to persist checkout session cache.",o)}}function Za(e,t){if(tr())try{Ds(e,t)&&window.sessionStorage.removeItem(e)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout session cache.",n)}}function Ls(e,t){if(!tr())return null;try{let n=window.sessionStorage.getItem(e+ei);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 Ga(e,t,n){if(tr())try{window.sessionStorage.setItem(e+ei,JSON.stringify({canonicalIdentity:t,idempotencyKey:n}))}catch(r){console.warn("[FloPayCheckout] Failed to persist checkout idempotency key.",r)}}function Wa(e,t){if(Za(e,t),!!tr())try{Ls(e,t)&&window.sessionStorage.removeItem(e+ei)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout idempotency key.",n)}}function zc(){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 As(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 Uc(e){return e?!!(e.account&&Object.keys(e.account).length>0||e.couponCodes!==void 0||e.tagsData!==void 0||e.utmMetadata!==void 0):!1}function Ja(e,t){return`${e}:${t.totalAmount??""}:${t.overrideAmount??""}:${t.quantity??1}:${t.currency??""}`}function Co(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=>Ja(`${o.type??""}:${o.code??o.providerItemId??o.providerPlanId??""}`,o)).sort(),i:e?.items?.map(o=>Ja(o.code??o.providerItemId??"",o)).sort(),s:e?.subscriptions?.map(o=>Ja(o.code??o.providerPlanId??"",o)).sort(),couponCodes:e?.couponCodes?[...e.couponCodes].sort():void 0,...t?{tagsData:e?.tagsData,utmMetadata:e?.utmMetadata,tokenizedData:e?.tokenizedData,checkoutMode:e?.checkoutMode??"full"}:{}};return JSON.stringify(r)}function qc(e,t=!1){let n=Co(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 $c(e,t){if(!e?.customer||!e.products)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=Fc(t.currency,t.items,t.subscriptions,t.products);if(!o||e.currency.toUpperCase()!==o.toUpperCase())return!1;let a=(t.products??Tc(t.items,t.subscriptions)).map(g=>({type:g.type,code:g.code??g.providerItemId??g.providerPlanId??"",quantity:g.quantity??1,totalAmount:g.totalAmount,overrideAmount:g.overrideAmount??null,currency:(g.currency??o).toUpperCase()})).sort((g,h)=>`${g.code}:${g.type??""}`.localeCompare(`${h.code}:${h.type??""}`)),d=e.products.map(g=>({type:g.type,code:g.code??"",quantity:g.quantity??1,totalAmount:g.totalAmount,overrideAmount:g.overrideAmount??null,currency:(g.currency??e.currency).toUpperCase()})).sort((g,h)=>`${g.code}:${g.type??""}`.localeCompare(`${h.code}:${h.type??""}`));if(a.length!==d.length)return!1;for(let g=0;g<a.length;g+=1){let h=a[g],v=d[g];if(h.code!==v.code||h.type!==void 0&&h.type!==v.type||h.quantity!==v.quantity||h.totalAmount!==v.totalAmount||h.overrideAmount!==v.overrideAmount||h.currency!==v.currency)return!1}let l=[...t.couponCodes??[]].sort(),S=[...e.coupons??[]].sort();return l.length===S.length&&l.every((g,h)=>g===S[h])}function ti({sessionId:e,nonce:t,createSession:n,billingApiUrl:r,telemetry:o,appearance:a,locale:d,loading:l,error:S,onComplete:g,onError:h,onInstrument:v,onDecline:A,onCountryChange:F,onZipChange:m,showPayPal:w=!0,showStripe:ge=!0,enabledPaymentMethods:V,showApplePay:C=!0,showGooglePay:pe=!0,debug:ne=!1,layout:ce,theme:de,buttonsTheme:ve,buttonsStyles:Ve,cardButtonContent:fe,cardBackButtonContent:kt,cardTitleContent:Le,showSecurityFooter:Ie,onButtonClick:Re,onBeforeButtonClick:re,enableAVS:oe,cardFieldOrder:D,cardPreFormSlot:_e,avsLayout:xe,className:Te,initialErrorMessage:Ne=null,children:Pe,checkoutMode:B,confirmLabel:se,renderConfirmButton:Ae,onSessionCompleted:le}){let H=Ac(r),ke=Rn(()=>Ms(de),[de]),We=a??ke?.appearance,nt=n?"embedded_checkout":"standard_checkout",Be=Pe?"custom_layout":ce==="buttons"?"buttons_layout":"default_layout",[Y,j]=wt(null),[q,Ce]=wt(null),qe=Et(null),[R,G]=wt(null),_=Et(null),[P,Ze]=wt(null),pt=Rn(()=>n?Co(n):"",[n]),J=n?`create:${pt}`:`session:${e??""}`,Qe=P?.gateways?.stripe?"stripe":P?.gateways?.paypal?"paypal":void 0,Ke=Et(new Set),mt=Et(J),vt=Et(J);Oo(()=>{vt.current=J,mt.current!==J&&(mt.current=J,Ke.current.clear())},[J]);let b=jn(M=>{if(vt.current===J){if(ka.has(M.name)){if(Ke.current.has(M.name))return;Ke.current.add(M.name)}at(()=>v?.(M))}},[J,v]),W=qr(b,J),X=Et(!1),rt=jn(M=>{if(X.current)return;let N=M.gateway||!Qe?M:{...M,gateway:Qe};b(N)},[b,Qe]);Kn(()=>{W({class:"lifecycle",name:"checkout.mount"})},[W]);let[_t,ht]=wt(e??""),He=e??_t,$e=n?"":He,[Vt,Ot]=wt(!0),[xt,mn]=wt(null),[En,Mn]=wt("full"),[en,_n]=wt(!1),[Gt,et]=wt(Ne),[yn,Oe]=wt(null),[Fn,ot]=wt(null),[nr,zt]=wt(!1),[Ht,fn]=wt(void 0),[ln,gn]=wt(""),[Bt,rr]=wt(!1),[Ut,Q]=wt(!1),[or,hn]=wt(!1),tn=Et(0),Dn=Et(void 0),[bn,Hn]=wt("loading"),[vn,f]=wt(0),yt=Et(!1),Yt=Et(!1),Yn=Et(!1),Me=Et(null),Pt=Rn(()=>({checkoutMode:B??En,layout:Pe?"unknown":ce==="buttons"?"buttons":"embedded"}),[B,Pe,En,ce]),lt=Et(g);lt.current=g;let Wt=Et(h);Wt.current=h;let Gn=Et(A);Gn.current=A,Kn(()=>{Dt(q)?.setCheckoutContext(Pt),R&&R!==q&&Dt(R)?.setCheckoutContext(Pt)},[q,R,Pt]);let nn=Et(le);nn.current=le;let ar=jn(M=>{Hn(M),!(M!=="exhausted"||Yn.current)&&(Yn.current=!0,Wt.current?.(new Lt("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),yr=jn(()=>{Hn("retrying"),f(M=>M+1)},[]);Kn(()=>{Hn("loading"),f(0),Yn.current=!1},[He]),Kn(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:Fs,checkout_type:nt,checkout_layout:Be,billing_api_url:H})},[Be,nt,H]);let Pn=Rn(()=>n?Co(n,!0):"",[n]),Wn=Rn(()=>ln===Pn?Ht:void 0,[Ht,ln,Pn]),cn=Rn(()=>n?Ca(n,Wn):void 0,[n,Wn]),At=B??cn?.checkoutMode??"full",ae=Rn(()=>cn?{...cn,checkoutMode:At}:void 0,[cn,At]);Kn(()=>{fn(void 0),gn(Pn),Dn.current=void 0,hn(!1)},[Pn]),Kn(()=>{et(Ne)},[Ne]);let It=jn((M,N,T)=>{at(()=>{Gn.current?.(Ft(M,N,T))})},[at]),bt=jn(async(M,N)=>{et(null),ot(null),zt(!1),Oe("processing");let T=N?.sessionId??M.id,Z=M.gateways?.stripe?"stripe":M.gateways?.paypal?"paypal":void 0,ze=qe.current??_.current,y=Dt(ze),s=ze?null:ta(H,o,Pt),c={log:E=>{y?y.log(E):s?.log(E)},error:E=>{y?y.error(E):s?.error(E)},terminal:E=>{y?y.terminal(E):s?.terminal(E)},performance:E=>{y?y.performance(E):s?.performance(E)},now:()=>y?.now()??s?.now()??0,elapsed:E=>y?.elapsed(E)??Math.max(0,(s?.now()??E)-E)},p=c.now(),x=!!(N?.initialAutoProcessingError||N?.initialAutoProcessingPending),ie=!1,Je,L=()=>{ie||(ie=!0,x=!0,Je=c.now(),c.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),c.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},$=!1,k=()=>{$||($=!0,c.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),c.performance({stage:"processing",durationMs:c.elapsed(p),durationMode:"machine",paymentMethodCategory:"saved"}),Je!==void 0&&c.performance({stage:"recovery",durationMs:c.elapsed(Je),durationMode:"machine",paymentMethodCategory:"saved"}))};c.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),X.current=!0;try{c.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"})}finally{X.current=!1}W({class:"lifecycle",name:"payment.processing.started",provider:Z}),x&&L();let O;try{let E=os(N?.initialAutoProcessingError),K;if(E)L(),E.type==="paypal_redirect_required"&&Me.current?.publishableKey&&Bs({sessionId:T,publishableKey:Me.current.publishableKey,paypalPublishableKey:Me.current.paypalPublishableKey}),K=await Yo(E,{flopay:qe.current,paypalFlopay:_.current,attempt3DS:N?.attempt3DS,billingApiUrl:H,sessionId:T,session:M,telemetry:!1}),E.type==="paypal_redirect_required"&&Ha();else if(N?.initialAutoProcessingPending){let Ee=(await new Qo(H,{telemetry:!1}).waitForCheckoutSessionCompletion(N.initialAutoProcessingPending.sessionId,{initialDelayMs:N.initialAutoProcessingPending.retryAfterMs})).data.session;if(!Nr(Ee))throw Do(Ee);K=Pr(Ee,T)}else{if(N?.initialAutoProcessingError)throw ur(N.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:N.initialAutoProcessingError.checkoutMethod});if(N?.fromCreateSession)return N?.fallbackToFull&&(Mn("full"),As("full")),!1;{let he=await Kr({billingApiUrl:H,sessionId:T,session:M,telemetry:!1});he.type==="success"?K=he.result:(L(),he.type==="paypal_redirect_required"&&Me.current?.publishableKey&&Bs({sessionId:T,publishableKey:Me.current.publishableKey,paypalPublishableKey:Me.current.paypalPublishableKey}),K=await Yo(he,{flopay:qe.current,paypalFlopay:_.current,attempt3DS:N?.attempt3DS,billingApiUrl:H,sessionId:T,session:M,telemetry:!1}),he.type==="paypal_redirect_required"&&Ha())}}T&&jr(T),k(),x&&(c.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),c.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),c.terminal({outcome:K.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),zt(K.status==="authorized"),Oe("success"),await vo(1200),O=()=>lt.current?.(K)}catch(E){let K=kr(E),he=K.checkoutMethod??ho;et(K.message),ot(K.message),zt(!1),N?.fallbackToFull&&(c.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),Mn("full"),As("full")),k();let ee=K.statusCode!==void 0?Dc(K.statusCode,"unknown"):void 0,Ee=ee==="4xx"?{requestCategory:"process_payment",statusClass:ee}:{},Mt=ee===void 0||ee==="4xx";if(Mt&&(K.telemetryOutcome==="payment_declined"||!!(K.declineCode||K.code?.toLowerCase().includes("declin"))))c.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...Ee});else if(Mt&&(K.telemetryOutcome==="validation_rejected"||K.type==="validation_error"))c.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...Ee});else{let qt=_s(E,x?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown"),On=K.telemetryRequestCategory??"process_payment";X.current=!0;try{c.error({...qt,...K.telemetryFailureCategory?{failureCategory:K.telemetryFailureCategory}:{},stage:x?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:On})}finally{X.current=!1}W({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:On,provider:Z})}return at(()=>Wt.current?.(K)),It(he,K,{code:K.code,declineCode:K.declineCode}),Oe("error"),await Promise.allSettled([vo(1500),N?.ensureProvidersReady?N.ensureProvidersReady():Promise.resolve()]),x&&(c.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),c.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{k(),s&&Po(s),Oe(null),ot(null)}return at(O),!0},[It,W,at,kr,H,o,Pt]);Kn(()=>{if(typeof window>"u"||Yt.current)return;let M=new URLSearchParams(window.location.search),N=M.get("payment_intent_client_secret");if(!N)return;let T=Oc();T&&(Yt.current=!0,(async()=>{let Z,ze=0;et(null),ot(null),Oe("processing"),_n(!0);try{if(M.get("redirect_status")==="failed")throw Object.assign(new Lt("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:y,paypalFlopay:s}=await Wo({publishableKey:T.publishableKey,paypalPublishableKey:T.paypalPublishableKey,billingApiUrl:H,locale:d,telemetry:o});Z=Dt(s??y),ze=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 c=(s??y)?.getRawProvider();if(!c)throw Object.assign(new Lt("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:p,error:x}=await c.retrievePaymentIntent(N);if(x)throw Object.assign(new Lt(x.message??"Failed to retrieve PayPal payment status.","api_error",{code:x.code}),{checkoutMethod:"paypal"});let ie=zi(p?.status);if(!p||ie==="failed")throw Object.assign(new Lt("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let Je=typeof p.payment_method=="string"?p.payment_method:p.payment_method?.id,L=ie;if(T.sessionId){let O=(await new Qo(H,{telemetry:!1}).getUnifiedCheckoutSession(T.sessionId)).data.session;if(O&&O.status!=="complete"){let E=await Kr({billingApiUrl:H,sessionId:T.sessionId,session:O,telemetry:!1,tokenizedData:{id:Je??p.id,type:"card",threeDSecureActionResultTokenId:p.id,isPaypal:!0}});if(E.type!=="success")throw Object.assign(new Lt("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});L=E.result.status}}T.sessionId&&jr(T.sessionId),Z?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),Z?.performance({stage:"redirect_resume",durationMs:Z.elapsed(ze),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),Z?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),Oe("success"),await vo(1200),at(()=>lt.current?.({status:L,paymentIntentId:p.id,paymentMethodId:Je,checkoutMethod:"paypal"}))}catch(y){let s=kr(y),c=s.checkoutMethod??"paypal",p=!!(s.declineCode||s.code?.toLowerCase().includes("declin"));if(Z)Z.performance({stage:"redirect_resume",durationMs:Z.elapsed(ze),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),p?Z.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):Z.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(p){let x=ta(H,o,Pt);x.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),Po(x)}else Ka(H,o,Pt,"REDIRECT_RESUME_FAILED","redirect_resume");et(s.message),ot(s.message),at(()=>Wt.current?.(s)),It(c,s,{code:s.code,declineCode:s.declineCode}),Oe("error"),await vo(1500)}finally{Ha(),zc(),Oe(null),ot(null),_n(!1)}})())},[It,at,d,kr,H,o]);let Jt=Et(null),dn=Rn(()=>ae?Co(ae):"",[ae]),Jn=Et(ae);Jn.current=ae,Kn(()=>{ht(e??"")},[e]),Kn(()=>{yt.current=!1,et(Ne),ot(null),zt(!1),Oe(null)},[dn,Ne,e]);async function ir(M,N,T){let Z=ta(H,o,Pt),ze=new Qo(H,{telemetry:!1}),y=!1;try{let s=M.idempotencyKey!==void 0?xs(M.idempotencyKey):void 0,c=Ds(N,T),p=Ls(N,T);c?.canonicalIdentity===T&&p&&p.canonicalIdentity===void 0&&(Ga(N,T,p.idempotencyKey),p={...p,canonicalIdentity:T});let x=s??(p?.canonicalIdentity===T?p.idempotencyKey:void 0),ie,Je=!1;Z.log({name:c?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let L=c?.sid??null,$=null,k,O,E=!1;if(L)try{$=await ze.getUnifiedCheckoutSession(L,c?.nonce),c&&c.canonicalIdentity===void 0&&($c($.data.session,M)?(Ya(N,T,L,c.nonce??$.data.session?.clientSecret),p&&p.canonicalIdentity===void 0&&(Ga(N,T,p.idempotencyKey),x??(x=p.idempotencyKey))):(Wa(N,T),p=null,x=s,L=null,$=null));let he=$?.data.session?.status,ee=$?.data.session,Ee=ee?.clientSecret||c?.nonce;if(L&&ee?.buyerIdentified===!1&&Ee&&(O=Lr(ze,L,Ee,M.account)),L&&$&&he==="complete"){if(xa(L))return{sid:L,result:$};Wa(N,T),L=null,$=null,Je=!0}}catch{Z.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),c?.canonicalIdentity===void 0?(Wa(N,T),x=s):Za(N,T),L=null}if(!L){!s&&(Je||!x)&&(x=xs(),ie=x),x&&Ga(N,T,x);let he=Z.now(),ee=0;Z.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let Ee={...M,idempotencyKey:x,avsCheck:!!oe,avsConfig:typeof oe=="object"?oe:void 0,checkoutType:"embedded_checkout",checkoutLayout:Pe?"custom_layout":ce==="buttons"?"buttons_layout":"default_layout"};Object.defineProperty(Ee,_c,{configurable:!1,enumerable:!1,value:{onAttempt:ft=>{ee=Math.max(ee,ft)}}});let Mt=()=>{Z.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:"2xx"}),Z.performance({stage:"session_create",durationMs:Z.now()-he,durationMode:"machine",requestCategory:"session_create",attempt:ee,statusClass:"2xx"})},Nn=ft=>{let qt=_s(ft,"CHECKOUT_SESSION_CREATE_FAILED","unknown");Z.performance({stage:"session_create",durationMs:Z.now()-he,durationMode:"machine",requestCategory:"session_create",attempt:ee,statusClass:qt.statusClass}),ft instanceof Lt&&ft.type==="validation_error"?Z.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown"}):qt.statusClass==="4xx"?Z.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create",statusClass:"4xx"}):(Z.error({...qt,stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create"}),W({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_create"}))};try{if(Bc(Ee)){let ft=await ze.createDetachedSession(Ee);ft.claimed.catch(()=>{}),$=ft.shell,L=ft.sessionId,O=ft.claim,k=ft.claimed.then(qt=>{let On=qt.data.session?.id??ft.sessionId;return On&&Ya(N,T,On,qt.data.session?.clientSecret??ft.nonce),Mt(),qt},qt=>{throw Za(N,T),Nn(qt),qt}).finally(()=>Po(Z)),k.catch(()=>{}),y=!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()-he,durationMode:"machine",requestCategory:"session_create",attempt:ee,statusClass:"2xx",paymentMethodCategory:"card"})}else $=await ze.createAndFetchSession(Ee),Mt()}catch(ft){throw Nn(ft),ft}L=$.data.session?.id??L??"",L&&!k&&Ya(N,T,L,$.data.session?.clientSecret)}let K=$?.data.session;return!O&&L&&K?.buyerIdentified===!1&&K.clientSecret&&(O=Lr(ze,L,K.clientSecret,M.account)),{sid:L??"",result:$,sdkGeneratedIdempotencyKey:ie,...k?{claimed:k}:{},...O?{claim:O}:{},...E?{claimRequiresIdentity:!0}:{}}}finally{y||Po(Z)}}let Xt=jn(async(M,N)=>{let T=Jn.current;if(!T)throw new Lt("createSession is required to bootstrap checkout.","validation_error");let Z=Ca(T,M),ze=Co(Z),y=qc(Z),s=na.get(ze);if(!s){let x={canonicalIdentity:ze,promise:ir(Z,y,ze),consumers:0,settled:!1};s=x,na.set(ze,x);let ie=()=>{x.settled=!0,Ts(ze,x)};x.promise.then(ie,ie)}s.consumers+=1;let c=!1,p=()=>{c||(c=!0,s.consumers-=1,Ts(ze,s))};N?.(p);try{let x=await s.promise;Jt.current=ze,M&&(gn(Pn),fn(ee=>Li(ee,M)));let{sid:ie,result:Je,claimed:L,claim:$,claimRequiresIdentity:k}=x;if(Dn.current=$,hn(k===!0),j(Je),Je.data.session&&Ze(Je.data.session),ie&&ht(ie),L){tn.current+=1;let ee=tn.current;Q(!0),L.then(Ee=>{tn.current===ee&&(j(Ee),Ee.data.session&&Ze(Ee.data.session),Q(!1),hn(!1))},Ee=>{tn.current===ee&&(Q(!1),hn(!1),mn(Ee instanceof Lt?Ee:new Lt(Ee instanceof Error?Ee.message:"Failed to create session","api_error")))})}else tn.current+=1,Q(!1),hn(!1);let{publishableKey:O,paypalPublishableKey:E}=Go(Je),{flopay:K,paypalFlopay:he}=await Wo({publishableKey:O,paypalPublishableKey:E,billingApiUrl:H,locale:d,telemetry:o});return qe.current=K,Ce(K),_.current=he,G(he),Ot(!1),x}catch(x){throw Jt.current===ze&&(Jt.current=null),x}finally{N||p()}},[Pn,d,H,o,Pt]),rn=Et(bt);rn.current=bt;let on=Et(Xt);on.current=Xt;let fr=jn(async M=>{if(!Uc(M)||Bt)return{sessionId:_t,session:P};rr(!0);try{let N=await Xt(M);return{sessionId:N.sid,session:N.result.data.session??null}}finally{rr(!1)}},[Xt,Bt,_t,P]),Xn=jn(async M=>{let N=Dn.current;if(!N)return;let T=tn.current,Z=await N(M);tn.current===T&&(j(Z),Z.data.session&&Ze(Z.data.session))},[]);Kn(()=>{let M=!1,N;if(mn(null),dn){let ze=Jn.current;return Mn(At),Ot(!1),Jt.current===dn?()=>{M=!0}:(Ze(Ni(ze,B)),(async()=>{let y=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),s=At==="auto"&&!yt.current&&!y;s&&(et(null),ot(null),Oe("processing"));try{let c=await on.current(void 0,Je=>{N=Je}),p=c.result.data.session??null;Me.current=Go(c.result);let x=Va(c.result),ie=xa(c.sid||p?.id);if(!M&&s&&p&&!x&&!ie){yt.current=!0,await Lc(dn,c.sdkGeneratedIdempotencyKey,()=>rn.current(p,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:c.result.autoProcessingError,initialAutoProcessingPending:c.result.autoProcessingPending,autoProcessingAttempted:c.result.autoProcessingAttempted,sessionId:c.sid||p.id}));return}!M&&s&&((x||ie)&&(yt.current=!0),Oe(null),ot(null))}catch(c){if(M)return;let p=c instanceof Lt||typeof c=="object"&&c!==null&&"code"in c?c.code:void 0;if(s&&p==="session_auto_completed"){yt.current=!0,Oe("success"),await vo(1200),M||(at(()=>{lt.current?.({status:"succeeded"})}),Oe(null),ot(null));return}s&&(Oe(null),ot(null));let x=c instanceof Lt?c:new Lt(c instanceof Error?c.message:"Failed to create session","api_error");mn(x)}finally{N?.(),N=void 0}})(),()=>{M=!0,N?.()})}Ot(!0);async function T(){let ze=!1;try{let y=new Qo(H,{telemetry:!1}),s=await y.getUnifiedCheckoutSession(He,t);if(M)return;j(s);let c=s.data.session??null;if(Ze(c),!c)throw new Lt("No session data returned","api_error");let p=c.checkoutMode;if(p==="setup")throw new Lt("This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.","validation_error",{code:"InvalidCardSetupSurface",param:"sessionId"});if(c.status==="authorized"){Ot(!1),at(()=>{lt.current?.(Pr(c,He)),nn.current?.(c.successUrl??"")});return}if(c.status==="complete"){Ot(!1),at(()=>{nn.current?.(c.successUrl??"")});return}if(c.status==="expired")throw Fo(c);ze=!0;let x=B??p??"full";Mn(x),tn.current+=1;let ie=c.clientSecret||t;Dn.current=c.buyerIdentified===!1&&ie?Lr(y,He,ie,{...c.customer?.id?{userId:c.customer.id}:{}}):void 0,Q(!1),hn(!1);let Je=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),L=Va(s);if(x==="auto"&&!yt.current&&!Je&&!L){yt.current=!0;let $=Z(s);try{if(await rn.current(c,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>$,sessionId:He||c.id}),M)return;await $,M||Ot(!1);return}catch{if(M)return;await $,M||Ot(!1);return}}await Z(s),M||Ot(!1)}catch(y){if(M)return;ze&&W({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"}),y instanceof Lt?!ze&&!Nc(y)&&Ka(H,o,Pt,"NETWORK_REQUEST_FAILED","session_read"):Ka(H,o,Pt,"INTERNAL_SDK_ERROR","checkout_mount");let s=y instanceof Lt?y:new Lt(y instanceof Error?y.message:"Failed to initialize checkout","api_error");mn(s),Ot(!1)}}async function Z(ze){let{publishableKey:y,paypalPublishableKey:s}=Go(ze);Me.current={publishableKey:y,paypalPublishableKey:s};let{flopay:c,paypalFlopay:p}=await Wo({publishableKey:y,paypalPublishableKey:s,billingApiUrl:H,locale:d,telemetry:o});qe.current=c,Ce(c),_.current=p,G(p)}return T(),()=>{M=!0}},[B,dn,At,$e,at,t]);let Ln=jn(async()=>{if(!(en||!P)){_n(!0),et(null);try{await bt(P,{attempt3DS:!0,fallbackToFull:!0,sessionId:He||P.id})}finally{_n(!1)}}},[He,en,bt,P]),Cn=Xa(Y),un=Va(Y),Xe=Rn(()=>{if(!(!Y||!P||!Y.data.stripe?.publishableKey))return{billingApiUrl:H}},[Y,P,H]),pn=!!(n&&!Pe&&ce==="buttons"&&re&&At==="full"),Tt=Rn(()=>({session:P,loading:Vt,error:xt,checkoutMode:En,inlineSessionDraft:ae,applyInlineSessionPatch:pn?fr:void 0,inlineSessionPatchProcessing:Bt,claimPending:Ut,claimRequiresIdentity:or,claimBuyerIdentity:Xn}),[P,Vt,xt,En,ae,pn,fr,Bt,Ut,or,Xn]),Rt=!!n&&ce==="buttons"&&!un&&(!q||!Xe),Ct=yn?te(qn,{status:yn,errorMessage:Fn,authorized:nr}):null;if(Vt){if(l)return Nt(Vn,{children:[l,Ct]});if(ce==="buttons"){let M=ke?.buttonsLayout?.cardButton?.borderRadius??ke?.appearance.variables?.borderRadius??8,N=T=>te("div",{style:{height:T,borderRadius:M,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return Nt(Vn,{children:[Nt("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[w&&N(Er),ge&&(C||pe)&&N(Er),ge&&N(Er),te("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),Ct]})}return Nt(Vn,{children:[Nt("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[te("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),te("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),Ct]})}return xt?S?te(Bn.Provider,{value:Tt,children:S(xt)}):te(Bn.Provider,{value:Tt,children:te("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:xt.message})}):Rt?Nt(Vn,{children:[te(Bn.Provider,{value:Tt,children:te(Kc,{onButtonClick:Re,showPayPal:w,showStripe:ge,showApplePay:C,showGooglePay:pe,theme:de,buttonsTheme:ve,buttonsStyles:Ve,cardButtonContent:fe,cardBackButtonContent:kt,cardTitleContent:Le})}),Ct]}):un&&P&&Cn?Nt(Vn,{children:[te(Bn.Provider,{value:Tt,children:Nt("div",{className:Te,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Gt&&te($r,{icon:!1,children:Gt}),bn==="retrying"&&te("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),bn==="exhausted"&&Nt("div",{role:"alert",children:[te("div",{children:"PayPal is temporarily unavailable. Please try again."}),te("button",{type:"button",onClick:yr,children:"Retry PayPal"})]}),Ut?l??te("div",{role:"status","data-testid":"flopay-paypal-catalog-loading","aria-label":"Preparing PayPal",style:{height:Er,borderRadius:8,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"},children:te("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})}):bn!=="exhausted"?te("div",{"aria-hidden":bn==="retrying"?!0:void 0,style:bn==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:te(Xi,{sessionId:He,nonce:P.clientSecret||void 0,billingApiUrl:H,email:P.customer?.email||ae?.account?.email,billingName:[P.customer?.firstName,P.customer?.lastName].filter(Boolean).join(" ")||[ae?.account?.firstName,ae?.account?.lastName].filter(Boolean).join(" ")||void 0,onBuyerIdentityReady:Xn,clientId:Cn.clientId,environment:Cn.environment,currency:(P.currency??"usd").toUpperCase(),isSubscription:P.mode==="subscription",providerObjectType:Cn.providerObjectType,onComplete:g,onErrorChange:et,onDecline:A,onButtonClick:Re,onInitializationStateChange:ar,allowAutomaticRetry:vn===0,session:P,telemetry:o,telemetryContext:Pt,onInstrument:rt,debug:ne},`${J}:paypal-init-${vn}`)}):null]})}),Ct]}):!q||!Xe?te(Vn,{children:Ct}):En==="confirm"?Nt(Vn,{children:[te(Bn.Provider,{value:Tt,children:te(Ko,{flopay:q,paypalFlopay:R,options:Xe,onInstrument:rt,children:Nt("div",{className:Te,children:[Gt&&te("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:Gt}),Ae?Ae({onConfirm:Ln,isProcessing:en}):te("button",{type:"button",onClick:Ln,disabled:en,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:en?"not-allowed":"pointer",opacity:en?.6:1},children:en?"Processing...":se??"Confirm Purchase"})]})},J)}),Ct]}):Nt(Vn,{children:[te(Bn.Provider,{value:Tt,children:te(Ko,{flopay:q,paypalFlopay:R,options:Xe,onInstrument:rt,children:Pe?Nt(Vn,{children:[Gt&&te("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:Gt}),te(jc,{sessionId:He,nonce:P?.clientSecret||void 0,billingApiUrl:H,session:P,children:Pe})]}):te($a,{sessionId:He,nonce:P?.clientSecret||void 0,email:P?.customer?.email||ae?.account?.email,userId:P?.customer?.id||ae?.account?.userId,firstName:P?.customer?.firstName||ae?.account?.firstName,lastName:P?.customer?.lastName||ae?.account?.lastName,totalAmount:P?Math.round(xc(P).total*100):0,currency:P?.currency?.toLowerCase()??"usd",onComplete:g,onError:h,onDecline:A,error:Gt,onErrorChange:et,showPayPal:w,showStripe:ge,enabledPaymentMethods:V??Y?.data.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:Y?.data.stripe?.enabledPaymentMethodCountries,showApplePay:C,showGooglePay:pe,layout:ce,theme:de,buttonsTheme:ve,buttonsStyles:Ve,appearance:We,cardButtonContent:fe,cardBackButtonContent:kt,cardTitleContent:Le,onButtonClick:Re,onBeforeButtonClick:re,onBuyerIdentityReady:Xn,enableAVS:oe,...D?{cardFieldOrder:D}:{},..._e?{cardPreFormSlot:_e}:{},avsLayout:xe,country:P?.customer?.country,city:P?.customer?.city,state:P?.customer?.state,onCountryChange:F,onZipChange:m,avsCheck:!!oe,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:Pe?"custom_layout":ce==="buttons"?"buttons_layout":"default_layout",className:Te,directPaypal:Xa(Y),isSubscription:P?.mode==="subscription",session:P,dataAttachmentPending:Ut,dataAttachmentRequiresIdentity:or,debug:ne})},J)}),Ct]})}function jc({sessionId:e,nonce:t,billingApiUrl:n,session:r,children:o}){return te(Vn,{children:ja.Children.map(o,a=>{if(!ja.isValidElement(a))return a;let d=a.props,l={};return d.sessionId||(l.sessionId=e),!d.nonce&&t&&(l.nonce=t),d.billingApiUrl||(l.billingApiUrl=n),r?.customer&&(d.email||(l.email=r.customer.email),d.userId||(l.userId=r.customer.id),d.firstName||(l.firstName=r.customer.firstName),d.lastName||(l.lastName=r.customer.lastName)),Object.keys(l).length===0?a:ja.cloneElement(a,l)})})}function Kc({onButtonClick:e,showPayPal:t,showStripe:n=!0,showApplePay:r,showGooglePay:o,theme:a,buttonsTheme:d,buttonsStyles:l,cardButtonContent:S,cardBackButtonContent:g,cardTitleContent:h}){let[v,A]=wt(!1),F=Rn(()=>Ms(a),[a]),m=Rn(()=>{let C=F?.buttonsLayout??Mc(d);return l?{...C,...l,cardButton:{...C.cardButton,...l.cardButton},cardFormContainer:{...C.cardFormContainer,...l.cardFormContainer},backButton:{...C.backButton,...l.backButton},backButtonIcon:{...C.backButtonIcon,...l.backButtonIcon},submitButton:{...C.submitButton,...l.submitButton},title:{...C.title,...l.title}}:C},[F,d,l]),w=F?.buttonsLayout?.cardButton?.borderRadius??F?.appearance.variables?.borderRadius??8,ge=C=>te("div",{style:{height:C,borderRadius:w,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),V=S===void 0?{boxSizing:"border-box",height:Er,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(v){let C=m.cardInputBorder??"#e5e7eb",pe=m.cardInputBackground??"white",ne=Ar(g),ce=Ar(h);return Nt("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:[Nt("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[Nt("button",{type:"button",onClick:()=>A(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:ne?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:[te("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...m.backButtonIcon},children:te("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:te("path",{d:"M15 18l-6-6 6-6"})})}),te(Fr,{content:g})]}),ce?te("div",{style:{flex:1}}):te("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...m.title},children:te(co,{content:h})})]}),te("div",{style:{backgroundColor:pe,border:`1px solid ${C}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:te("div",{style:{width:"60%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),Nt("div",{style:{display:"flex"},children:[te("div",{style:{flex:1,backgroundColor:pe,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${C}`,borderLeft:`1px solid ${C}`,borderBottomLeftRadius:8,padding:12,height:45},children:te("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),te("div",{style:{flex:1,backgroundColor:pe,borderTop:"none",borderRight:`1px solid ${C}`,borderBottom:`1px solid ${C}`,borderLeft:`1px solid ${C}`,borderBottomRightRadius:8,padding:12,height:45},children:te("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),te("div",{style:{backgroundColor:pe,border:`1px solid ${C}`,borderRadius:8,marginTop:8,padding:12,height:45},children:te("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),te("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",...m.submitButton,opacity:.5}}),te("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 Vt("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&ve(Gr),n&&(r||o)&&ve(Gr),n&&re("button",{type:"button",onClick:()=>{e?.("card"),M(!0)},style:{width:"100%",...H,backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:"8px",fontSize:u.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,...u.cardButton},onMouseDown:P=>{P.currentTarget.style.transform="scale(0.985)"},onMouseUp:P=>{P.currentTarget.style.transform="scale(1)"},children:re(Dr,{content:S})}),re("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}import{Fragment as nd,jsx as Xr,jsxs as rd}from"react/jsx-runtime";var Xc=44;function qs(e){return new Promise(t=>setTimeout(t,e))}function Zc(e,t){return e instanceof Zr?e:new Zr(e instanceof Error?e.message:t,"api_error")}function Qc(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function ed(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 td({sessionId:e,nonce:t,createSession:n,paymentMethodId:r,checkoutMethod:o,clientId:a,products:c,items:s,subscriptions:S,account:b,successUrl:g,cancelUrl:m,couponCodes:M,tagsData:D,utmMetadata:u,billingApiUrl:w,locale:ve,theme:H,appearance:P,buttonsTheme:fe,buttonsStyles:Q,onSuccess:ce,onError:oe,onDecline:Ce,children:He,disabled:be=!1,type:Rt="button",style:De,...Te}){let Ae=Eo(()=>Gc(w),[w]),ee=Eo(()=>ed({createSession:n,clientId:a,products:c,items:s,subscriptions:S,account:b,successUrl:g,cancelUrl:m,couponCodes:M,tagsData:D,utmMetadata:u}),[b,m,a,M,n,c,s,S,g,D,u]),[J,L]=Ro(!1),[me,et]=Ro(null),[Ue,Ye]=Ro(null),[te,T]=Ro(!1),[ae,Fe]=Ro(null),ie=Jr(!0),j=Jr(null),_e=Jr(ae),Je=Jr(ce),We=Jr(oe),Se=Jr(Ce);Wr(()=>{_e.current=ae},[ae]),Wr(()=>{Je.current=ce},[ce]),Wr(()=>{We.current=oe},[oe]),Wr(()=>{Se.current=Ce},[Ce]),Wr(()=>(ie.current=!0,()=>{ie.current=!1,j.current?.abort()}),[]),Wr(()=>{if(typeof window>"u")return;let y=U=>{U.key==="Escape"&&Fe(null)};return window.addEventListener("keydown",y),()=>{window.removeEventListener("keydown",y)}},[]);let G=hr((y,U=Po)=>{Se.current?.($t(U,y,{code:y.code,declineCode:y.declineCode}))},[]),Y=hr(async y=>{ie.current&&(Ye(null),T(y.result.status==="authorized"),et("success"),await qs(1200),ie.current&&Je.current?.(y))},[]),$=hr(async(y,U)=>{ie.current&&(We.current?.(y),U?.emitDecline&&G(y,U.method),Ye(y.message),T(!1),et("error"),await qs(1500))},[G]),we=hr(async(y,U,Xe)=>{let dt=y.data.session??null;if(!dt)throw new Zr("No session data returned","api_error");let Mt=dt.clientSecret||t;if(zr(dt)){await Y({result:kr(dt,U),session:dt,sessionId:dt.id||U,autoCompleted:!1});return}if(dt.status==="expired")throw qo(dt);try{if(y.autoProcessingPending){let Wt=(await new si(Ae).waitForCheckoutSessionCompletion(y.autoProcessingPending.sessionId,{initialDelayMs:y.autoProcessingPending.retryAfterMs})).data.session;if(!zr(Wt))throw $o(Wt);await Y({result:kr(Wt,U),session:Wt,sessionId:Wt.id||U,autoCompleted:!1});return}if(y.autoProcessingError){if(y.autoProcessingError.type==="3ds_required"&&y.autoProcessingError.nextActionRedirectUrl&&U&&Mt){let W=new AbortController;j.current=W;let Le;try{Le=await cs({billingApiUrl:Ae,sessionId:U,nonce:Mt,nextActionRedirectUrl:y.autoProcessingError.nextActionRedirectUrl,signal:W.signal})}finally{j.current===W&&(j.current=null)}if(Le.status==="declined")throw yr({type:Le.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:Le.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:y.autoProcessingError.checkoutMethod});let Ot=(await new si(Ae).waitForCheckoutSessionCompletion(U,{initialDelayMs:0,nonce:Mt})).data.session;if(!zr(Ot))throw yr({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:y.autoProcessingError.checkoutMethod});await Y({result:kr(Ot,U),session:Ot,sessionId:Ot.id||U,autoCompleted:!1});return}throw yr(y.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:y.autoProcessingError.checkoutMethod})}if(Xe?.fromCreateSession&&y.autoProcessingAttempted===!0)throw yr({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let Bt=await Hr({billingApiUrl:Ae,sessionId:U??dt.id,session:dt,nonce:Mt});if(Bt.type!=="success")throw yr({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await Y({result:Bt.result,session:dt,sessionId:dt.id||U,autoCompleted:!1})}catch(Bt){let W=Rr(Bt),Le=dt.id||U;await $(W,{emitDecline:!0,method:W.checkoutMethod??Po}),Qc(W,Le)&&Le&&ie.current&&Fe({sessionId:Le,errorMessage:W.message,nonce:Mt||void 0})}},[t,Ae,$,Y]),Me=hr(async y=>{if(Te.onClick?.(y),!(y.defaultPrevented||be||J)){if(Fe(null),e&&ee){let U=new Zr("Provide either sessionId or create-session props, not both.","validation_error");await $(U),ie.current&&(et(null),Ye(null));return}if(!e&&!ee){let U=new Zr("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await $(U),ie.current&&(et(null),Ye(null));return}L(!0),Ye(null),T(!1),et("processing");try{let U=new si(Ae);if(e){let Xe=await U.getUnifiedCheckoutSession(e,t);await we(Xe,e);return}try{let Xe=await U.createAndFetchSession({...ee});await we(Xe,Xe.data.session?.id??null,{fromCreateSession:!0})}catch(Xe){if(Xe instanceof Zr&&Xe.code==="session_auto_completed"){await Y({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw Xe}}catch(U){await $(Zc(U,"Automatic payment failed. Please try again."))}finally{ie.current&&(et(null),Ye(null),L(!1))}}},[Te,ee,be,J,t,we,Ae,e,$,Y]),x=hr(y=>{let U=_e.current;Fe(null),Je.current?.({result:y,session:null,sessionId:U?.sessionId??null,autoCompleted:!1})},[]),K=hr(y=>{We.current?.(y)},[]),I=hr(y=>{Se.current?.(y)},[]),C=Eo(()=>Jc(H),[H]),nt=Eo(()=>{let y=C?.buttonsLayout??Wc(fe);return Q?{...y,...Q,cardButton:{...y.cardButton,...Q.cardButton}}:y},[C,fe,Q]),St=Eo(()=>{let y=C?.appearance;return P?y?{...y,...P,variables:{...y.variables,...P.variables}}:P:y},[P,C]),de=St?.variables,ct=de?.colorPrimary??"#4A49FF",it=de?.colorPrimaryHover??po(ct,.12),rt=de?.borderRadius??"8px";return rd(nd,{children:[Xr("button",{...Te,type:Rt,onClick:Me,disabled:be||J,"aria-busy":J,style:{width:"100%",...He===void 0?{boxSizing:"border-box",height:Xc,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...nt.cardButton,...Ha({themeBundle:C,resolvedPrimaryColor:ct,resolvedBorderRadius:rt,submitButtonStyle:nt.submitButton,explicitPrimaryColor:de?.colorPrimary}),fontSize:nt.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:be||J?"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||J?.6:1,...De},onMouseEnter:y=>{Te.onMouseEnter?.(y),!y.defaultPrevented&&!be&&!J&&(C||de?.colorPrimary)&&(y.currentTarget.style.backgroundColor=it)},onMouseLeave:y=>{Te.onMouseLeave?.(y),!y.defaultPrevented&&(C||de?.colorPrimary)&&(y.currentTarget.style.backgroundColor=ct)},onMouseDown:y=>{Te.onMouseDown?.(y),y.defaultPrevented||(y.currentTarget.style.transform="scale(0.985)")},onMouseUp:y=>{Te.onMouseUp?.(y),y.defaultPrevented||(y.currentTarget.style.transform="scale(1)")},children:Xr(Dr,{content:He})}),me&&Xr(Yn,{status:me,errorMessage:Ue,authorized:te}),ae&&Xr("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:y=>{y.target===y.currentTarget&&Fe(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:Xr("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:Xr(ii,{sessionId:ae.sessionId,nonce:ae.nonce,checkoutMode:"full",billingApiUrl:Ae,locale:ve,theme:H,...St?{appearance:St}:{},buttonsTheme:fe,buttonsStyles:Q,initialErrorMessage:ae.errorMessage,cardTitleContent:null,onComplete:x,onError:K,onDecline:I})})})]})}export{Jo as DirectPayPalButton,td as FloPayAutomaticPaymentButton,ll as FloPayCardSetup,sl as FloPayCardSetupError,ii as FloPayCheckout,Xo as FloPayProvider,Ya as SplitCardForm,wa as VaultCardFields,ap as dropThirdPartyOnlyError,bl as useCheckout,ur as useFloPay,_a as usePayPalFloPay};
42
+ `})]})}return Nt("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&ge(Er),n&&(r||o)&&ge(Er),n&&te("button",{type:"button",onClick:()=>{e?.("card"),A(!0)},style:{width:"100%",...V,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:C=>{C.currentTarget.style.transform="scale(0.985)"},onMouseUp:C=>{C.currentTarget.style.transform="scale(1)"},children:te(Mr,{content:S})}),te("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}import{Fragment as Qc,jsx as Jr,jsxs as ed}from"react/jsx-runtime";var Gc=44;function Ns(e){return new Promise(t=>setTimeout(t,e))}function Wc(e,t){return e instanceof Xr?e:new Xr(e instanceof Error?e.message:t,"api_error")}function Jc(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function Xc(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 Zc({sessionId:e,nonce:t,createSession:n,paymentMethodId:r,checkoutMethod:o,clientId:a,products:d,items:l,subscriptions:S,account:g,successUrl:h,cancelUrl:v,couponCodes:A,tagsData:F,utmMetadata:m,billingApiUrl:w,locale:ge,theme:V,appearance:C,buttonsTheme:pe,buttonsStyles:ne,onSuccess:ce,onError:de,onDecline:ve,children:Ve,disabled:fe=!1,type:kt="button",style:Le,...Ie}){let Re=So(()=>Vc(w),[w]),re=So(()=>Xc({createSession:n,clientId:a,products:d,items:l,subscriptions:S,account:g,successUrl:h,cancelUrl:v,couponCodes:A,tagsData:F,utmMetadata:m}),[g,v,a,A,n,d,l,S,h,F,m]),[oe,D]=wo(!1),[_e,xe]=wo(null),[Te,Ne]=wo(null),[Pe,B]=wo(!1),[se,Ae]=wo(null),le=Wr(!0),H=Wr(null),ke=Wr(se),We=Wr(ce),nt=Wr(de),Be=Wr(ve);Gr(()=>{ke.current=se},[se]),Gr(()=>{We.current=ce},[ce]),Gr(()=>{nt.current=de},[de]),Gr(()=>{Be.current=ve},[ve]),Gr(()=>(le.current=!0,()=>{le.current=!1,H.current?.abort()}),[]),Gr(()=>{if(typeof window>"u")return;let b=W=>{W.key==="Escape"&&Ae(null)};return window.addEventListener("keydown",b),()=>{window.removeEventListener("keydown",b)}},[]);let Y=mr((b,W=ho)=>{Be.current?.(Ft(W,b,{code:b.code,declineCode:b.declineCode}))},[]),j=mr(async b=>{le.current&&(Ne(null),B(b.result.status==="authorized"),xe("success"),await Ns(1200),le.current&&We.current?.(b))},[]),q=mr(async(b,W)=>{le.current&&(nt.current?.(b),W?.emitDecline&&Y(b,W.method),Ne(b.message),B(!1),xe("error"),await Ns(1500))},[Y]),Ce=mr(async(b,W,X)=>{let rt=b.data.session??null;if(!rt)throw new Xr("No session data returned","api_error");let _t=rt.clientSecret||t;if(Nr(rt)){await j({result:Pr(rt,W),session:rt,sessionId:rt.id||W,autoCompleted:!1});return}if(rt.status==="expired")throw Fo(rt);try{if(b.autoProcessingPending){let Vt=(await new ni(Re).waitForCheckoutSessionCompletion(b.autoProcessingPending.sessionId,{initialDelayMs:b.autoProcessingPending.retryAfterMs})).data.session;if(!Nr(Vt))throw Do(Vt);await j({result:Pr(Vt,W),session:Vt,sessionId:Vt.id||W,autoCompleted:!1});return}if(b.autoProcessingError){if(b.autoProcessingError.type==="3ds_required"&&b.autoProcessingError.nextActionRedirectUrl&&W&&_t){let He=new AbortController;H.current=He;let $e;try{$e=await as({billingApiUrl:Re,sessionId:W,nonce:_t,nextActionRedirectUrl:b.autoProcessingError.nextActionRedirectUrl,signal:He.signal})}finally{H.current===He&&(H.current=null)}if($e.status==="declined")throw ur({type:$e.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:$e.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:b.autoProcessingError.checkoutMethod});let xt=(await new ni(Re).waitForCheckoutSessionCompletion(W,{initialDelayMs:0,nonce:_t})).data.session;if(!Nr(xt))throw ur({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:b.autoProcessingError.checkoutMethod});await j({result:Pr(xt,W),session:xt,sessionId:xt.id||W,autoCompleted:!1});return}throw ur(b.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:b.autoProcessingError.checkoutMethod})}if(X?.fromCreateSession&&b.autoProcessingAttempted===!0)throw ur({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let ht=await Kr({billingApiUrl:Re,sessionId:W??rt.id,session:rt,nonce:_t});if(ht.type!=="success")throw ur({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await j({result:ht.result,session:rt,sessionId:rt.id||W,autoCompleted:!1})}catch(ht){let He=kr(ht),$e=rt.id||W;await q(He,{emitDecline:!0,method:He.checkoutMethod??ho}),Jc(He,$e)&&$e&&le.current&&Ae({sessionId:$e,errorMessage:He.message,nonce:_t||void 0})}},[t,Re,q,j]),qe=mr(async b=>{if(Ie.onClick?.(b),!(b.defaultPrevented||fe||oe)){if(Ae(null),e&&re){let W=new Xr("Provide either sessionId or create-session props, not both.","validation_error");await q(W),le.current&&(xe(null),Ne(null));return}if(!e&&!re){let W=new Xr("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await q(W),le.current&&(xe(null),Ne(null));return}D(!0),Ne(null),B(!1),xe("processing");try{let W=new ni(Re);if(e){let X=await W.getUnifiedCheckoutSession(e,t);await Ce(X,e);return}try{let X=await W.createAndFetchSession({...re});await Ce(X,X.data.session?.id??null,{fromCreateSession:!0})}catch(X){if(X instanceof Xr&&X.code==="session_auto_completed"){await j({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw X}}catch(W){await q(Wc(W,"Automatic payment failed. Please try again."))}finally{le.current&&(xe(null),Ne(null),D(!1))}}},[Ie,re,fe,oe,t,Ce,Re,e,q,j]),R=mr(b=>{let W=ke.current;Ae(null),We.current?.({result:b,session:null,sessionId:W?.sessionId??null,autoCompleted:!1})},[]),G=mr(b=>{nt.current?.(b)},[]),_=mr(b=>{Be.current?.(b)},[]),P=So(()=>Yc(V),[V]),Ze=So(()=>{let b=P?.buttonsLayout??Hc(pe);return ne?{...b,...ne,cardButton:{...b.cardButton,...ne.cardButton}}:b},[P,pe,ne]),pt=So(()=>{let b=P?.appearance;return C?b?{...b,...C,variables:{...b.variables,...C.variables}}:C:b},[C,P]),J=pt?.variables,Qe=J?.colorPrimary??"#4A49FF",Ke=J?.colorPrimaryHover??lo(Qe,.12),mt=J?.borderRadius??"8px";return ed(Qc,{children:[Jr("button",{...Ie,type:kt,onClick:qe,disabled:fe||oe,"aria-busy":oe,style:{width:"100%",...Ve===void 0?{boxSizing:"border-box",height:Gc,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...Ze.cardButton,...qa({themeBundle:P,resolvedPrimaryColor:Qe,resolvedBorderRadius:mt,submitButtonStyle:Ze.submitButton,explicitPrimaryColor:J?.colorPrimary}),fontSize:Ze.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:fe||oe?"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:fe||oe?.6:1,...Le},onMouseEnter:b=>{Ie.onMouseEnter?.(b),!b.defaultPrevented&&!fe&&!oe&&(P||J?.colorPrimary)&&(b.currentTarget.style.backgroundColor=Ke)},onMouseLeave:b=>{Ie.onMouseLeave?.(b),!b.defaultPrevented&&(P||J?.colorPrimary)&&(b.currentTarget.style.backgroundColor=Qe)},onMouseDown:b=>{Ie.onMouseDown?.(b),b.defaultPrevented||(b.currentTarget.style.transform="scale(0.985)")},onMouseUp:b=>{Ie.onMouseUp?.(b),b.defaultPrevented||(b.currentTarget.style.transform="scale(1)")},children:Jr(Mr,{content:Ve})}),_e&&Jr(qn,{status:_e,errorMessage:Te,authorized:Pe}),se&&Jr("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:b=>{b.target===b.currentTarget&&Ae(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:Jr("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:Jr(ti,{sessionId:se.sessionId,nonce:se.nonce,checkoutMode:"full",billingApiUrl:Re,locale:ge,theme:V,...pt?{appearance:pt}:{},buttonsTheme:pe,buttonsStyles:ne,initialErrorMessage:se.errorMessage,cardTitleContent:null,onComplete:R,onError:G,onDecline:_})})})]})}export{jo as DirectPayPalButton,Zc as FloPayAutomaticPaymentButton,ol as FloPayCardSetup,rl as FloPayCardSetupError,ti as FloPayCheckout,Ko as FloPayProvider,$a as SplitCardForm,va as VaultCardFields,tp as dropThirdPartyOnlyError,fl as useCheckout,cr as useFloPay,wa as usePayPalFloPay};