@flopay/react 1.8.3 → 1.8.4

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.cjs CHANGED
@@ -1,12 +1,12 @@
1
- "use strict";var Fs=Object.create;var Bo=Object.defineProperty;var Ds=Object.getOwnPropertyDescriptor;var Ns=Object.getOwnPropertyNames;var Ls=Object.getPrototypeOf,Os=Object.prototype.hasOwnProperty;var zs=(e,t)=>{for(var n in t)Bo(e,n,{get:t[n],enumerable:!0})},Pi=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Ns(t))!Os.call(e,o)&&o!==n&&Bo(e,o,{get:()=>t[o],enumerable:!(r=Ds(t,o))||r.enumerable});return e};var Ci=(e,t,n)=>(n=e!=null?Fs(Ls(e)):{},Pi(t||!e||!e.__esModule?Bo(n,"default",{value:e,enumerable:!0}):n,e)),Us=e=>Pi(Bo({},"__esModule",{value:!0}),e);var Ll={};zs(Ll,{DirectPayPalButton:()=>co,FloPayAutomaticPaymentButton:()=>us,FloPayCardSetup:()=>ms,FloPayCardSetupError:()=>vo,FloPayCheckout:()=>na,FloPayProvider:()=>po,SplitCardForm:()=>Zo,VaultCardFields:()=>jr,dropThirdPartyOnlyError:()=>ys.dropThirdPartyOnlyError,useCheckout:()=>xi,useFloPay:()=>rr,usePayPalFloPay:()=>Lo});module.exports=Us(Ll);var ys=require("@flopay/shared");var ra=require("@flopay/js"),bn=require("@flopay/shared"),qe=require("react");var ht=require("react/jsx-runtime");function qs(){return(0,ht.jsxs)(ht.Fragment,{children:[(0,ht.jsxs)("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:[(0,ht.jsx)("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),(0,ht.jsx)("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",(0,ht.jsx)("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:(0,ht.jsx)("path",{d:"M9 18l6-6-6-6"})})]})}function $s(){return(0,ht.jsx)(ht.Fragment,{children:"Go back"})}function js(){return(0,ht.jsx)(ht.Fragment,{children:"Secure card checkout"})}function Ar(e){return e!==void 0&&(e===""||e===null||e===!1)}function Mr({content:e}){return(0,ht.jsx)(ht.Fragment,{children:e===void 0?(0,ht.jsx)(qs,{}):e})}function Br({content:e}){return(0,ht.jsx)(ht.Fragment,{children:e===void 0?(0,ht.jsx)($s,{}):e})}function oo({content:e}){return(0,ht.jsx)(ht.Fragment,{children:e===void 0?(0,ht.jsx)(js,{}):e})}var Fr=require("@flopay/shared");function Si(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 ba(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 wi(e,t){let n=e.products??[...(e.subscriptions??[]).map(i=>({type:"subscription",code:i.code??i.providerPlanId,name:i.subscriptionName??i.providerPlanName??i.code??i.providerPlanId??null,quantity:i.quantity??1,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount,currency:i.currency,metadata:i.metadata})),...(e.items??[]).map(i=>({type:"item",code:i.code??i.providerItemId,name:i.itemName??i.providerItemName??i.code??i.providerItemId??null,quantity:i.quantity??1,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount,currency:i.currency,metadata:i.metadata}))],r=n.reduce((i,d)=>i+(d.overrideAmount??d.totalAmount??0),0),o=e.currency??n.find(i=>i.currency)?.currency??"USD";return{id:"",clientSecret:"",mode:n.some(i=>i.type==="subscription")?"subscription":"payment",amount:Math.round(r*100),currency:o,status:"open",captureMethod:e.captureMethod,customer:{id:e.account.userId,email:e.account.email??"",firstName:e.account.firstName,lastName:e.account.lastName,gender:e.account.gender??void 0,city:e.account.city??void 0,state:e.account.state??void 0,country:e.account.country??void 0,zip:e.account.zip??void 0},successUrl:e.successUrl,cancelUrl:e.cancelUrl,checkoutMode:t??e.checkoutMode??"full",products:n.map((i,d)=>({uuid:`synthetic-${i.type??"item"}-${d}`,checkoutSessionId:"",type:i.type??"item",code:i.code,name:i.name??null,quantity:i.quantity??1,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount??null,currency:i.currency??o,metadata:i.metadata??null}))}}function 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 va(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,i=typeof t=="string"?n?.declineCode:n?.declineCode??t.declineCode;return{method:e,message:r,...o?{code:o}:{},...i?{declineCode:i}:{}}}var Vs=[{match:/^paypal authorization required\.?$/i,replacement:"For your additional security, please re-authenticate this payment via PayPal."}];function dr(e){if(typeof e!="string")return e??void 0;let t=e.trim();if(!t)return e;for(let{match:n,replacement:r}of Vs)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 Dr(e){return e?.status==="authorized"||e?.status==="complete"}function ki(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function Fo(e){let t=ki(e);return new Fr.FloPayError(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function Do(e){let t=ki(e);return new Fr.FloPayError(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 No(e,t){return e==="processing"||(0,Fr.isMoneySettledOutcome)(e,t)}function Ii(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}function Ei(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?{mode:"setup"}:{mode:"payment",amount:e}}function ao(e){let t=[e?.id,e?.originalPaymentMethodId];for(let n of t)if(typeof n=="string"&&n.startsWith("pm_"))return n}var Ir=require("@flopay/js"),Se=require("@flopay/shared"),I=Ci(require("react"),1);var Pa=require("react"),In=(0,Pa.createContext)({flopay:null,paypalFlopay:null,billingApiUrl:""}),zn=(0,Pa.createContext)({session:null,loading:!1,error:null});var qo=require("@flopay/js"),Tt=require("@flopay/shared"),Fi=require("@paypal/paypal-js"),_=require("react");var Ri=require("@flopay/shared"),En=require("react");var Un=require("react/jsx-runtime");function io(e){return!!(e.firstName?.trim()||e.lastName?.trim())}function Nr(){let[e,t]=(0,En.useState)(null),n=(0,En.useRef)(null),r=(0,En.useRef)(0),o=(0,En.useCallback)((d,c)=>(n.current?.(null),r.current+=1,t({id:r.current,methodLabel:d,identity:c}),new Promise(v=>{n.current=v})),[]),i=(0,En.useCallback)(d=>{let c=n.current;n.current=null,t(null),c?.(d)},[]);return(0,En.useEffect)(()=>()=>{n.current?.(null),n.current=null},[]),{request:e,collect:o,finish:i}}function Cr({identity:e,methodLabel:t,onComplete:n,onCancel:r,submitting:o=!1,testId:i="flopay-buyer-identity-pane"}){let[d,c]=(0,En.useState)(e.email?.trim()??""),[v,g]=(0,En.useState)([e.firstName,e.lastName].filter(Boolean).join(" ")),h=(0,Ri.isValidEmail)(d.trim())&&!!v.trim();return(0,Un.jsxs)("div",{"data-testid":i,style:{display:"flex",flexDirection:"column",gap:"0.75rem",padding:"0.875rem",border:"1px solid #d1d5db",borderRadius:8,background:"#fff",color:"#262833"},children:[(0,Un.jsxs)("div",{style:{fontWeight:700},children:["Continue with ",t]}),(0,Un.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",(0,Un.jsx)("input",{type:"email",autoComplete:"email",required:!0,value:d,onChange:f=>c(f.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]}),(0,Un.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Full name",(0,Un.jsx)("input",{type:"text",autoComplete:"name",required:!0,value:v,onChange:f=>g(f.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]}),(0,Un.jsxs)("div",{style:{display:"flex",gap:"0.5rem"},children:[r&&(0,Un.jsx)("button",{type:"button",onClick:r,style:{flex:1,minHeight:42},children:"Cancel"}),(0,Un.jsxs)("button",{type:"button",disabled:!h||o,onClick:()=>{let f=kn(v);n({email:d.trim(),firstName:f.firstName,lastName:f.lastName})},style:{flex:2,minHeight:42},children:["Continue with ",t]})]})]})}function Hs(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 Sr(e){if(typeof e!="string")return;let t=e.trim();return/^[a-z0-9_.-]{1,64}$/i.test(t)?t:void 0}function nr(e){if(typeof e!="object"||e===null)return;let t=e;return Sr(t.code)??Sr(t.type)??Sr(t.name)}function Lr(e){if(!(typeof e!="object"||e===null))return Sr(e.decline_code)}function so(e){return typeof e!="object"||e===null?!1:Sr(e.type)?.toLowerCase()==="card_error"||Lr(e)!==void 0}function ur(e){let t=Hs(e)?.toLowerCase()??"",r=`${nr(e)?.toLowerCase()??""} ${t}`;return r.includes("popup")&&r.includes("block")}var _i=require("@flopay/shared"),lo=require("react");function rr(){return(0,lo.useContext)(In).flopay}function Lo(){return(0,lo.useContext)(In).paypalFlopay??null}function xi(){return(0,lo.useContext)(zn)}function Ti(){return(0,lo.useContext)(In).billingApiUrl||(0,_i.resolveBillingApiUrl)()}var Ai=require("@flopay/shared"),wr=require("react");function ze(e){if(!e)return;let t=n=>{console.error("[FloPay] Merchant callback failed; checkout continued.",n)};try{Promise.resolve(e()).catch(t)}catch(n){t(n)}}var Oo=require("react"),zo=typeof window>"u"?Oo.useEffect:Oo.useLayoutEffect;var Ks={"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 Ys(e){return e==="stripe"||e==="paypal"?e:void 0}function Ws(e){let t=Ys(e.provider),n={schemaVersion:Ai.FLO_INSTRUMENT_SCHEMA_VERSION,...t?{gateway:t}:{}};if(e.class==="lifecycle"){let r=Ks[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 Ca=new Set(["checkout_mount","sdk_loaded","form_rendered","card_expanded"]);function Or(e,t){let n=(0,wr.useRef)(e);n.current=e;let r=(0,wr.useRef)(new Set),o=(0,wr.useRef)(t),i=(0,wr.useRef)(t);return zo(()=>{i.current=t,o.current!==t&&(o.current=t,r.current.clear())},[t]),(0,wr.useCallback)(d=>{if(i.current!==t)return;let c=Ws(d);if(c){if(Ca.has(c.name)){if(r.current.has(c.name))return;r.current.add(c.name)}ze(()=>n.current?.(c))}},[t])}var Gs=Symbol.for("@flopay/js.telemetry.bridge.v1"),Js=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function Xs(){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 Zs(e){let t=Xs(),n=(o,i)=>o?o.bind(e):i,r=n(e.now,t.now);return{error:n(e.error,t.error),log:n(e.log,t.log),performance:n(e.performance,t.performance),terminal:n(e.terminal,t.terminal),now:r,elapsed:e.elapsed?e.elapsed.bind(e):o=>Math.max(0,r()-o),setCheckoutContext:n(e.setCheckoutContext,t.setCheckoutContext),beginCheckout:n(e.beginCheckout,t.beginCheckout),disable:n(e.disable,t.disable),subscribe:n(e.subscribe,t.subscribe),flush:n(e.flush,t.flush),destroy:n(e.destroy,t.destroy)}}function Uo(e){let t=globalThis[Js];return Zs(t?.(e)??{})}function jt(e){if(e)return e[Gs]}var hn=require("react/jsx-runtime"),$o=45,Qs=1e3,el=11e3,tl=["https://www.paypal.com","https://www.sandbox.paypal.com"],Mi="We couldn't open PayPal. Try again or choose another payment method.",nl={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 Bi(e){return e.includes("No ack for postMessage init()")&&tl.some(t=>e.includes(t))&&e.includes("10000ms")}function rl(e){return e?`${Mi} Allow pop-ups for this site, then try again.`:Mi}function ol(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 Di({sessionId:e,nonce:t,billingApiUrl:n,email:r,billingName:o,onBuyerIdentityReady:i,clientId:d,environment:c,currency:v,isSubscription:g,providerObjectType:h,onTokenizedBody:f,onComplete:D,onErrorChange:B,onDecline:p,onTechnicalFailure:C,isProcessing:he=!1,onLoadStateChange:V,onInitializationStateChange:S,allowAutomaticRetry:me=!0,onButtonClick:H,runBeforeButtonClick:de,session:K,existingOrderId:be,telemetry:$e,telemetryContext:we,onInstrument:gt,debug:Fe=!1}){let Ee=rr(),Re=Or(gt,e),oe=(0,_.useMemo)(()=>{if(Ee)return null;let k=Uo({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:Tt.SDK_VERSION,enabled:$e!==!1});return k.setCheckoutContext(we??{}),k.beginCheckout(we??{}),k},[n,Ee,$e,we?.checkoutMode,we?.layout]),ne=(0,_.useMemo)(()=>jt(Ee),[Ee]);(0,_.useEffect)(()=>()=>{oe&&oe.flush().catch(()=>{}).finally(()=>oe.destroy())},[oe]);let O=(0,_.useMemo)(()=>({error:k=>{ne?ne.error(k):oe?.error(k),Re({class:"technical_error",errorCode:k.requestCategory==="intent_create"?"PAYMENT_PROCESSING_FAILED":k.errorCode,requestCategory:k.requestCategory,provider:k.provider})},log:k=>{ne?ne.log(k):oe?.log(k),Re({class:"lifecycle",name:k.name,provider:k.provider})},performance:k=>{ne?ne.performance(k):oe?.performance(k)},terminal:k=>{ne?ne.terminal(k):oe?.terminal(k)},startTiming:()=>ne?.now()??oe?.now()??0,elapsed:k=>ne?.elapsed(k)??Math.max(0,(oe?.now()??k)-k)}),[Re,ne,oe]),ue=(0,_.useRef)(null),We=(0,_.useRef)(0),re=(0,_.useRef)(null),Te=(0,_.useRef)(!1),[Z,T]=(0,_.useState)(!1),[j,Ae]=(0,_.useState)(!1),[ye,Q]=(0,_.useState)(0),De=(0,_.useRef)(0),[Qe,Ze]=(0,_.useState)(!1),_e=(0,_.useRef)(!1),ie=(0,_.useRef)(!1),[ae,X]=(0,_.useState)(!1),[xe,Le]=(0,_.useState)(!1),[L,ee]=(0,_.useState)(!1),[A,R]=(0,_.useState)(!1),rt=kn(o??[K?.customer?.firstName,K?.customer?.lastName].filter(Boolean).join(" ")),St=!L&&i&&!(0,Tt.isValidEmail)(r?.trim()||K?.customer?.email?.trim())?{email:r?.trim()||K?.customer?.email?.trim(),firstName:rt.firstName,lastName:rt.lastName}:null,{request:ve,collect:ct,finish:st}=Nr(),ot=(0,_.useMemo)(()=>n.replace(/\/+$/,""),[n]),Ge=h??(g?"subscription":"order"),b=h==="order"||h==="setup_token",G=(0,_.useMemo)(()=>JSON.stringify([ot,d,v,c??"",Ge,b,e,be??""]),[ot,d,v,c,be,Ge,b,e]),et=(0,_.useRef)(G),dt=et.current!==G,[Mt,Bt]=(0,_.useState)([]),se=k=>{Fe&&Bt(ut=>[...ut,`${new Date().toISOString().slice(11,23)} ${k}`])},Ve=(0,_.useRef)(f),Wt=(0,_.useRef)(D),wt=(0,_.useRef)(B),Ot=(0,_.useRef)(p),xn=(0,_.useRef)(C),Tn=(0,_.useRef)(H),Qn=(0,_.useRef)(V),Gt=(0,_.useRef)(S),sn=(0,_.useRef)(i),ln=(0,_.useRef)(de),Ft=(0,_.useRef)(K),Pn=(0,_.useRef)(r),bt=(0,_.useRef)(o),sr=(0,_.useRef)(null),Vt=(0,_.useRef)(e),lr=(0,_.useRef)(t),Dt=(0,_.useRef)(null),$n=(0,_.useRef)(0),at=(0,_.useRef)(null),Rt=(0,_.useRef)(null),_t=(0,_.useRef)(new Map),Qt=(0,_.useRef)(new Map),cn=(0,_.useRef)(!1);(0,_.useEffect)(()=>(cn.current=!0,()=>{cn.current=!1}),[]),(0,_.useEffect)(()=>{Ve.current=f},[f]),(0,_.useEffect)(()=>{sn.current=i},[i]),(0,_.useEffect)(()=>{Wt.current=D},[D]),(0,_.useEffect)(()=>{wt.current=B},[B]),(0,_.useEffect)(()=>{Ot.current=p},[p]),(0,_.useEffect)(()=>{xn.current=C},[C]),(0,_.useEffect)(()=>{Tn.current=H},[H]),(0,_.useEffect)(()=>{Qn.current=V},[V]),(0,_.useEffect)(()=>{Gt.current=S},[S]),(0,_.useEffect)(()=>{ln.current=de},[de]),(0,_.useEffect)(()=>{Ft.current=K},[K]),(0,_.useEffect)(()=>{Pn.current=r},[r]),(0,_.useEffect)(()=>{bt.current=o},[o]),(0,_.useEffect)(()=>{lr.current=t},[t]),(0,_.useEffect)(()=>{Vt.current!==e&&(Vt.current=e,sr.current=null,ee(!1),R(!1))},[e]),(0,_.useEffect)(()=>{De.current=ye},[ye]),(0,_.useEffect)(()=>{Qe&&re.current?.focus()},[Qe,ye]);let dn=(0,_.useCallback)(()=>{window.setTimeout(()=>{re.current?.focus()},0)},[]),jn=(0,_.useCallback)(async k=>{R(!0);try{await sn.current?.(k),sr.current=k,Pn.current=k.email,bt.current=[k.firstName,k.lastName].filter(Boolean).join(" "),ee(!0),ze(()=>wt.current?.(null))}catch(ut){let Ke=ut instanceof Error?ut.message:"Buyer details could not be attached to checkout.";ze(()=>wt.current?.(Ke))}finally{R(!1)}},[]),Vn=(0,_.useCallback)(()=>{T(!1),Q(k=>k+1)},[]),zt=(0,_.useCallback)(()=>{Ze(!1),(ue.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??ue.current)?.focus?.()},[]);(0,_.useEffect)(()=>{!Z||!Te.current||(Te.current=!1,zt())},[zt,Z,ye]);let le=(0,_.useCallback)((k,ut)=>{let Ke=xn.current;if(Ke){Ke("paypal",k,ut);return}wt.current?.(rl(ut?.popupBlocked??ur(k)))},[]),Cn=()=>{at.current?.timer&&(clearTimeout(at.current.timer),at.current.timer=null)},An=()=>{Cn();let k=$n.current+1;return $n.current=k,Rt.current=null,at.current={generation:k,timer:null,yieldedControl:!1},Ze(!1),k},er=k=>k!==void 0&&at.current?.generation!==k?!1:(Cn(),at.current=null,Rt.current=null,!0),yr=k=>{let ut=k?.generation??at.current?.generation??$n.current;(!k?.generation||at.current?.generation===ut)&&(Cn(),at.current=null),Rt.current=ut,k?.showRetry&&Ze(!0),k?.remount&&Vn(),k?.focus!==!1&&dn()},Er=k=>at.current?.generation===k&&Rt.current!==k,Mn=k=>{typeof document<"u"&&document.visibilityState!=="visible"||(Cn(),k.timer=setTimeout(()=>{at.current?.generation===k.generation&&(at.current=null,Rt.current=k.generation,le(new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}),Ze(!0),Vn(),dn())},600))},un=()=>{let k=at.current;k?.yieldedControl&&Mn(k)},Oe=()=>{let k=at.current;k&&(k.yieldedControl=!0,Cn())},Jt=k=>{let ut=Dt.current;return ut&&Qt.current.set(k,ut),k};(0,_.useEffect)(()=>{let k=()=>{document.visibilityState==="visible"?un():Oe()};return document.addEventListener("visibilitychange",k),window.addEventListener("focus",un),window.addEventListener("blur",Oe),()=>{document.removeEventListener("visibilitychange",k),window.removeEventListener("focus",un),window.removeEventListener("blur",Oe),Cn()}},[]),(0,_.useEffect)(()=>{et.current!==G&&(et.current=G,_e.current=!1,ie.current=!1,T(!1),Ae(!1),X(!1),Gt.current?.("loading"))},[G]),(0,_.useEffect)(()=>{ze(()=>Qn.current?.(Z&&!ae))},[Z,ae]);let Nt=(0,Tt.normalizeGatewayEnvironment)(c);(0,_.useEffect)(()=>{let k=d?`${d.slice(0,6)}\u2026(len ${d.length})`:"(empty)",ut=typeof navigator<"u"?navigator.userAgent:"(no navigator)";if(se(`mount clientId=${k} env=${c??"(unset)"}\u2192${Nt??"live"} ccy=${v} sub=${g}`),se(`ua=${ut.slice(0,80)}${ut.length>80?"\u2026":""}`),!d){se("FAIL: clientId empty \u2014 gateway misconfigured"),X(!0),O.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(!ue.current){se("FAIL: containerRef not attached");return}We.current=O.startTiming(),O.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let Ke=!1,pn=!1,tt=()=>Ke||pn,Ut,cr=!1,Kn=()=>{Ut=(0,Tt.generateIdempotencyKey)(),Ut||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),cr=!0},Sn=null,Xt=!1,mn=null,yn=!1,Ne=()=>{!mn||yn||(yn=!0,mn.close().catch(()=>{}))},kt=null,xt=()=>{kt!==null&&(O.log({name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal"}),O.performance({stage:"overlay_return",durationMs:O.elapsed(kt),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal"}),kt=null)},Bn=!1,fn=ue.current,Fn=null,Dn=null,qt=[],nn=m=>{if(!m||typeof m.getBoundingClientRect!="function")return"(no rect)";let y=m.getBoundingClientRect();return`${Math.round(y.width)}\xD7${Math.round(y.height)}`},rn=m=>{if(!m)return"(empty)";try{let y=new URL(m,typeof window<"u"?window.location.href:"https://localhost"),x=y.pathname.toLowerCase();return x.includes("checkcaptcha")||x.includes("captcha")?`CAPTCHA(${y.host}${x})`:x.includes("risk")||x.includes("challenge")?`RISK(${y.host}${x})`:x.includes("smart/buttons")?`smart-buttons(${y.host})`:`${y.host}${x}`.slice(0,100)}catch{return m.slice(0,80)}},tr=m=>{let y=m.getAttribute("src"),x=m.getAttribute("srcdoc"),Me=m.getAttribute("name"),J=m.getAttribute("sandbox"),q=[];return y&&q.push(`src=${rn(y)}`),x&&q.push(`srcdoc[${x.length}ch]`),!y&&!x&&q.push("src=(empty) srcdoc=(empty)"),Me&&q.push(`name=${Me.slice(0,40)}`),J!==null&&q.push(`sandbox="${J.slice(0,40)}"`),q.join(" ")},Rr=m=>{if(!(m instanceof HTMLIFrameElement))return"";try{let y=m.contentDocument;if(!y)return"cd=null";let x=y.body?.children.length??0,Me=y.body?.innerHTML.length??0,J=y.head?.innerHTML.length??0;return`cd=same-origin readyState=${y.readyState} body[${x}children,${Me}ch] head[${J}ch]`}catch(y){return`cd=cross-origin(${y.message.slice(0,30)})`}},Nn=[],Yn=m=>{if(tt())return;let y=m.message??String(m.error??"(no message)");y&&(y.toLowerCase().includes("paypal")||y.toLowerCase().includes("zoid")||y.toLowerCase().includes("postrobot")||y.toLowerCase().includes("storage"))&&(se(`window:error ${y.slice(0,140)}`),Nn.push(y))},Zt=m=>{if(tt())return;let y=m.reason instanceof Error?m.reason.message:String(m.reason??"(no reason)");y&&(y.toLowerCase().includes("paypal")||y.toLowerCase().includes("zoid")||y.toLowerCase().includes("postrobot")||y.toLowerCase().includes("storage"))&&(se(`window:rejection ${y.slice(0,140)}`),Nn.push(y))};Fe&&typeof window<"u"&&(window.addEventListener("error",Yn),window.addEventListener("unhandledrejection",Zt));let it={value:0};if(Fe&&typeof PerformanceObserver<"u")try{Dn=new PerformanceObserver(m=>{if(!tt())for(let y of m.getEntries()){if(!y.name.toLowerCase().includes("paypal"))continue;it.value+=1;let x=Math.round(y.duration);se(`net ${x}ms ${y.name.slice(0,90)}`)}}),Dn.observe({type:"resource",buffered:!0})}catch{}let Ht=()=>{for(Fn?.disconnect(),Fn=null,Dn?.disconnect(),Dn=null;qt.length;)clearTimeout(qt.pop());Fe&&typeof window<"u"&&(window.removeEventListener("error",Yn),window.removeEventListener("unhandledrejection",Zt))},N=m=>{if(!m)return!1;let y=m.toLowerCase();return y.includes("zoid destroyed")||y.includes("destroyed all components")||y.includes("window closed")||y.includes("detected container element removed")},M=m=>{if(tt()||N(m))return;let y=dr(m)??m;ze(()=>wt.current?.(y))},te=m=>{Ke||(X(!0),m.includes("paypal_ineligible")||O.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:",m))},ce=(m,y=!1)=>{if(Ke)return;let x=_e.current||!me;if(Xt)return;Xt=!0,pn=!0,Ht(),Ne();let Me=y||Bi(m);if(Me&&me&&!_e.current){_e.current=!0,T(!1),Le(!1),Ae(!0),Gt.current?.("retrying"),Sn=setTimeout(()=>{Ke||Q(J=>J+1)},Qs);return}if(Me||x){if(T(!1),Le(!1),Ae(!1),X(!0),Gt.current?.("exhausted"),!ie.current){ie.current=!0;let J=Bi(m)?"paypal_init_timeout":y?"paypal_render_timeout":"paypal_init_failure";console.error("[FloPay] Direct PayPal initialization failed:",J)}return}te(m)};X(!1);let Ye=async(m,y=Dt.current)=>{if(tt())return;let x=y?.sessionId??e;if(Ve.current){await Ve.current(m,{sessionId:x,accountPatch:y?.accountPatch,nonce:y?.nonce});return}let Me=O.startTiming();O.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let J=()=>{O.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),O.performance({stage:"processing",durationMs:O.elapsed(Me),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})};try{let q=Ft.current,Xe=y?.accountPatch?.email??Pn.current,nt=y?.accountPatch?.userId??q?.customer?.id??q?.accountData?.userId??"",Pe=await new qo.PaymentAPI(ot,{telemetry:!1}).processPayment(nt,{sessionId:x,nonce:y?.nonce??lr.current,tokenizedData:m,accountData:{userId:nt,email:Xe??q?.customer?.email??"",firstName:y?.accountPatch?.firstName??q?.customer?.firstName??q?.accountData?.firstName??"",lastName:y?.accountPatch?.lastName??q?.customer?.lastName??q?.accountData?.lastName??"",country:y?.accountPatch?.country??q?.customer?.country??q?.accountData?.country??void 0,zip:y?.accountPatch?.zip??q?.customer?.zip??q?.accountData?.zip??void 0}});if(Pe.ok){if(pn||Ke&&cn.current)return;J(),O.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),ze(()=>Wt.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(tt())return;let z=await Pe.json().catch(()=>null),ge=z?.message??"PayPal payment failed.",lt=dr(ge)??ge;J(),Pe.status===400&&(typeof z?.declineCode=="string"||!Array.isArray(z?.fields))?O.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):Pe.status===400||Pe.status===422?O.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx"}):O.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:Pe.status>=500?"5xx":Pe.status>=400?"4xx":Pe.status>=300?"3xx":"unknown",failureCategory:Pe.status>=500?"server_error":void 0}),M(lt),ze(()=>Ot.current?.($t("paypal",lt,{code:z?.code,declineCode:z?.declineCode})));return}catch(q){if(tt())return;J(),O.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let Xe=q instanceof Error?q.message:"PayPal payment failed.",nt=dr(Xe)??Xe;M(nt),ze(()=>Ot.current?.($t("paypal",nt)));return}},pe=()=>new Tt.FloPayError("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),U=m=>tt()?Promise.reject(pe()):Promise.resolve(m),w=async m=>{if(tt())throw pe();cr||Kn();let y=Dt.current,x=y?.sessionId??e,Me=y?.nonce??lr.current;O.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let J;try{J=await new qo.PaymentAPI(ot,{telemetry:!1}).createSessionIntent(x,Me??"",b?{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:Tt.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE,paymentMethodId:null,intentKind:Ge==="setup_token"?"setup":"payment"}:{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"},{idempotencyKey:Ut})}catch(q){throw O.error({...(0,Tt.classifyTelemetryFailure)(q,"PAYMENT_PROCESSING_FAILED","unknown"),stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"}),q}if(tt())throw pe();if(J.provider!=="paypal"||J.providerObjectType!==Ge)throw new Error(m);return O.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),J.providerObjectId},P=(m,y)=>{let x=y?.nonce??lr.current;if(!x)return;let Me=y?.sessionId??e,J=Lr(m)??nr(m)??"provider_declined";new qo.PaymentAPI(ot,{telemetry:!1}).reportSessionIntentDecline(Me,x,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:J}).catch(()=>{})},Y=ye;se("loadScript:scheduled (deferred 1 tick)");let pt=null,vt=setTimeout(()=>{if(Ke){se("loadScript:skipped (cancelled before defer ran)");return}se("loadScript:start");let m=Nt==="live"?"production":Nt;pt=(0,Fi.loadScript)({clientId:d,currency:v,...Ge==="subscription"?{intent:"subscription",vault:!0}:Ge==="order"?{intent:"capture"}:{},...m?{environment:m}:{},...m==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}}),pt.then(y=>{if(se(`loadScript:resolved inactive=${tt()} ns=${!!y} buttons=${!!y?.Buttons}`),tt())return;if(!y?.Buttons){se("FAIL: namespace missing Buttons factory"),ce("PayPal SDK did not expose the Buttons factory.");return}O.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),O.performance({stage:"provider_ready",durationMs:O.elapsed(We.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),O.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let x=async(fe,Pe)=>{if(tt()||De.current!==Y)return;let z=fe.vaultSetupToken??fe.subscriptionID??fe.orderID??"",ge=z?Qt.current.get(z):_t.current.get(Y);if(!(!ge||!Er(ge.generation))&&er(ge.generation)){Qt.current.delete(z),_t.current.delete(ge.surfaceKey),xt();try{if(Le(!0),ze(()=>wt.current?.(null)),!z)throw new Tt.FloPayError("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});let lt=Ft.current,Lt=kn(bt.current??[lt?.customer?.firstName,lt?.customer?.lastName].filter(Boolean).join(" ")),ke={email:ge.accountPatch?.email?.trim()||Pn.current?.trim()||lt?.customer?.email?.trim(),firstName:ge.accountPatch?.firstName?.trim()||Lt.firstName,lastName:ge.accountPatch?.lastName?.trim()||Lt.lastName};if(!(0,Tt.isValidEmail)(ke.email)||!(ke.firstName||ke.lastName))try{let gn=ol(await Pe?.order?.get?.());ke={email:gn.email||ke.email,firstName:gn.firstName||ke.firstName,lastName:gn.lastName||ke.lastName}}catch{}if(sn.current&&(!(0,Tt.isValidEmail)(ke.email)||!(ke.firstName||ke.lastName))){let gn=await ct("PayPal",ke);if(!gn)return;ke=gn}(0,Tt.isValidEmail)(ke.email)&&(ke.firstName||ke.lastName)&&(ge.accountPatch={...ge.accountPatch,...ke},await sn.current?.(ke)),await Ye(Ge==="setup_token"?{id:z,type:"paypal_setup_token",isPaypal:!0,gateway:"paypal",paymentMethodType:Tt.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE}:b?{id:z,isPaypal:!0,gateway:"paypal",paymentMethodType:Tt.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE}:{id:z,isPaypal:!0},ge)}catch(lt){M(lt instanceof Error?lt.message:"PayPal capture failed.")}finally{tt()||Le(!1)}}},Me=y.Buttons({style:{layout:"horizontal",height:$o,tagline:!1},onClick:async(fe,Pe)=>{if(tt()){await Pe.reject();return}Kn();let z=ln.current,ge={accountPatch:sr.current??void 0};if(z)try{let ke=await z("paypal");if(tt()){await Pe.reject();return}if(!ke.proceed){Dt.current=null,_t.current.delete(Y),await Pe.reject();return}ge={sessionId:ke.sessionId,accountPatch:{...sr.current,...ke.accountPatch},nonce:ke.nonce}}catch(ke){se(`onClick:runBeforeButtonClick rejected msg=${(ke instanceof Error?ke.message:String(ke)).slice(0,120)}`),Dt.current=null,_t.current.delete(Y),await Pe.reject();return}ze(()=>Tn.current?.("paypal"));let Lt={generation:An(),surfaceKey:Y,...ge};Dt.current=Lt,_t.current.set(Y,Lt),await Pe.resolve(),O.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),O.log({name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),O.log({name:"provider.overlay.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),kt=O.startTiming()},createOrder:Ge==="order"?be?()=>U(be).then(Jt):()=>w("Failed to create PayPal order.").then(Jt):void 0,createSubscription:Ge==="subscription"?be?()=>U(be).then(Jt):()=>w("Failed to create PayPal subscription.").then(Jt):void 0,createVaultSetupToken:Ge==="setup_token"?()=>w("Failed to create PayPal setup token.").then(Jt):void 0,onApprove:x,onCancel:()=>{if(tt())return;let fe=_t.current.get(Y)??Dt.current;fe&&_t.current.delete(fe.surfaceKey),Dt.current=null,xt(),O.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),Te.current=!0,yr({generation:fe?.generation,remount:!0,focus:!1})},onError:fe=>{if(tt()||De.current!==Y)return;let Pe=fe instanceof Error?fe.message:"PayPal failed to render.";if(se(`onError rendered=${Bn} msg=${Pe.slice(0,120)}`),Bn){let z=_t.current.get(Y)??Dt.current;if(z&&!Er(z.generation)||!z&&Rt.current===$n.current)return;if(N(Pe)){er(z?.generation);return}if(xt(),so(fe)){O.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),P(fe,z),ze(()=>Ot.current?.($t("paypal",Pe))),z&&_t.current.delete(z.surfaceKey),Dt.current=null,er(z?.generation);return}let ge=Pe.toLowerCase();O.error({errorCode:ge.includes("popup")&&ge.includes("block")?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),z&&_t.current.delete(z.surfaceKey),Dt.current=null,yr({generation:z?.generation,remount:!0,showRetry:!0,focus:!0}),le(fe,{code:"paypal_runtime_failed"});return}ce(Pe)}}),J=Me.isEligible();if(se(`isEligible=${J}`),O.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!J){T(!1),ce("PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}mn=Me,Fe&&se(`container:dims ${nn(fn)} visibility=${typeof document<"u"?document.visibilityState:"(no document)"}`),Fe&&typeof MutationObserver<"u"&&(Fn=new MutationObserver(fe=>{if(!tt()){for(let Pe of fe)if(Pe.type==="childList")Pe.addedNodes.forEach(z=>{if(!(z instanceof Element))return;let ge=z.tagName.toLowerCase(),lt=(z.getAttribute("title")??"").slice(0,40),Lt=ge==="iframe"?` ${tr(z)}`:"";se(`child+ ${ge}${lt?` title="${lt}"`:""}${Lt} dims=${nn(z)}`)});else if(Pe.type==="attributes"&&Pe.target instanceof Element){let z=Pe.target;if(z.tagName.toLowerCase()!=="iframe")continue;let ge=Pe.attributeName;(ge==="src"||ge==="srcdoc")&&se(`attr~ iframe ${ge}=${ge==="srcdoc"?`[${(z.getAttribute("srcdoc")??"").length}ch]`:rn(z.getAttribute("src"))} dims=${nn(z)}`)}}}),Fn.observe(fn,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let Xe=fe=>{if(tt()||Bn)return;let Pe=fn.querySelectorAll("iframe"),z=typeof document<"u"&&"hasStorageAccess"in document;se(`watchdog:${fe} container=${nn(fn)} children=${fn.childElementCount} iframes=${Pe.length} visibility=${typeof document<"u"?document.visibilityState:"(no document)"} cookies=${typeof navigator<"u"?navigator.cookieEnabled:"?"} hasStorageAccessApi=${z} paypalNetRequests=${it.value}`),Pe.forEach((ge,lt)=>{let Lt=(ge.getAttribute("title")??"").slice(0,40);se(` iframe[${lt}] ${nn(ge)}${Lt?` title="${Lt}"`:""} ${tr(ge)}`);let ke=Rr(ge);ke&&se(` ${ke}`)}),Nn.length===0&&se(" (no PayPal/zoid window errors captured)")};Fe&&(qt.push(setTimeout(()=>Xe("3s"),3e3)),qt.push(setTimeout(()=>Xe("8s"),8e3)),qt.push(setTimeout(()=>Xe("15s"),15e3))),se("render:start");let nt=O.startTiming();qt.push(setTimeout(()=>{tt()||Bn||(se("watchdog:11s retryable render timeout"),ce("PayPal Buttons render did not settle within 11000ms.",!0))},el)),Me.render(fn).then(()=>{if(se(`render:resolved inactive=${tt()}`),Ht(),tt()){Ne();return}Bn=!0,T(!0),Ae(!1),Gt.current?.("ready"),O.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),O.performance({stage:"checkout_render",durationMs:O.elapsed(nt),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}).catch(fe=>{let Pe=fe instanceof Error?fe.message:"PayPal failed to render.";se(`render:rejected msg=${Pe.slice(0,120)}`),Ht(),ce(Pe)})}).catch(y=>{let x=y instanceof Error?y.message:"PayPal SDK failed to load.";se(`loadScript:rejected msg=${x.slice(0,120)}`),ce(x)})},0);return()=>{Ke=!0,clearTimeout(vt),Sn&&clearTimeout(Sn),Ht(),Ne()}},[me,ot,d,v,c,Ge,b,e,be,ye,O,ct]);let Hn=Fe?(0,hn.jsxs)("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:ae?"#fef2f2":"#f3f4f6",border:`1px solid ${ae?"#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=${Z} failed=${ae})`,Mt.length===0?`
1
+ "use strict";var Fs=Object.create;var Bo=Object.defineProperty;var Ns=Object.getOwnPropertyDescriptor;var Ds=Object.getOwnPropertyNames;var Ls=Object.getPrototypeOf,Os=Object.prototype.hasOwnProperty;var zs=(e,t)=>{for(var n in t)Bo(e,n,{get:t[n],enumerable:!0})},Pi=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Ds(t))!Os.call(e,o)&&o!==n&&Bo(e,o,{get:()=>t[o],enumerable:!(r=Ns(t,o))||r.enumerable});return e};var Ci=(e,t,n)=>(n=e!=null?Fs(Ls(e)):{},Pi(t||!e||!e.__esModule?Bo(n,"default",{value:e,enumerable:!0}):n,e)),Us=e=>Pi(Bo({},"__esModule",{value:!0}),e);var Ll={};zs(Ll,{DirectPayPalButton:()=>co,FloPayAutomaticPaymentButton:()=>us,FloPayCardSetup:()=>ms,FloPayCardSetupError:()=>vo,FloPayCheckout:()=>na,FloPayProvider:()=>po,SplitCardForm:()=>Zo,VaultCardFields:()=>jr,dropThirdPartyOnlyError:()=>ys.dropThirdPartyOnlyError,useCheckout:()=>xi,useFloPay:()=>rr,usePayPalFloPay:()=>Lo});module.exports=Us(Ll);var ys=require("@flopay/shared");var ra=require("@flopay/js"),bn=require("@flopay/shared"),qe=require("react");var ht=require("react/jsx-runtime");function qs(){return(0,ht.jsxs)(ht.Fragment,{children:[(0,ht.jsxs)("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:[(0,ht.jsx)("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),(0,ht.jsx)("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",(0,ht.jsx)("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:(0,ht.jsx)("path",{d:"M9 18l6-6-6-6"})})]})}function $s(){return(0,ht.jsx)(ht.Fragment,{children:"Go back"})}function js(){return(0,ht.jsx)(ht.Fragment,{children:"Secure card checkout"})}function Ar(e){return e!==void 0&&(e===""||e===null||e===!1)}function Mr({content:e}){return(0,ht.jsx)(ht.Fragment,{children:e===void 0?(0,ht.jsx)(qs,{}):e})}function Br({content:e}){return(0,ht.jsx)(ht.Fragment,{children:e===void 0?(0,ht.jsx)($s,{}):e})}function oo({content:e}){return(0,ht.jsx)(ht.Fragment,{children:e===void 0?(0,ht.jsx)(js,{}):e})}var Fr=require("@flopay/shared");function Si(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 ba(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 wi(e,t){let n=e.products??[...(e.subscriptions??[]).map(i=>({type:"subscription",code:i.code??i.providerPlanId,name:i.subscriptionName??i.providerPlanName??i.code??i.providerPlanId??null,quantity:i.quantity??1,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount,currency:i.currency,metadata:i.metadata})),...(e.items??[]).map(i=>({type:"item",code:i.code??i.providerItemId,name:i.itemName??i.providerItemName??i.code??i.providerItemId??null,quantity:i.quantity??1,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount,currency:i.currency,metadata:i.metadata}))],r=n.reduce((i,d)=>i+(d.overrideAmount??d.totalAmount??0),0),o=e.currency??n.find(i=>i.currency)?.currency??"USD";return{id:"",clientSecret:"",mode:n.some(i=>i.type==="subscription")?"subscription":"payment",amount:Math.round(r*100),currency:o,status:"open",captureMethod:e.captureMethod,customer:{id:e.account.userId,email:e.account.email??"",firstName:e.account.firstName,lastName:e.account.lastName,gender:e.account.gender??void 0,city:e.account.city??void 0,state:e.account.state??void 0,country:e.account.country??void 0,zip:e.account.zip??void 0},successUrl:e.successUrl,cancelUrl:e.cancelUrl,checkoutMode:t??e.checkoutMode??"full",products:n.map((i,d)=>({uuid:`synthetic-${i.type??"item"}-${d}`,checkoutSessionId:"",type:i.type??"item",code:i.code,name:i.name??null,quantity:i.quantity??1,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount??null,currency:i.currency??o,metadata:i.metadata??null}))}}function 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 va(e,t){return t?{...e,...t}:e}function jt(e,t,n){let r=typeof t=="string"?t:t.message,o=typeof t=="string"?n?.code:n?.code??t.code,i=typeof t=="string"?n?.declineCode:n?.declineCode??t.declineCode;return{method:e,message:r,...o?{code:o}:{},...i?{declineCode:i}:{}}}var Vs=[{match:/^paypal authorization required\.?$/i,replacement:"For your additional security, please re-authenticate this payment via PayPal."}];function dr(e){if(typeof e!="string")return e??void 0;let t=e.trim();if(!t)return e;for(let{match:n,replacement:r}of Vs)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 ki(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function Fo(e){let t=ki(e);return new Fr.FloPayError(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function No(e){let t=ki(e);return new Fr.FloPayError(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 Do(e,t){return e==="processing"||(0,Fr.isMoneySettledOutcome)(e,t)}function Ii(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}function Ei(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?{mode:"setup"}:{mode:"payment",amount:e}}function ao(e){let t=[e?.id,e?.originalPaymentMethodId];for(let n of t)if(typeof n=="string"&&n.startsWith("pm_"))return n}var Ir=require("@flopay/js"),Se=require("@flopay/shared"),I=Ci(require("react"),1);var Pa=require("react"),In=(0,Pa.createContext)({flopay:null,paypalFlopay:null,billingApiUrl:""}),zn=(0,Pa.createContext)({session:null,loading:!1,error:null});var qo=require("@flopay/js"),Tt=require("@flopay/shared"),Fi=require("@paypal/paypal-js"),_=require("react");var Ri=require("@flopay/shared"),En=require("react");var Un=require("react/jsx-runtime");function io(e){return!!(e.firstName?.trim()||e.lastName?.trim())}function Dr(){let[e,t]=(0,En.useState)(null),n=(0,En.useRef)(null),r=(0,En.useRef)(0),o=(0,En.useCallback)((d,c)=>(n.current?.(null),r.current+=1,t({id:r.current,methodLabel:d,identity:c}),new Promise(v=>{n.current=v})),[]),i=(0,En.useCallback)(d=>{let c=n.current;n.current=null,t(null),c?.(d)},[]);return(0,En.useEffect)(()=>()=>{n.current?.(null),n.current=null},[]),{request:e,collect:o,finish:i}}function Cr({identity:e,methodLabel:t,onComplete:n,onCancel:r,submitting:o=!1,testId:i="flopay-buyer-identity-pane"}){let[d,c]=(0,En.useState)(e.email?.trim()??""),[v,g]=(0,En.useState)([e.firstName,e.lastName].filter(Boolean).join(" ")),h=(0,Ri.isValidEmail)(d.trim())&&!!v.trim();return(0,Un.jsxs)("div",{"data-testid":i,style:{display:"flex",flexDirection:"column",gap:"0.75rem",padding:"0.875rem",border:"1px solid #d1d5db",borderRadius:8,background:"#fff",color:"#262833"},children:[(0,Un.jsxs)("div",{style:{fontWeight:700},children:["Continue with ",t]}),(0,Un.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",(0,Un.jsx)("input",{type:"email",autoComplete:"email","data-testid":"flopay-email",required:!0,value:d,onChange:f=>c(f.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]}),(0,Un.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Full name",(0,Un.jsx)("input",{type:"text",autoComplete:"name","data-testid":"flopay-name",required:!0,value:v,onChange:f=>g(f.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]}),(0,Un.jsxs)("div",{style:{display:"flex",gap:"0.5rem"},children:[r&&(0,Un.jsx)("button",{type:"button",onClick:r,style:{flex:1,minHeight:42},children:"Cancel"}),(0,Un.jsxs)("button",{type:"button",disabled:!h||o,onClick:()=>{let f=kn(v);n({email:d.trim(),firstName:f.firstName,lastName:f.lastName})},style:{flex:2,minHeight:42},children:["Continue with ",t]})]})]})}function Hs(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 Sr(e){if(typeof e!="string")return;let t=e.trim();return/^[a-z0-9_.-]{1,64}$/i.test(t)?t:void 0}function nr(e){if(typeof e!="object"||e===null)return;let t=e;return Sr(t.code)??Sr(t.type)??Sr(t.name)}function Lr(e){if(!(typeof e!="object"||e===null))return Sr(e.decline_code)}function so(e){return typeof e!="object"||e===null?!1:Sr(e.type)?.toLowerCase()==="card_error"||Lr(e)!==void 0}function ur(e){let t=Hs(e)?.toLowerCase()??"",r=`${nr(e)?.toLowerCase()??""} ${t}`;return r.includes("popup")&&r.includes("block")}var _i=require("@flopay/shared"),lo=require("react");function rr(){return(0,lo.useContext)(In).flopay}function Lo(){return(0,lo.useContext)(In).paypalFlopay??null}function xi(){return(0,lo.useContext)(zn)}function Ti(){return(0,lo.useContext)(In).billingApiUrl||(0,_i.resolveBillingApiUrl)()}var Ai=require("@flopay/shared"),wr=require("react");function ze(e){if(!e)return;let t=n=>{console.error("[FloPay] Merchant callback failed; checkout continued.",n)};try{Promise.resolve(e()).catch(t)}catch(n){t(n)}}var Oo=require("react"),zo=typeof window>"u"?Oo.useEffect:Oo.useLayoutEffect;var Ks={"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 Ys(e){return e==="stripe"||e==="paypal"?e:void 0}function Ws(e){let t=Ys(e.provider),n={schemaVersion:Ai.FLO_INSTRUMENT_SCHEMA_VERSION,...t?{gateway:t}:{}};if(e.class==="lifecycle"){let r=Ks[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 Ca=new Set(["checkout_mount","sdk_loaded","form_rendered","card_expanded"]);function Or(e,t){let n=(0,wr.useRef)(e);n.current=e;let r=(0,wr.useRef)(new Set),o=(0,wr.useRef)(t),i=(0,wr.useRef)(t);return zo(()=>{i.current=t,o.current!==t&&(o.current=t,r.current.clear())},[t]),(0,wr.useCallback)(d=>{if(i.current!==t)return;let c=Ws(d);if(c){if(Ca.has(c.name)){if(r.current.has(c.name))return;r.current.add(c.name)}ze(()=>n.current?.(c))}},[t])}var Gs=Symbol.for("@flopay/js.telemetry.bridge.v1"),Js=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function Xs(){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 Zs(e){let t=Xs(),n=(o,i)=>o?o.bind(e):i,r=n(e.now,t.now);return{error:n(e.error,t.error),log:n(e.log,t.log),performance:n(e.performance,t.performance),terminal:n(e.terminal,t.terminal),now:r,elapsed:e.elapsed?e.elapsed.bind(e):o=>Math.max(0,r()-o),setCheckoutContext:n(e.setCheckoutContext,t.setCheckoutContext),beginCheckout:n(e.beginCheckout,t.beginCheckout),disable:n(e.disable,t.disable),subscribe:n(e.subscribe,t.subscribe),flush:n(e.flush,t.flush),destroy:n(e.destroy,t.destroy)}}function Uo(e){let t=globalThis[Js];return Zs(t?.(e)??{})}function Vt(e){if(e)return e[Gs]}var hn=require("react/jsx-runtime"),$o=45,Qs=1e3,el=11e3,tl=["https://www.paypal.com","https://www.sandbox.paypal.com"],Mi="We couldn't open PayPal. Try again or choose another payment method.",nl={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 Bi(e){return e.includes("No ack for postMessage init()")&&tl.some(t=>e.includes(t))&&e.includes("10000ms")}function rl(e){return e?`${Mi} Allow pop-ups for this site, then try again.`:Mi}function ol(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 Ni({sessionId:e,nonce:t,billingApiUrl:n,email:r,billingName:o,onBuyerIdentityReady:i,clientId:d,environment:c,currency:v,isSubscription:g,providerObjectType:h,onTokenizedBody:f,onComplete:N,onErrorChange:B,onDecline:p,onTechnicalFailure:C,isProcessing:he=!1,onLoadStateChange:V,onInitializationStateChange:S,allowAutomaticRetry:me=!0,onButtonClick:H,runBeforeButtonClick:de,session:K,existingOrderId:be,telemetry:$e,telemetryContext:we,onInstrument:gt,debug:Fe=!1}){let Ee=rr(),Re=Or(gt,e),oe=(0,_.useMemo)(()=>{if(Ee)return null;let k=Uo({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:Tt.SDK_VERSION,enabled:$e!==!1});return k.setCheckoutContext(we??{}),k.beginCheckout(we??{}),k},[n,Ee,$e,we?.checkoutMode,we?.layout]),ne=(0,_.useMemo)(()=>Vt(Ee),[Ee]);(0,_.useEffect)(()=>()=>{oe&&oe.flush().catch(()=>{}).finally(()=>oe.destroy())},[oe]);let O=(0,_.useMemo)(()=>({error:k=>{ne?ne.error(k):oe?.error(k),Re({class:"technical_error",errorCode:k.requestCategory==="intent_create"?"PAYMENT_PROCESSING_FAILED":k.errorCode,requestCategory:k.requestCategory,provider:k.provider})},log:k=>{ne?ne.log(k):oe?.log(k),Re({class:"lifecycle",name:k.name,provider:k.provider})},performance:k=>{ne?ne.performance(k):oe?.performance(k)},terminal:k=>{ne?ne.terminal(k):oe?.terminal(k)},startTiming:()=>ne?.now()??oe?.now()??0,elapsed:k=>ne?.elapsed(k)??Math.max(0,(oe?.now()??k)-k)}),[Re,ne,oe]),ue=(0,_.useRef)(null),We=(0,_.useRef)(0),re=(0,_.useRef)(null),Ae=(0,_.useRef)(!1),[Z,T]=(0,_.useState)(!1),[j,Me]=(0,_.useState)(!1),[ye,Q]=(0,_.useState)(0),Ne=(0,_.useRef)(0),[Qe,Ze]=(0,_.useState)(!1),_e=(0,_.useRef)(!1),ie=(0,_.useRef)(!1),[ae,X]=(0,_.useState)(!1),[xe,Le]=(0,_.useState)(!1),[L,ee]=(0,_.useState)(!1),[A,E]=(0,_.useState)(!1),rt=kn(o??[K?.customer?.firstName,K?.customer?.lastName].filter(Boolean).join(" ")),St=!L&&i&&!(0,Tt.isValidEmail)(r?.trim()||K?.customer?.email?.trim())?{email:r?.trim()||K?.customer?.email?.trim(),firstName:rt.firstName,lastName:rt.lastName}:null,{request:ve,collect:ct,finish:st}=Dr(),ot=(0,_.useMemo)(()=>n.replace(/\/+$/,""),[n]),Ge=h??(g?"subscription":"order"),b=h==="order"||h==="setup_token",G=(0,_.useMemo)(()=>JSON.stringify([ot,d,v,c??"",Ge,b,e,be??""]),[ot,d,v,c,be,Ge,b,e]),et=(0,_.useRef)(G),dt=et.current!==G,[Mt,Bt]=(0,_.useState)([]),se=k=>{Fe&&Bt(ut=>[...ut,`${new Date().toISOString().slice(11,23)} ${k}`])},Ve=(0,_.useRef)(f),Gt=(0,_.useRef)(N),wt=(0,_.useRef)(B),zt=(0,_.useRef)(p),xn=(0,_.useRef)(C),Tn=(0,_.useRef)(H),Qn=(0,_.useRef)(V),Jt=(0,_.useRef)(S),sn=(0,_.useRef)(i),ln=(0,_.useRef)(de),Ft=(0,_.useRef)(K),Pn=(0,_.useRef)(r),bt=(0,_.useRef)(o),sr=(0,_.useRef)(null),Ht=(0,_.useRef)(e),lr=(0,_.useRef)(t),Nt=(0,_.useRef)(null),$n=(0,_.useRef)(0),at=(0,_.useRef)(null),Rt=(0,_.useRef)(null),_t=(0,_.useRef)(new Map),Qt=(0,_.useRef)(new Map),cn=(0,_.useRef)(!1);(0,_.useEffect)(()=>(cn.current=!0,()=>{cn.current=!1}),[]),(0,_.useEffect)(()=>{Ve.current=f},[f]),(0,_.useEffect)(()=>{sn.current=i},[i]),(0,_.useEffect)(()=>{Gt.current=N},[N]),(0,_.useEffect)(()=>{wt.current=B},[B]),(0,_.useEffect)(()=>{zt.current=p},[p]),(0,_.useEffect)(()=>{xn.current=C},[C]),(0,_.useEffect)(()=>{Tn.current=H},[H]),(0,_.useEffect)(()=>{Qn.current=V},[V]),(0,_.useEffect)(()=>{Jt.current=S},[S]),(0,_.useEffect)(()=>{ln.current=de},[de]),(0,_.useEffect)(()=>{Ft.current=K},[K]),(0,_.useEffect)(()=>{Pn.current=r},[r]),(0,_.useEffect)(()=>{bt.current=o},[o]),(0,_.useEffect)(()=>{lr.current=t},[t]),(0,_.useEffect)(()=>{Ht.current!==e&&(Ht.current=e,sr.current=null,ee(!1),E(!1))},[e]),(0,_.useEffect)(()=>{Ne.current=ye},[ye]),(0,_.useEffect)(()=>{Qe&&re.current?.focus()},[Qe,ye]);let dn=(0,_.useCallback)(()=>{window.setTimeout(()=>{re.current?.focus()},0)},[]),jn=(0,_.useCallback)(async k=>{E(!0);try{await sn.current?.(k),sr.current=k,Pn.current=k.email,bt.current=[k.firstName,k.lastName].filter(Boolean).join(" "),ee(!0),ze(()=>wt.current?.(null))}catch(ut){let Ke=ut instanceof Error?ut.message:"Buyer details could not be attached to checkout.";ze(()=>wt.current?.(Ke))}finally{E(!1)}},[]),Vn=(0,_.useCallback)(()=>{T(!1),Q(k=>k+1)},[]),Ut=(0,_.useCallback)(()=>{Ze(!1),(ue.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??ue.current)?.focus?.()},[]);(0,_.useEffect)(()=>{!Z||!Ae.current||(Ae.current=!1,Ut())},[Ut,Z,ye]);let le=(0,_.useCallback)((k,ut)=>{let Ke=xn.current;if(Ke){Ke("paypal",k,ut);return}wt.current?.(rl(ut?.popupBlocked??ur(k)))},[]),Cn=()=>{at.current?.timer&&(clearTimeout(at.current.timer),at.current.timer=null)},An=()=>{Cn();let k=$n.current+1;return $n.current=k,Rt.current=null,at.current={generation:k,timer:null,yieldedControl:!1},Ze(!1),k},er=k=>k!==void 0&&at.current?.generation!==k?!1:(Cn(),at.current=null,Rt.current=null,!0),yr=k=>{let ut=k?.generation??at.current?.generation??$n.current;(!k?.generation||at.current?.generation===ut)&&(Cn(),at.current=null),Rt.current=ut,k?.showRetry&&Ze(!0),k?.remount&&Vn(),k?.focus!==!1&&dn()},Er=k=>at.current?.generation===k&&Rt.current!==k,Mn=k=>{typeof document<"u"&&document.visibilityState!=="visible"||(Cn(),k.timer=setTimeout(()=>{at.current?.generation===k.generation&&(at.current=null,Rt.current=k.generation,le(new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}),Ze(!0),Vn(),dn())},600))},un=()=>{let k=at.current;k?.yieldedControl&&Mn(k)},Oe=()=>{let k=at.current;k&&(k.yieldedControl=!0,Cn())},Xt=k=>{let ut=Nt.current;return ut&&Qt.current.set(k,ut),k};(0,_.useEffect)(()=>{let k=()=>{document.visibilityState==="visible"?un():Oe()};return document.addEventListener("visibilitychange",k),window.addEventListener("focus",un),window.addEventListener("blur",Oe),()=>{document.removeEventListener("visibilitychange",k),window.removeEventListener("focus",un),window.removeEventListener("blur",Oe),Cn()}},[]),(0,_.useEffect)(()=>{et.current!==G&&(et.current=G,_e.current=!1,ie.current=!1,T(!1),Me(!1),X(!1),Jt.current?.("loading"))},[G]),(0,_.useEffect)(()=>{ze(()=>Qn.current?.(Z&&!ae))},[Z,ae]);let Dt=(0,Tt.normalizeGatewayEnvironment)(c);(0,_.useEffect)(()=>{let k=d?`${d.slice(0,6)}\u2026(len ${d.length})`:"(empty)",ut=typeof navigator<"u"?navigator.userAgent:"(no navigator)";if(se(`mount clientId=${k} env=${c??"(unset)"}\u2192${Dt??"live"} ccy=${v} sub=${g}`),se(`ua=${ut.slice(0,80)}${ut.length>80?"\u2026":""}`),!d){se("FAIL: clientId empty \u2014 gateway misconfigured"),X(!0),O.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(!ue.current){se("FAIL: containerRef not attached");return}We.current=O.startTiming(),O.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let Ke=!1,pn=!1,tt=()=>Ke||pn,qt,cr=!1,Kn=()=>{qt=(0,Tt.generateIdempotencyKey)(),qt||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),cr=!0},Sn=null,Lt=!1,mn=null,yn=!1,De=()=>{!mn||yn||(yn=!0,mn.close().catch(()=>{}))},kt=null,xt=()=>{kt!==null&&(O.log({name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal"}),O.performance({stage:"overlay_return",durationMs:O.elapsed(kt),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal"}),kt=null)},Bn=!1,fn=ue.current,Fn=null,Nn=null,$t=[],en=m=>{if(!m||typeof m.getBoundingClientRect!="function")return"(no rect)";let y=m.getBoundingClientRect();return`${Math.round(y.width)}\xD7${Math.round(y.height)}`},rn=m=>{if(!m)return"(empty)";try{let y=new URL(m,typeof window<"u"?window.location.href:"https://localhost"),x=y.pathname.toLowerCase();return x.includes("checkcaptcha")||x.includes("captcha")?`CAPTCHA(${y.host}${x})`:x.includes("risk")||x.includes("challenge")?`RISK(${y.host}${x})`:x.includes("smart/buttons")?`smart-buttons(${y.host})`:`${y.host}${x}`.slice(0,100)}catch{return m.slice(0,80)}},tr=m=>{let y=m.getAttribute("src"),x=m.getAttribute("srcdoc"),Te=m.getAttribute("name"),J=m.getAttribute("sandbox"),q=[];return y&&q.push(`src=${rn(y)}`),x&&q.push(`srcdoc[${x.length}ch]`),!y&&!x&&q.push("src=(empty) srcdoc=(empty)"),Te&&q.push(`name=${Te.slice(0,40)}`),J!==null&&q.push(`sandbox="${J.slice(0,40)}"`),q.join(" ")},Rr=m=>{if(!(m instanceof HTMLIFrameElement))return"";try{let y=m.contentDocument;if(!y)return"cd=null";let x=y.body?.children.length??0,Te=y.body?.innerHTML.length??0,J=y.head?.innerHTML.length??0;return`cd=same-origin readyState=${y.readyState} body[${x}children,${Te}ch] head[${J}ch]`}catch(y){return`cd=cross-origin(${y.message.slice(0,30)})`}},Dn=[],Yn=m=>{if(tt())return;let y=m.message??String(m.error??"(no message)");y&&(y.toLowerCase().includes("paypal")||y.toLowerCase().includes("zoid")||y.toLowerCase().includes("postrobot")||y.toLowerCase().includes("storage"))&&(se(`window:error ${y.slice(0,140)}`),Dn.push(y))},Zt=m=>{if(tt())return;let y=m.reason instanceof Error?m.reason.message:String(m.reason??"(no reason)");y&&(y.toLowerCase().includes("paypal")||y.toLowerCase().includes("zoid")||y.toLowerCase().includes("postrobot")||y.toLowerCase().includes("storage"))&&(se(`window:rejection ${y.slice(0,140)}`),Dn.push(y))};Fe&&typeof window<"u"&&(window.addEventListener("error",Yn),window.addEventListener("unhandledrejection",Zt));let it={value:0};if(Fe&&typeof PerformanceObserver<"u")try{Nn=new PerformanceObserver(m=>{if(!tt())for(let y of m.getEntries()){if(!y.name.toLowerCase().includes("paypal"))continue;it.value+=1;let x=Math.round(y.duration);se(`net ${x}ms ${y.name.slice(0,90)}`)}}),Nn.observe({type:"resource",buffered:!0})}catch{}let Kt=()=>{for(Fn?.disconnect(),Fn=null,Nn?.disconnect(),Nn=null;$t.length;)clearTimeout($t.pop());Fe&&typeof window<"u"&&(window.removeEventListener("error",Yn),window.removeEventListener("unhandledrejection",Zt))},D=m=>{if(!m)return!1;let y=m.toLowerCase();return y.includes("zoid destroyed")||y.includes("destroyed all components")||y.includes("window closed")||y.includes("detected container element removed")},M=m=>{if(tt()||D(m))return;let y=dr(m)??m;ze(()=>wt.current?.(y))},te=m=>{Ke||(X(!0),m.includes("paypal_ineligible")||O.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:",m))},ce=(m,y=!1)=>{if(Ke)return;let x=_e.current||!me;if(Lt)return;Lt=!0,pn=!0,Kt(),De();let Te=y||Bi(m);if(Te&&me&&!_e.current){_e.current=!0,T(!1),Le(!1),Me(!0),Jt.current?.("retrying"),Sn=setTimeout(()=>{Ke||Q(J=>J+1)},Qs);return}if(Te||x){if(T(!1),Le(!1),Me(!1),X(!0),Jt.current?.("exhausted"),!ie.current){ie.current=!0;let J=Bi(m)?"paypal_init_timeout":y?"paypal_render_timeout":"paypal_init_failure";console.error("[FloPay] Direct PayPal initialization failed:",J)}return}te(m)};X(!1);let Ye=async(m,y=Nt.current)=>{if(tt())return;let x=y?.sessionId??e;if(Ve.current){await Ve.current(m,{sessionId:x,accountPatch:y?.accountPatch,nonce:y?.nonce});return}let Te=O.startTiming();O.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let J=()=>{O.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),O.performance({stage:"processing",durationMs:O.elapsed(Te),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})};try{let q=Ft.current,Xe=y?.accountPatch?.email??Pn.current,nt=y?.accountPatch?.userId??q?.customer?.id??q?.accountData?.userId??"",Pe=await new qo.PaymentAPI(ot,{telemetry:!1}).processPayment(nt,{sessionId:x,nonce:y?.nonce??lr.current,tokenizedData:m,accountData:{userId:nt,email:Xe??q?.customer?.email??"",firstName:y?.accountPatch?.firstName??q?.customer?.firstName??q?.accountData?.firstName??"",lastName:y?.accountPatch?.lastName??q?.customer?.lastName??q?.accountData?.lastName??"",country:y?.accountPatch?.country??q?.customer?.country??q?.accountData?.country??void 0,zip:y?.accountPatch?.zip??q?.customer?.zip??q?.accountData?.zip??void 0}});if(Pe.ok){if(pn||Ke&&cn.current)return;J(),O.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),ze(()=>Gt.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(tt())return;let z=await Pe.json().catch(()=>null),ge=z?.message??"PayPal payment failed.",lt=dr(ge)??ge;J(),Pe.status===400&&(typeof z?.declineCode=="string"||!Array.isArray(z?.fields))?O.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):Pe.status===400||Pe.status===422?O.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx"}):O.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:Pe.status>=500?"5xx":Pe.status>=400?"4xx":Pe.status>=300?"3xx":"unknown",failureCategory:Pe.status>=500?"server_error":void 0}),M(lt),ze(()=>zt.current?.(jt("paypal",lt,{code:z?.code,declineCode:z?.declineCode})));return}catch(q){if(tt())return;J(),O.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let Xe=q instanceof Error?q.message:"PayPal payment failed.",nt=dr(Xe)??Xe;M(nt),ze(()=>zt.current?.(jt("paypal",nt)));return}},pe=()=>new Tt.FloPayError("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),U=m=>tt()?Promise.reject(pe()):Promise.resolve(m),w=async m=>{if(tt())throw pe();cr||Kn();let y=Nt.current,x=y?.sessionId??e,Te=y?.nonce??lr.current;O.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let J;try{J=await new qo.PaymentAPI(ot,{telemetry:!1}).createSessionIntent(x,Te??"",b?{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:Tt.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE,paymentMethodId:null,intentKind:Ge==="setup_token"?"setup":"payment"}:{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"},{idempotencyKey:qt})}catch(q){throw O.error({...(0,Tt.classifyTelemetryFailure)(q,"PAYMENT_PROCESSING_FAILED","unknown"),stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"}),q}if(tt())throw pe();if(J.provider!=="paypal"||J.providerObjectType!==Ge)throw new Error(m);return O.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),J.providerObjectId},P=(m,y)=>{let x=y?.nonce??lr.current;if(!x)return;let Te=y?.sessionId??e,J=Lr(m)??nr(m)??"provider_declined";new qo.PaymentAPI(ot,{telemetry:!1}).reportSessionIntentDecline(Te,x,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:J}).catch(()=>{})},Y=ye;se("loadScript:scheduled (deferred 1 tick)");let pt=null,vt=setTimeout(()=>{if(Ke){se("loadScript:skipped (cancelled before defer ran)");return}se("loadScript:start");let m=Dt==="live"?"production":Dt;pt=(0,Fi.loadScript)({clientId:d,currency:v,...Ge==="subscription"?{intent:"subscription",vault:!0}:Ge==="order"?{intent:"capture"}:{},...m?{environment:m}:{},...m==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}}),pt.then(y=>{if(se(`loadScript:resolved inactive=${tt()} ns=${!!y} buttons=${!!y?.Buttons}`),tt())return;if(!y?.Buttons){se("FAIL: namespace missing Buttons factory"),ce("PayPal SDK did not expose the Buttons factory.");return}O.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),O.performance({stage:"provider_ready",durationMs:O.elapsed(We.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),O.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let x=async(fe,Pe)=>{if(tt()||Ne.current!==Y)return;let z=fe.vaultSetupToken??fe.subscriptionID??fe.orderID??"",ge=z?Qt.current.get(z):_t.current.get(Y);if(!(!ge||!Er(ge.generation))&&er(ge.generation)){Qt.current.delete(z),_t.current.delete(ge.surfaceKey),xt();try{if(Le(!0),ze(()=>wt.current?.(null)),!z)throw new Tt.FloPayError("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});let lt=Ft.current,Ot=kn(bt.current??[lt?.customer?.firstName,lt?.customer?.lastName].filter(Boolean).join(" ")),ke={email:ge.accountPatch?.email?.trim()||Pn.current?.trim()||lt?.customer?.email?.trim(),firstName:ge.accountPatch?.firstName?.trim()||Ot.firstName,lastName:ge.accountPatch?.lastName?.trim()||Ot.lastName};if(!(0,Tt.isValidEmail)(ke.email)||!(ke.firstName||ke.lastName))try{let gn=ol(await Pe?.order?.get?.());ke={email:gn.email||ke.email,firstName:gn.firstName||ke.firstName,lastName:gn.lastName||ke.lastName}}catch{}if(sn.current&&(!(0,Tt.isValidEmail)(ke.email)||!(ke.firstName||ke.lastName))){let gn=await ct("PayPal",ke);if(!gn)return;ke=gn}(0,Tt.isValidEmail)(ke.email)&&(ke.firstName||ke.lastName)&&(ge.accountPatch={...ge.accountPatch,...ke},await sn.current?.(ke)),await Ye(Ge==="setup_token"?{id:z,type:"paypal_setup_token",isPaypal:!0,gateway:"paypal",paymentMethodType:Tt.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE}:b?{id:z,isPaypal:!0,gateway:"paypal",paymentMethodType:Tt.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE}:{id:z,isPaypal:!0},ge)}catch(lt){M(lt instanceof Error?lt.message:"PayPal capture failed.")}finally{tt()||Le(!1)}}},Te=y.Buttons({style:{layout:"horizontal",height:$o,tagline:!1},onClick:async(fe,Pe)=>{if(tt()){await Pe.reject();return}Kn();let z=ln.current,ge={accountPatch:sr.current??void 0};if(z)try{let ke=await z("paypal");if(tt()){await Pe.reject();return}if(!ke.proceed){Nt.current=null,_t.current.delete(Y),await Pe.reject();return}ge={sessionId:ke.sessionId,accountPatch:{...sr.current,...ke.accountPatch},nonce:ke.nonce}}catch(ke){se(`onClick:runBeforeButtonClick rejected msg=${(ke instanceof Error?ke.message:String(ke)).slice(0,120)}`),Nt.current=null,_t.current.delete(Y),await Pe.reject();return}ze(()=>Tn.current?.("paypal"));let Ot={generation:An(),surfaceKey:Y,...ge};Nt.current=Ot,_t.current.set(Y,Ot),await Pe.resolve(),O.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),O.log({name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),O.log({name:"provider.overlay.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),kt=O.startTiming()},createOrder:Ge==="order"?be?()=>U(be).then(Xt):()=>w("Failed to create PayPal order.").then(Xt):void 0,createSubscription:Ge==="subscription"?be?()=>U(be).then(Xt):()=>w("Failed to create PayPal subscription.").then(Xt):void 0,createVaultSetupToken:Ge==="setup_token"?()=>w("Failed to create PayPal setup token.").then(Xt):void 0,onApprove:x,onCancel:()=>{if(tt())return;let fe=_t.current.get(Y)??Nt.current;fe&&_t.current.delete(fe.surfaceKey),Nt.current=null,xt(),O.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),Ae.current=!0,yr({generation:fe?.generation,remount:!0,focus:!1})},onError:fe=>{if(tt()||Ne.current!==Y)return;let Pe=fe instanceof Error?fe.message:"PayPal failed to render.";if(se(`onError rendered=${Bn} msg=${Pe.slice(0,120)}`),Bn){let z=_t.current.get(Y)??Nt.current;if(z&&!Er(z.generation)||!z&&Rt.current===$n.current)return;if(D(Pe)){er(z?.generation);return}if(xt(),so(fe)){O.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),P(fe,z),ze(()=>zt.current?.(jt("paypal",Pe))),z&&_t.current.delete(z.surfaceKey),Nt.current=null,er(z?.generation);return}let ge=Pe.toLowerCase();O.error({errorCode:ge.includes("popup")&&ge.includes("block")?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),z&&_t.current.delete(z.surfaceKey),Nt.current=null,yr({generation:z?.generation,remount:!0,showRetry:!0,focus:!0}),le(fe,{code:"paypal_runtime_failed"});return}ce(Pe)}}),J=Te.isEligible();if(se(`isEligible=${J}`),O.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!J){T(!1),ce("PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}mn=Te,Fe&&se(`container:dims ${en(fn)} visibility=${typeof document<"u"?document.visibilityState:"(no document)"}`),Fe&&typeof MutationObserver<"u"&&(Fn=new MutationObserver(fe=>{if(!tt()){for(let Pe of fe)if(Pe.type==="childList")Pe.addedNodes.forEach(z=>{if(!(z instanceof Element))return;let ge=z.tagName.toLowerCase(),lt=(z.getAttribute("title")??"").slice(0,40),Ot=ge==="iframe"?` ${tr(z)}`:"";se(`child+ ${ge}${lt?` title="${lt}"`:""}${Ot} dims=${en(z)}`)});else if(Pe.type==="attributes"&&Pe.target instanceof Element){let z=Pe.target;if(z.tagName.toLowerCase()!=="iframe")continue;let ge=Pe.attributeName;(ge==="src"||ge==="srcdoc")&&se(`attr~ iframe ${ge}=${ge==="srcdoc"?`[${(z.getAttribute("srcdoc")??"").length}ch]`:rn(z.getAttribute("src"))} dims=${en(z)}`)}}}),Fn.observe(fn,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let Xe=fe=>{if(tt()||Bn)return;let Pe=fn.querySelectorAll("iframe"),z=typeof document<"u"&&"hasStorageAccess"in document;se(`watchdog:${fe} container=${en(fn)} children=${fn.childElementCount} iframes=${Pe.length} visibility=${typeof document<"u"?document.visibilityState:"(no document)"} cookies=${typeof navigator<"u"?navigator.cookieEnabled:"?"} hasStorageAccessApi=${z} paypalNetRequests=${it.value}`),Pe.forEach((ge,lt)=>{let Ot=(ge.getAttribute("title")??"").slice(0,40);se(` iframe[${lt}] ${en(ge)}${Ot?` title="${Ot}"`:""} ${tr(ge)}`);let ke=Rr(ge);ke&&se(` ${ke}`)}),Dn.length===0&&se(" (no PayPal/zoid window errors captured)")};Fe&&($t.push(setTimeout(()=>Xe("3s"),3e3)),$t.push(setTimeout(()=>Xe("8s"),8e3)),$t.push(setTimeout(()=>Xe("15s"),15e3))),se("render:start");let nt=O.startTiming();$t.push(setTimeout(()=>{tt()||Bn||(se("watchdog:11s retryable render timeout"),ce("PayPal Buttons render did not settle within 11000ms.",!0))},el)),Te.render(fn).then(()=>{if(se(`render:resolved inactive=${tt()}`),Kt(),tt()){De();return}Bn=!0,T(!0),Me(!1),Jt.current?.("ready"),O.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),O.performance({stage:"checkout_render",durationMs:O.elapsed(nt),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}).catch(fe=>{let Pe=fe instanceof Error?fe.message:"PayPal failed to render.";se(`render:rejected msg=${Pe.slice(0,120)}`),Kt(),ce(Pe)})}).catch(y=>{let x=y instanceof Error?y.message:"PayPal SDK failed to load.";se(`loadScript:rejected msg=${x.slice(0,120)}`),ce(x)})},0);return()=>{Ke=!0,clearTimeout(vt),Sn&&clearTimeout(Sn),Kt(),De()}},[me,ot,d,v,c,Ge,b,e,be,ye,O,ct]);let Hn=Fe?(0,hn.jsxs)("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:ae?"#fef2f2":"#f3f4f6",border:`1px solid ${ae?"#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=${Z} failed=${ae})`,Mt.length===0?`
2
2
  (waiting for first lifecycle event\u2026)`:`
3
3
  ${Mt.join(`
4
- `)}`]}):null;return ae&&!dt?Fe?(0,hn.jsx)("div",{children:Hn}):null:(0,hn.jsxs)("div",{children:[Hn,St&&(0,hn.jsx)(Cr,{identity:St,methodLabel:"PayPal",testId:"flopay-direct-paypal-identity-pane",onComplete:k=>{jn(k)},submitting:A}),ve&&(0,hn.jsx)(Cr,{identity:ve.identity,methodLabel:ve.methodLabel,testId:"flopay-direct-paypal-identity-pane",onComplete:st,onCancel:()=>st(null)}),(0,hn.jsxs)("div",{"aria-hidden":j||St||ve?!0:void 0,style:j||St||ve?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:$o},children:[!Z&&!j&&(0,hn.jsx)("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"}}),(0,hn.jsx)("div",{ref:ue,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,role:"group","aria-label":"PayPal payment method",style:{minHeight:$o,display:"flex",opacity:Z?1:0},"aria-busy":xe||he},ye)]},ye),Qe&&(0,hn.jsx)("button",{ref:re,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:zt,style:nl,children:"Try PayPal again"})]})}function co(e){return(0,hn.jsx)(Di,{...e})}function Ni(e){return(0,hn.jsx)(Di,{...e})}var uo=require("react/jsx-runtime");function zr({children:e,margin:t,icon:n=!0,styleOverride:r}){return(0,uo.jsxs)("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&&(0,uo.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:(0,uo.jsx)("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]})}var At=require("react/jsx-runtime");function Rn({status:e,errorMessage:t,authorized:n=!1,processingLabel:r="PROCESSING...",successLabel:o,errorLabel:i="PAYMENT FAILED",successNote:d="You will be automatically redirected, do not close or navigate away from this window."}){return(0,At.jsx)("div",{"data-testid":"flopay-processing-overlay","data-status":e,role:"dialog","aria-modal":"true",style:{position:"fixed",inset:0,background:"rgba(0,0,0,0.35)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3,backdropFilter:"blur(2px)"},children:(0,At.jsxs)("div",{style:{background:"white",borderRadius:12,padding:"2rem 2.5rem",textAlign:"center",boxShadow:"0 8px 32px rgba(0,0,0,0.18)",minWidth:240,display:"flex",flexDirection:"column",alignItems:"center",gap:16},children:[(0,At.jsxs)("div",{style:{width:48,height:48,position:"relative"},children:[e==="processing"&&(0,At.jsxs)("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:{animation:"flopay-spin 0.8s linear infinite"},children:[(0,At.jsx)("circle",{cx:"12",cy:"12",r:"10",stroke:"#e5e7eb",strokeWidth:"3"}),(0,At.jsx)("path",{d:"M4 12a8 8 0 018-8v3a5 5 0 00-5 5H4z",fill:"#4A49FF"})]}),e==="success"&&(0,At.jsx)("div",{style:{animation:"flopay-pop 0.4s cubic-bezier(0.34,1.56,0.64,1)"},children:(0,At.jsxs)("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[(0,At.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#22c55e"}),(0,At.jsx)("path",{d:"M7 12.5l3 3 7-7",stroke:"white",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{strokeDasharray:20,strokeDashoffset:20,animation:"flopay-draw 0.4s 0.15s ease forwards"}})]})}),e==="error"&&(0,At.jsx)("div",{style:{animation:"flopay-shake 0.4s ease"},children:(0,At.jsxs)("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[(0,At.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#ef4444"}),(0,At.jsx)("path",{d:"M8 8l8 8M16 8l-8 8",stroke:"white",strokeWidth:"2.5",strokeLinecap:"round",style:{strokeDasharray:12,strokeDashoffset:12,animation:"flopay-draw 0.3s 0.1s ease forwards"}})]})})]}),(0,At.jsxs)("span",{style:{fontSize:14,fontWeight:600,letterSpacing:"0.05em",color:e==="success"?"#16a34a":e==="error"?"#dc2626":"#374151"},children:[e==="processing"&&r,e==="success"&&(o??(n?"PAYMENT AUTHORISED":"PAYMENT SUCCESSFUL")),e==="error"&&i]}),e==="success"&&d!==null&&(0,At.jsx)("p",{style:{fontSize:13,color:"#6b7280",fontWeight:400,maxWidth:260,lineHeight:1.4,margin:0},children:d}),e==="error"&&t&&(0,At.jsx)("p",{style:{fontSize:13,color:"#6b7280",fontWeight:400,maxWidth:260,lineHeight:1.4,margin:0},children:t}),(0,At.jsx)("style",{children:`
4
+ `)}`]}):null;return ae&&!dt?Fe?(0,hn.jsx)("div",{children:Hn}):null:(0,hn.jsxs)("div",{children:[Hn,St&&(0,hn.jsx)(Cr,{identity:St,methodLabel:"PayPal",testId:"flopay-direct-paypal-identity-pane",onComplete:k=>{jn(k)},submitting:A}),ve&&(0,hn.jsx)(Cr,{identity:ve.identity,methodLabel:ve.methodLabel,testId:"flopay-direct-paypal-identity-pane",onComplete:st,onCancel:()=>st(null)}),(0,hn.jsxs)("div",{"aria-hidden":j||St||ve?!0:void 0,style:j||St||ve?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:$o},children:[!Z&&!j&&(0,hn.jsx)("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"}}),(0,hn.jsx)("div",{ref:ue,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,role:"group","aria-label":"PayPal payment method",style:{minHeight:$o,display:"flex",opacity:Z?1:0},"aria-busy":xe||he},ye)]},ye),Qe&&(0,hn.jsx)("button",{ref:re,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:Ut,style:nl,children:"Try PayPal again"})]})}function co(e){return(0,hn.jsx)(Ni,{...e})}function Di(e){return(0,hn.jsx)(Ni,{...e})}var uo=require("react/jsx-runtime");function zr({children:e,margin:t,icon:n=!0,styleOverride:r}){return(0,uo.jsxs)("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&&(0,uo.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:(0,uo.jsx)("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]})}var At=require("react/jsx-runtime");function Rn({status:e,errorMessage:t,authorized:n=!1,processingLabel:r="PROCESSING...",successLabel:o,errorLabel:i="PAYMENT FAILED",successNote:d="You will be automatically redirected, do not close or navigate away from this window."}){return(0,At.jsx)("div",{"data-testid":"flopay-processing-overlay","data-status":e,role:"dialog","aria-modal":"true",style:{position:"fixed",inset:0,background:"rgba(0,0,0,0.35)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3,backdropFilter:"blur(2px)"},children:(0,At.jsxs)("div",{style:{background:"white",borderRadius:12,padding:"2rem 2.5rem",textAlign:"center",boxShadow:"0 8px 32px rgba(0,0,0,0.18)",minWidth:240,display:"flex",flexDirection:"column",alignItems:"center",gap:16},children:[(0,At.jsxs)("div",{style:{width:48,height:48,position:"relative"},children:[e==="processing"&&(0,At.jsxs)("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:{animation:"flopay-spin 0.8s linear infinite"},children:[(0,At.jsx)("circle",{cx:"12",cy:"12",r:"10",stroke:"#e5e7eb",strokeWidth:"3"}),(0,At.jsx)("path",{d:"M4 12a8 8 0 018-8v3a5 5 0 00-5 5H4z",fill:"#4A49FF"})]}),e==="success"&&(0,At.jsx)("div",{style:{animation:"flopay-pop 0.4s cubic-bezier(0.34,1.56,0.64,1)"},children:(0,At.jsxs)("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[(0,At.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#22c55e"}),(0,At.jsx)("path",{d:"M7 12.5l3 3 7-7",stroke:"white",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{strokeDasharray:20,strokeDashoffset:20,animation:"flopay-draw 0.4s 0.15s ease forwards"}})]})}),e==="error"&&(0,At.jsx)("div",{style:{animation:"flopay-shake 0.4s ease"},children:(0,At.jsxs)("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[(0,At.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#ef4444"}),(0,At.jsx)("path",{d:"M8 8l8 8M16 8l-8 8",stroke:"white",strokeWidth:"2.5",strokeLinecap:"round",style:{strokeDasharray:12,strokeDashoffset:12,animation:"flopay-draw 0.3s 0.1s ease forwards"}})]})})]}),(0,At.jsxs)("span",{style:{fontSize:14,fontWeight:600,letterSpacing:"0.05em",color:e==="success"?"#16a34a":e==="error"?"#dc2626":"#374151"},children:[e==="processing"&&r,e==="success"&&(o??(n?"PAYMENT AUTHORISED":"PAYMENT SUCCESSFUL")),e==="error"&&i]}),e==="success"&&d!==null&&(0,At.jsx)("p",{style:{fontSize:13,color:"#6b7280",fontWeight:400,maxWidth:260,lineHeight:1.4,margin:0},children:d}),e==="error"&&t&&(0,At.jsx)("p",{style:{fontSize:13,color:"#6b7280",fontWeight:400,maxWidth:260,lineHeight:1.4,margin:0},children:t}),(0,At.jsx)("style",{children:`
5
5
  @keyframes flopay-spin { to { transform: rotate(360deg); } }
6
6
  @keyframes flopay-pop { 0% { transform: scale(0); } 100% { transform: scale(1); } }
7
7
  @keyframes flopay-draw { to { stroke-dashoffset: 0; } }
8
8
  @keyframes flopay-shake { 0%,100% { transform: translateX(0); } 20%,60% { transform: translateX(-4px); } 40%,80% { transform: translateX(4px); } }
9
- `})]})})}var Li=require("@flopay/shared"),Yt=require("react");var Oi=require("react/jsx-runtime");function po({flopay:e,paypalFlopay:t,options:n,onInstrument:r,children:o}){let[i,d]=(0,Yt.useState)(e instanceof Promise?null:e),[c,v]=(0,Yt.useState)(t instanceof Promise||!t?null:t),g=(0,Yt.useRef)(null),h=(0,Yt.useRef)(null),f=Or(r);(0,Yt.useEffect)(()=>{f({class:"lifecycle",name:"checkout.mount"})},[f]),(0,Yt.useEffect)(()=>{i&&f({class:"lifecycle",name:"sdk.initialize.ready"})},[f,i]),(0,Yt.useEffect)(()=>{if(i)return jt(i)?.subscribe?.(f)},[f,i]),(0,Yt.useEffect)(()=>{if(!(!c||c===i))return jt(c)?.subscribe?.(f)},[f,i,c]),(0,Yt.useEffect)(()=>{if(!i)return;let p=jt(i);return g.current=p?.beginCheckout()??p?.now()??0,p?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{p?.log({name:"checkout.unmount",stage:"unmount"})}},[i]),(0,Yt.useEffect)(()=>{let p=!1;return e instanceof Promise?e.then(C=>{p||d(C)},()=>{p||f({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"})}):d(e),()=>{p=!0}},[f,e]),(0,Yt.useEffect)(()=>{let p=!1;if(!t){v(null);return}return t instanceof Promise?t.then(C=>{p||v(C)},()=>{p||f({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED",provider:"paypal"})}):v(t),()=>{p=!0}},[f,t]),(0,Yt.useEffect)(()=>{if(!i||h.current===i)return;h.current=i;let p=jt(i);p?.log({name:"checkout.rendered",stage:"checkout_render"}),f({class:"lifecycle",name:"checkout.rendered"}),p?.performance({stage:"checkout_render",durationMs:p.elapsed(g.current??0),durationMode:"machine"})},[f,i]);let D=(0,Li.resolveBillingApiUrl)(n?.billingApiUrl),B=(0,Yt.useMemo)(()=>({flopay:i,paypalFlopay:c,billingApiUrl:D,emitInstrument:f}),[i,c,D,f]);return(0,Oi.jsx)(In.Provider,{value:B,children:o})}var jo="flopay_recent_completion_";function Ur(e){if(!(!e||typeof window>"u"))try{let t={expiresAt:Date.now()+6e4};window.sessionStorage.setItem(jo+e,JSON.stringify(t))}catch{}}function wa(e){if(!e||typeof window>"u")return!1;try{let t=window.sessionStorage.getItem(jo+e);if(!t)return!1;let n=JSON.parse(t);return typeof n?.expiresAt!="number"||n.expiresAt<=Date.now()?(window.sessionStorage.removeItem(jo+e),!1):!0}catch{return!1}}var qr=require("@flopay/js"),Ue=require("@flopay/shared");var yo="card";async function al(e,t,n){if(n){if(typeof e.retrieveSetupIntent!="function")return null;let{setupIntent:i,error:d}=await e.retrieveSetupIntent(t);return{error:d,intent:i??null}}if(typeof e.retrievePaymentIntent!="function")return null;let{paymentIntent:r,error:o}=await e.retrievePaymentIntent(t);return{error:o,intent:r??null}}async function il(e,t,n,r){if(r){if(typeof e.confirmCardSetup!="function")return null;let{setupIntent:d,error:c}=await e.confirmCardSetup(t,n);return{error:c,intent:d??null}}if(typeof e.confirmCardPayment!="function")return null;let{paymentIntent:o,error:i}=await e.confirmCardPayment(t,n);return{error:i,intent:o??null}}function Ia(e,t){return Object.assign(e,{checkoutMethod:t})}function or(e,t){let n=e instanceof Ue.FloPayError?e:new Ue.FloPayError(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 mo(e,t){try{return await e()}catch(n){throw or(n,t)}}function zi(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 sl(e){return e.status==="succeeded"||e.status==="declined"}async function Ui(e){if(typeof document>"u"||typeof window>"u")throw new Ue.FloPayError("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});if(e.signal?.aborted)throw new Ue.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"});let t=3e5,n=1e3,r=15e3,o=`${e.billingApiUrl.replace(/\/$/,"")}/v1/checkouts/sessions/${encodeURIComponent(e.sessionId)}/3ds/complete`,i=async()=>{let h=new AbortController,f=()=>h.abort();e.signal?.aborted?h.abort():e.signal?.addEventListener("abort",f);let D=window.setTimeout(()=>h.abort(),r);try{let B=await fetch(o,{method:"POST",headers:{"x-checkout-session-token":e.nonce,"content-type":"application/json"},body:"{}",signal:h.signal});if(!B.ok)return{status:"unknown"};let p=await B.json().catch(()=>null);return ll(p)}catch{return{status:"unknown"}}finally{window.clearTimeout(D),e.signal?.removeEventListener("abort",f)}},d=document.activeElement instanceof HTMLElement?document.activeElement:null,c=document.createElement("div");c.setAttribute("data-flopay-auto-3ds-overlay","1"),c.setAttribute("role","dialog"),c.setAttribute("aria-modal","true"),c.setAttribute("aria-label","Card authentication"),c.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 v=document.createElement("iframe");v.setAttribute("title","Card authentication"),v.setAttribute("allow","payment"),v.tabIndex=0,v.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(";"),v.src=e.nextActionRedirectUrl,c.appendChild(v),document.body.appendChild(c),v.focus();let g=null;try{g=new URL(e.billingApiUrl,window.location.href).origin}catch{g=null}try{let h=await new Promise((f,D)=>{let B=!1,p=0,C=0,he=0,V=!1,S=()=>{window.clearTimeout(p),window.clearInterval(C),window.clearTimeout(he),window.removeEventListener("message",K),v.removeEventListener("load",H),e.signal?.removeEventListener("abort",de)},me=async()=>{if(!(B||V)){V=!0;try{let be=await i();if(B||!sl(be))return;B=!0,S(),f(be)}finally{V=!1}}},H=()=>{window.clearTimeout(he),he=window.setTimeout(()=>{me()},250)},de=()=>{B||(B=!0,S(),D(new Ue.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"})))},K=be=>{if(be.source!==v.contentWindow||g&&be.origin!==g)return;let $e=be.data;!$e||typeof $e!="object"||$e.source!=="flopay-vault-3ds-return"||B||(B=!0,S(),f(null))};p=window.setTimeout(()=>{B||(B=!0,S(),D(new Ue.FloPayError("Card authentication timed out.","api_error",{code:"three_ds_timeout"})))},t),C=window.setInterval(()=>{me()},n),v.addEventListener("load",H),window.addEventListener("message",K),e.signal?.addEventListener("abort",de),e.signal?.aborted&&de()});return h||await i()}finally{c.parentNode?.removeChild(c),d?.isConnected&&d.focus()}}function ll(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 pr(e,t="Payment failed. Please try again.",n){let r=n?.checkoutMethod??e?.checkoutMethod??(e?.type==="paypal_redirect_required"?"paypal":"card"),o=e?.message??t,i=dr(o)??o;return Ia(new Ue.FloPayError(i,"api_error",{code:(0,Ue.normalizeCheckoutFailureOutcome)(e?.outcome)??(0,Ue.normalizeCheckoutFailureOutcome)(e?.type)??e?.gatewayErrorCode}),r)}function ka(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function Vo(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}async function cl(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 qi(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let o of n)if(typeof o=="string"&&o.length>0&&(!t?.requirePaymentIntentClientSecret||Vo(o)))return o;let r=e?.data;if(r&&typeof r=="object"){let o=r,i=[o.threeDSecureToken,o.clientSecret,o.stripeClientSecret,o.id];for(let c of i)if(typeof c=="string"&&c.length>0&&(!t?.requirePaymentIntentClientSecret||Vo(c)))return c;let d=o.gateways;if(d&&typeof d=="object"){let c=d.stripe;if(c&&typeof c=="object"){let v=c,g=[v.stripeClientSecret,v.clientSecret];for(let h of g)if(typeof h=="string"&&h.length>0&&(!t?.requirePaymentIntentClientSecret||Vo(h)))return h}}}}async function dl({billingApiUrl:e,sessionId:t,nonce:n,responseJson:r}){let o=qi(r,{requirePaymentIntentClientSecret:!0});if(typeof o=="string"&&o.length>0)return{type:"3ds_required",threeDSecureToken:o};if(!t)return null;try{let c=(await new qr.PaymentAPI(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(Vo(c))return{type:"3ds_required",threeDSecureToken:c}}catch{}return null}async function $r({billingApiUrl:e,sessionId:t,session:n,nonce:r,tokenizedData:o,returnUrl:i,telemetry:d}){let c=e.replace(/\/+$/,""),v=t??n.id,g=r??n.clientSecret,h=n.customer?.id??n.accountData?.userId??"",f=n.customer?.email??n.accountData?.email??"",D=n.customer?.firstName??n.accountData?.firstName??"",B=n.customer?.lastName??n.accountData?.lastName??"",p=n.customer?.country??n.accountData?.country??void 0,C=n.customer?.zip??n.accountData?.zip??void 0,he=new qr.PaymentAPI(c,d===!1?{telemetry:!1}:void 0),V=await cl(()=>he.processPayment(h,{sessionId:v,nonce:g,tokenizedData:o,accountData:{userId:h,email:f,firstName:D,lastName:B,country:p,zip:C},returnUrl:i??ka(n)}));if(V.ok){let H=typeof V.json=="function"?await V.json().catch(()=>null):null;return(0,Ue.isAuthorizationOnlySession)(n)||H?.status==="authorized"?{type:"success",result:{status:"authorized",paymentId:typeof H?.paymentId=="string"?H.paymentId:n.paymentId,sessionId:typeof H?.sessionId=="string"?H.sessionId:v,authorizationExpiresAt:typeof H?.authorizationExpiresAt=="string"?H.authorizationExpiresAt:n.authorizationExpiresAt,paymentMethodId:ao(o),checkoutMethod:o?o.isPaypal?"paypal":"card":void 0}}:{type:"success",result:{status:"succeeded",paymentIntentId:o?.threeDSecureActionResultTokenId,paymentMethodId:ao(o),checkoutMethod:o?o.isPaypal?"paypal":"card":void 0}}}let S;try{S=await V.json()}catch{throw new Ue.FloPayError("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:V.status})}if(S?.type==="paypal_redirect_required"||S?.type==="3ds_required"){let H=qi(S);if(!H)throw new Ue.FloPayError("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:V.status});return{type:S.type,threeDSecureToken:H,paymentMethodId:S.paymentMethodId}}if(S?.gatewayErrorCode==="authentication_required"){let H=await dl({billingApiUrl:c,sessionId:v,nonce:g,responseJson:S});if(H)return H;throw Ia(new Ue.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}let me=new Ue.FloPayError(S?.message??"Payment failed. Please try again.","api_error",{code:S?.code??S?.gatewayErrorCode,declineCode:S?.declineCode??S?.gatewayDeclineReason,statusCode:V.status});throw Object.assign(me,{telemetryOutcome:(0,Ue.classifyPaymentRejection)(V.status,S)})}async function Ho(e,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:i,session:d,returnUrl:c,telemetry:v}){let g=t?.getRawProvider();if(!g)throw or(new Ue.FloPayError("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!r||!e.threeDSecureToken)throw Ia(new Ue.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let h=(0,Ue.isSetupIntentClientSecret)(e.threeDSecureToken),f=null,D=e.paymentMethodId,B=await mo(()=>al(g,e.threeDSecureToken,h),"card");if(B){if(B.error)throw or(new Ue.FloPayError(B.error.message??`Failed to retrieve 3DS ${h?"setup":"payment"} status.`,"api_error",{code:B.error.code}),"card");let C=B.intent;!D&&C?.payment_method&&(typeof C.payment_method=="string"?D=C.payment_method:"id"in C.payment_method&&(D=C.payment_method.id??void 0))}let p=D?await mo(()=>il(g,e.threeDSecureToken,{payment_method:D,return_url:c??ka(d)??window.location.href},h),"card"):null;if(p){if(p.error)throw or(new Ue.FloPayError(p.error.message??"3DS authentication failed.","api_error",{code:p.error.code}),"card");f=p.intent}else{let C=await mo(()=>g.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(C.error)throw or(new Ue.FloPayError(C.error.message??"3DS authentication failed.","api_error",{code:C.error.code}),"card");f=(h?C.setupIntent:C.paymentIntent)??null}if(f&&(f.status==="requires_capture"||f.status==="succeeded"||f.status==="processing")){let C=await $r({billingApiUrl:o,sessionId:i,session:d,telemetry:v,tokenizedData:{id:f.id,type:"card",threeDSecureActionResultTokenId:f.id},returnUrl:c});return C.type==="success"?{...C.result,paymentIntentId:C.result.paymentIntentId??f.id,paymentMethodId:C.result.paymentMethodId??D}:Ho(C,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:i,session:d,returnUrl:c,telemetry:v})}throw or(new Ue.FloPayError("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let h=(n??t)?.getRawProvider();if(!h)throw or(new Ue.FloPayError("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:D}=await mo(()=>h.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(D)throw or(new Ue.FloPayError(D.message??"PayPal authorization failed.","api_error",{code:D.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:f}=await mo(()=>h.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:c??ka(d)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(f)throw or(new Ue.FloPayError(f.message??"PayPal authorization failed.","api_error",{code:f.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new Ue.FloPayError("Unsupported payment redirect state.","api_error")}function kr(e){if(e instanceof Ue.FloPayError){let r=dr(e.message);return r&&r!==e.message?Object.assign(new Ue.FloPayError(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=dr(t)??t;return new Ue.FloPayError(n,"api_error")}function Ko(e){let t=e.data.stripe?.publishableKey,n=!!e.data.paypal?.publishableKey;if(!t&&!n)throw new Ue.FloPayError("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 Yo({publishableKey:e,paypalPublishableKey:t,billingApiUrl:n,locale:r,telemetry:o}){if(!e)return{flopay:null,paypalFlopay:null};let i=!!t&&t!==e,[d,c]=await Promise.all([(0,qr.loadFloPay)(e,{billingApiUrl:n,locale:r,telemetry:o}),i?(0,qr.loadFloPay)(t,{billingApiUrl:n,locale:r,telemetry:o}).catch(v=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",v),null)):Promise.resolve(null)]);return{flopay:d,paypalFlopay:t?i?c:d:null}}var mr=require("@flopay/js"),u=require("@flopay/shared"),Et=require("@stripe/react-stripe-js"),a=Ci(require("react"),1);function $i(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 ji={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"};var ar=require("react"),Vi=require("react/jsx-runtime");function jr({capture:e,html:t,messageToken:n,expectedOrigin:r,theme:o,containerStyle:i,onReady:d,onError:c,onValidation:v}){let g=(0,ar.useRef)(null),h=(0,ar.useRef)(d),f=(0,ar.useRef)(c),D=(0,ar.useRef)(v);h.current=d,f.current=c,D.current=v;let B=(0,ar.useRef)(o);return B.current=o,(0,ar.useEffect)(()=>{let p=g.current;if(!p)return;let C=!0,he=!1,V=()=>{!C||he||(he=!0,h.current?.())},S=e.on("ready",()=>{V()}),me=e.on("error",K=>{f.current?.(K.message??"There was a problem loading the secure card form.")}),H=e.on("validation",K=>{D.current?.(K.message??null)}),de={html:t,...n?{messageToken:n}:{},...r?{expectedOrigin:r}:{},...B.current?{theme:B.current}:{}};return e.mount(p,de).then(()=>{V()}).catch(K=>{C&&f.current?.(K instanceof Error?K.message:"Failed to load the secure card form.")}),()=>{C=!1,S(),me(),H(),e.unmount()}},[e,t,n,r]),(0,ar.useEffect)(()=>{o&&e.applyTheme?.(o)},[e,o]),(0,Vi.jsx)("div",{ref:g,"data-testid":"flopay-vault-card-fields",style:i})}function Vr(e,t=.12){let n=/^#?([0-9a-fA-F]{6})$/.exec(e.trim());if(!n)return e;let r=parseInt(n[1],16),o=Math.max(0,Math.min(1,1-t)),i=Math.round((r>>16&255)*o),d=Math.round((r>>8&255)*o),c=Math.round((r&255)*o);return`#${(1<<24|i<<16|d<<8|c).toString(16).slice(1)}`}function Ea(e){if(typeof e=="number"||typeof e=="string")return e}function Wo({appearance:e,buttonsStyles:t,layout:n="default"}){let r=e?.variables,o=g=>typeof g=="string"&&g?g:void 0,i=t.submitButton,d=o(r?.colorPrimary)??o(i?.backgroundColor)??"#4A49FF",c=n==="buttons",v=t.nameInput;return{primaryColor:d,primaryHoverColor:o(r?.colorPrimaryHover)??Vr(d,.12),inputBackgroundColor:o(t.cardInputBackground)??o(r?.colorBackground)??"#ffffff",textColor:o(t.cardInputColor)??o(v?.color)??o(r?.colorText)??"#262833",borderColor:o(t.cardInputBorder)??(c?"#e5e7eb":"#A4A4FF"),placeholderColor:o(t.cardInputPlaceholderColor)??"#9ca3af",errorColor:o(r?.colorDanger)??"#dc2626",successColor:"#16a34a",fontFamily:o(v?.fontFamily)??o(r?.fontFamily)??"Poppins, sans-serif",fontSize:o(t.cardInputFontSize)??o(r?.fontSizeBase)??"16px",fontWeight:String(Ea(v?.fontWeight)??400),borderRadius:o(r?.borderRadius)??"8px"}}var s=require("react/jsx-runtime"),Jn="flopay_stripe_resume",Hi="flopay_wallet_resume";function Qi(e){return e instanceof u.FloPayError&&(e.type==="validation_error"||e.statusCode===400||e.statusCode===422)}async function Jo(e,t,...n){let r=n[2].provider;t?.({class:"lifecycle",name:"payment.intent.started",provider:r});try{return await new mr.PaymentAPI(e).createSessionIntent(...n)}catch(o){throw Qi(o)||t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"intent_create",provider:r}),o}}var fo="flopay_paypal_resume",ul=250,Ki="Just a moment \u2014 we are finalizing your order. Please press pay again.";function Aa(e,t,n){e?.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:"provider_runtime",stage:"provider_load",provider:t,paymentMethodCategory:n,requestCategory:"provider_sdk"})}async function Xo({billingApiUrl:e,sessionId:t,nonce:n,request:r}){if(!(!t||!n))try{await new mr.PaymentAPI(e,{telemetry:!1}).reportSessionIntentDecline(t,n,r)}catch{}}function pl(e){return e instanceof u.FloPayError&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function Ra(e){return e?.html?{html:e.html,...e.messageToken?{messageToken:e.messageToken}:{},...e.expectedOrigin?{expectedOrigin:e.expectedOrigin}:{}}:null}function ml({event:e,fallbackEmail:t,fallbackName:n}){let r=e.billingDetails,o=kn(r?.name),i=kn(n);return{email:r?.email?.trim()||t?.trim(),firstName:o.firstName??i.firstName,lastName:o.lastName??i.lastName}}async function es({event:e,prepared:t,email:n,billingName:r,methodLabel:o,collect:i}){let d=ml({event:e,fallbackEmail:t?.accountPatch?.email??n,fallbackName:[t?.accountPatch?.firstName,t?.accountPatch?.lastName].filter(Boolean).join(" ")||r});return!(0,u.isValidEmail)(d.email)||!io(d)?i(o,d):d}var yl=`
9
+ `})]})})}var Li=require("@flopay/shared"),Wt=require("react");var Oi=require("react/jsx-runtime");function po({flopay:e,paypalFlopay:t,options:n,onInstrument:r,children:o}){let[i,d]=(0,Wt.useState)(e instanceof Promise?null:e),[c,v]=(0,Wt.useState)(t instanceof Promise||!t?null:t),g=(0,Wt.useRef)(null),h=(0,Wt.useRef)(null),f=Or(r);(0,Wt.useEffect)(()=>{f({class:"lifecycle",name:"checkout.mount"})},[f]),(0,Wt.useEffect)(()=>{i&&f({class:"lifecycle",name:"sdk.initialize.ready"})},[f,i]),(0,Wt.useEffect)(()=>{if(i)return Vt(i)?.subscribe?.(f)},[f,i]),(0,Wt.useEffect)(()=>{if(!(!c||c===i))return Vt(c)?.subscribe?.(f)},[f,i,c]),(0,Wt.useEffect)(()=>{if(!i)return;let p=Vt(i);return g.current=p?.beginCheckout()??p?.now()??0,p?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{p?.log({name:"checkout.unmount",stage:"unmount"})}},[i]),(0,Wt.useEffect)(()=>{let p=!1;return e instanceof Promise?e.then(C=>{p||d(C)},()=>{p||f({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"})}):d(e),()=>{p=!0}},[f,e]),(0,Wt.useEffect)(()=>{let p=!1;if(!t){v(null);return}return t instanceof Promise?t.then(C=>{p||v(C)},()=>{p||f({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED",provider:"paypal"})}):v(t),()=>{p=!0}},[f,t]),(0,Wt.useEffect)(()=>{if(!i||h.current===i)return;h.current=i;let p=Vt(i);p?.log({name:"checkout.rendered",stage:"checkout_render"}),f({class:"lifecycle",name:"checkout.rendered"}),p?.performance({stage:"checkout_render",durationMs:p.elapsed(g.current??0),durationMode:"machine"})},[f,i]);let N=(0,Li.resolveBillingApiUrl)(n?.billingApiUrl),B=(0,Wt.useMemo)(()=>({flopay:i,paypalFlopay:c,billingApiUrl:N,emitInstrument:f}),[i,c,N,f]);return(0,Oi.jsx)(In.Provider,{value:B,children:o})}var jo="flopay_recent_completion_";function Ur(e){if(!(!e||typeof window>"u"))try{let t={expiresAt:Date.now()+6e4};window.sessionStorage.setItem(jo+e,JSON.stringify(t))}catch{}}function wa(e){if(!e||typeof window>"u")return!1;try{let t=window.sessionStorage.getItem(jo+e);if(!t)return!1;let n=JSON.parse(t);return typeof n?.expiresAt!="number"||n.expiresAt<=Date.now()?(window.sessionStorage.removeItem(jo+e),!1):!0}catch{return!1}}var qr=require("@flopay/js"),Ue=require("@flopay/shared");var yo="card";async function al(e,t,n){if(n){if(typeof e.retrieveSetupIntent!="function")return null;let{setupIntent:i,error:d}=await e.retrieveSetupIntent(t);return{error:d,intent:i??null}}if(typeof e.retrievePaymentIntent!="function")return null;let{paymentIntent:r,error:o}=await e.retrievePaymentIntent(t);return{error:o,intent:r??null}}async function il(e,t,n,r){if(r){if(typeof e.confirmCardSetup!="function")return null;let{setupIntent:d,error:c}=await e.confirmCardSetup(t,n);return{error:c,intent:d??null}}if(typeof e.confirmCardPayment!="function")return null;let{paymentIntent:o,error:i}=await e.confirmCardPayment(t,n);return{error:i,intent:o??null}}function Ia(e,t){return Object.assign(e,{checkoutMethod:t})}function or(e,t){let n=e instanceof Ue.FloPayError?e:new Ue.FloPayError(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 mo(e,t){try{return await e()}catch(n){throw or(n,t)}}function zi(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 sl(e){return e.status==="succeeded"||e.status==="declined"}async function Ui(e){if(typeof document>"u"||typeof window>"u")throw new Ue.FloPayError("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});if(e.signal?.aborted)throw new Ue.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"});let t=3e5,n=1e3,r=15e3,o=`${e.billingApiUrl.replace(/\/$/,"")}/v1/checkouts/sessions/${encodeURIComponent(e.sessionId)}/3ds/complete`,i=async()=>{let h=new AbortController,f=()=>h.abort();e.signal?.aborted?h.abort():e.signal?.addEventListener("abort",f);let N=window.setTimeout(()=>h.abort(),r);try{let B=await fetch(o,{method:"POST",headers:{"x-checkout-session-token":e.nonce,"content-type":"application/json"},body:"{}",signal:h.signal});if(!B.ok)return{status:"unknown"};let p=await B.json().catch(()=>null);return ll(p)}catch{return{status:"unknown"}}finally{window.clearTimeout(N),e.signal?.removeEventListener("abort",f)}},d=document.activeElement instanceof HTMLElement?document.activeElement:null,c=document.createElement("div");c.setAttribute("data-flopay-auto-3ds-overlay","1"),c.setAttribute("role","dialog"),c.setAttribute("aria-modal","true"),c.setAttribute("aria-label","Card authentication"),c.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 v=document.createElement("iframe");v.setAttribute("title","Card authentication"),v.setAttribute("allow","payment"),v.tabIndex=0,v.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(";"),v.src=e.nextActionRedirectUrl,c.appendChild(v),document.body.appendChild(c),v.focus();let g=null;try{g=new URL(e.billingApiUrl,window.location.href).origin}catch{g=null}try{let h=await new Promise((f,N)=>{let B=!1,p=0,C=0,he=0,V=!1,S=()=>{window.clearTimeout(p),window.clearInterval(C),window.clearTimeout(he),window.removeEventListener("message",K),v.removeEventListener("load",H),e.signal?.removeEventListener("abort",de)},me=async()=>{if(!(B||V)){V=!0;try{let be=await i();if(B||!sl(be))return;B=!0,S(),f(be)}finally{V=!1}}},H=()=>{window.clearTimeout(he),he=window.setTimeout(()=>{me()},250)},de=()=>{B||(B=!0,S(),N(new Ue.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"})))},K=be=>{if(be.source!==v.contentWindow||g&&be.origin!==g)return;let $e=be.data;!$e||typeof $e!="object"||$e.source!=="flopay-vault-3ds-return"||B||(B=!0,S(),f(null))};p=window.setTimeout(()=>{B||(B=!0,S(),N(new Ue.FloPayError("Card authentication timed out.","api_error",{code:"three_ds_timeout"})))},t),C=window.setInterval(()=>{me()},n),v.addEventListener("load",H),window.addEventListener("message",K),e.signal?.addEventListener("abort",de),e.signal?.aborted&&de()});return h||await i()}finally{c.parentNode?.removeChild(c),d?.isConnected&&d.focus()}}function ll(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 pr(e,t="Payment failed. Please try again.",n){let r=n?.checkoutMethod??e?.checkoutMethod??(e?.type==="paypal_redirect_required"?"paypal":"card"),o=e?.message??t,i=dr(o)??o;return Ia(new Ue.FloPayError(i,"api_error",{code:(0,Ue.normalizeCheckoutFailureOutcome)(e?.outcome)??(0,Ue.normalizeCheckoutFailureOutcome)(e?.type)??e?.gatewayErrorCode}),r)}function ka(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function Vo(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}async function cl(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 qi(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let o of n)if(typeof o=="string"&&o.length>0&&(!t?.requirePaymentIntentClientSecret||Vo(o)))return o;let r=e?.data;if(r&&typeof r=="object"){let o=r,i=[o.threeDSecureToken,o.clientSecret,o.stripeClientSecret,o.id];for(let c of i)if(typeof c=="string"&&c.length>0&&(!t?.requirePaymentIntentClientSecret||Vo(c)))return c;let d=o.gateways;if(d&&typeof d=="object"){let c=d.stripe;if(c&&typeof c=="object"){let v=c,g=[v.stripeClientSecret,v.clientSecret];for(let h of g)if(typeof h=="string"&&h.length>0&&(!t?.requirePaymentIntentClientSecret||Vo(h)))return h}}}}async function dl({billingApiUrl:e,sessionId:t,nonce:n,responseJson:r}){let o=qi(r,{requirePaymentIntentClientSecret:!0});if(typeof o=="string"&&o.length>0)return{type:"3ds_required",threeDSecureToken:o};if(!t)return null;try{let c=(await new qr.PaymentAPI(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(Vo(c))return{type:"3ds_required",threeDSecureToken:c}}catch{}return null}async function $r({billingApiUrl:e,sessionId:t,session:n,nonce:r,tokenizedData:o,returnUrl:i,telemetry:d}){let c=e.replace(/\/+$/,""),v=t??n.id,g=r??n.clientSecret,h=n.customer?.id??n.accountData?.userId??"",f=n.customer?.email??n.accountData?.email??"",N=n.customer?.firstName??n.accountData?.firstName??"",B=n.customer?.lastName??n.accountData?.lastName??"",p=n.customer?.country??n.accountData?.country??void 0,C=n.customer?.zip??n.accountData?.zip??void 0,he=new qr.PaymentAPI(c,d===!1?{telemetry:!1}:void 0),V=await cl(()=>he.processPayment(h,{sessionId:v,nonce:g,tokenizedData:o,accountData:{userId:h,email:f,firstName:N,lastName:B,country:p,zip:C},returnUrl:i??ka(n)}));if(V.ok){let H=typeof V.json=="function"?await V.json().catch(()=>null):null;return(0,Ue.isAuthorizationOnlySession)(n)||H?.status==="authorized"?{type:"success",result:{status:"authorized",paymentId:typeof H?.paymentId=="string"?H.paymentId:n.paymentId,sessionId:typeof H?.sessionId=="string"?H.sessionId:v,authorizationExpiresAt:typeof H?.authorizationExpiresAt=="string"?H.authorizationExpiresAt:n.authorizationExpiresAt,paymentMethodId:ao(o),checkoutMethod:o?o.isPaypal?"paypal":"card":void 0}}:{type:"success",result:{status:"succeeded",paymentIntentId:o?.threeDSecureActionResultTokenId,paymentMethodId:ao(o),checkoutMethod:o?o.isPaypal?"paypal":"card":void 0}}}let S;try{S=await V.json()}catch{throw new Ue.FloPayError("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:V.status})}if(S?.type==="paypal_redirect_required"||S?.type==="3ds_required"){let H=qi(S);if(!H)throw new Ue.FloPayError("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:V.status});return{type:S.type,threeDSecureToken:H,paymentMethodId:S.paymentMethodId}}if(S?.gatewayErrorCode==="authentication_required"){let H=await dl({billingApiUrl:c,sessionId:v,nonce:g,responseJson:S});if(H)return H;throw Ia(new Ue.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}let me=new Ue.FloPayError(S?.message??"Payment failed. Please try again.","api_error",{code:S?.code??S?.gatewayErrorCode,declineCode:S?.declineCode??S?.gatewayDeclineReason,statusCode:V.status});throw Object.assign(me,{telemetryOutcome:(0,Ue.classifyPaymentRejection)(V.status,S)})}async function Ho(e,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:i,session:d,returnUrl:c,telemetry:v}){let g=t?.getRawProvider();if(!g)throw or(new Ue.FloPayError("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!r||!e.threeDSecureToken)throw Ia(new Ue.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let h=(0,Ue.isSetupIntentClientSecret)(e.threeDSecureToken),f=null,N=e.paymentMethodId,B=await mo(()=>al(g,e.threeDSecureToken,h),"card");if(B){if(B.error)throw or(new Ue.FloPayError(B.error.message??`Failed to retrieve 3DS ${h?"setup":"payment"} status.`,"api_error",{code:B.error.code}),"card");let C=B.intent;!N&&C?.payment_method&&(typeof C.payment_method=="string"?N=C.payment_method:"id"in C.payment_method&&(N=C.payment_method.id??void 0))}let p=N?await mo(()=>il(g,e.threeDSecureToken,{payment_method:N,return_url:c??ka(d)??window.location.href},h),"card"):null;if(p){if(p.error)throw or(new Ue.FloPayError(p.error.message??"3DS authentication failed.","api_error",{code:p.error.code}),"card");f=p.intent}else{let C=await mo(()=>g.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(C.error)throw or(new Ue.FloPayError(C.error.message??"3DS authentication failed.","api_error",{code:C.error.code}),"card");f=(h?C.setupIntent:C.paymentIntent)??null}if(f&&(f.status==="requires_capture"||f.status==="succeeded"||f.status==="processing")){let C=await $r({billingApiUrl:o,sessionId:i,session:d,telemetry:v,tokenizedData:{id:f.id,type:"card",threeDSecureActionResultTokenId:f.id},returnUrl:c});return C.type==="success"?{...C.result,paymentIntentId:C.result.paymentIntentId??f.id,paymentMethodId:C.result.paymentMethodId??N}:Ho(C,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:i,session:d,returnUrl:c,telemetry:v})}throw or(new Ue.FloPayError("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let h=(n??t)?.getRawProvider();if(!h)throw or(new Ue.FloPayError("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:N}=await mo(()=>h.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(N)throw or(new Ue.FloPayError(N.message??"PayPal authorization failed.","api_error",{code:N.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:f}=await mo(()=>h.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:c??ka(d)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(f)throw or(new Ue.FloPayError(f.message??"PayPal authorization failed.","api_error",{code:f.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new Ue.FloPayError("Unsupported payment redirect state.","api_error")}function kr(e){if(e instanceof Ue.FloPayError){let r=dr(e.message);return r&&r!==e.message?Object.assign(new Ue.FloPayError(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=dr(t)??t;return new Ue.FloPayError(n,"api_error")}function Ko(e){let t=e.data.stripe?.publishableKey,n=!!e.data.paypal?.publishableKey;if(!t&&!n)throw new Ue.FloPayError("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 Yo({publishableKey:e,paypalPublishableKey:t,billingApiUrl:n,locale:r,telemetry:o}){if(!e)return{flopay:null,paypalFlopay:null};let i=!!t&&t!==e,[d,c]=await Promise.all([(0,qr.loadFloPay)(e,{billingApiUrl:n,locale:r,telemetry:o}),i?(0,qr.loadFloPay)(t,{billingApiUrl:n,locale:r,telemetry:o}).catch(v=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",v),null)):Promise.resolve(null)]);return{flopay:d,paypalFlopay:t?i?c:d:null}}var mr=require("@flopay/js"),u=require("@flopay/shared"),Et=require("@stripe/react-stripe-js"),a=Ci(require("react"),1);function $i(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 ji={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"};var ar=require("react"),Vi=require("react/jsx-runtime");function jr({capture:e,html:t,messageToken:n,expectedOrigin:r,theme:o,containerStyle:i,onReady:d,onError:c,onValidation:v}){let g=(0,ar.useRef)(null),h=(0,ar.useRef)(d),f=(0,ar.useRef)(c),N=(0,ar.useRef)(v);h.current=d,f.current=c,N.current=v;let B=(0,ar.useRef)(o);return B.current=o,(0,ar.useEffect)(()=>{let p=g.current;if(!p)return;let C=!0,he=!1,V=()=>{!C||he||(he=!0,h.current?.())},S=e.on("ready",()=>{V()}),me=e.on("error",K=>{f.current?.(K.message??"There was a problem loading the secure card form.")}),H=e.on("validation",K=>{N.current?.(K.message??null)}),de={html:t,...n?{messageToken:n}:{},...r?{expectedOrigin:r}:{},...B.current?{theme:B.current}:{}};return e.mount(p,de).then(()=>{V()}).catch(K=>{C&&f.current?.(K instanceof Error?K.message:"Failed to load the secure card form.")}),()=>{C=!1,S(),me(),H(),e.unmount()}},[e,t,n,r]),(0,ar.useEffect)(()=>{o&&e.applyTheme?.(o)},[e,o]),(0,Vi.jsx)("div",{ref:g,"data-testid":"flopay-vault-card-fields",style:i})}function Vr(e,t=.12){let n=/^#?([0-9a-fA-F]{6})$/.exec(e.trim());if(!n)return e;let r=parseInt(n[1],16),o=Math.max(0,Math.min(1,1-t)),i=Math.round((r>>16&255)*o),d=Math.round((r>>8&255)*o),c=Math.round((r&255)*o);return`#${(1<<24|i<<16|d<<8|c).toString(16).slice(1)}`}function Ea(e){if(typeof e=="number"||typeof e=="string")return e}function Wo({appearance:e,buttonsStyles:t,layout:n="default"}){let r=e?.variables,o=g=>typeof g=="string"&&g?g:void 0,i=t.submitButton,d=o(r?.colorPrimary)??o(i?.backgroundColor)??"#4A49FF",c=n==="buttons",v=t.nameInput;return{primaryColor:d,primaryHoverColor:o(r?.colorPrimaryHover)??Vr(d,.12),inputBackgroundColor:o(t.cardInputBackground)??o(r?.colorBackground)??"#ffffff",textColor:o(t.cardInputColor)??o(v?.color)??o(r?.colorText)??"#262833",borderColor:o(t.cardInputBorder)??(c?"#e5e7eb":"#A4A4FF"),placeholderColor:o(t.cardInputPlaceholderColor)??"#9ca3af",errorColor:o(r?.colorDanger)??"#dc2626",successColor:"#16a34a",fontFamily:o(v?.fontFamily)??o(r?.fontFamily)??"Poppins, sans-serif",fontSize:o(t.cardInputFontSize)??o(r?.fontSizeBase)??"16px",fontWeight:String(Ea(v?.fontWeight)??400),borderRadius:o(r?.borderRadius)??"8px"}}var s=require("react/jsx-runtime"),Jn="flopay_stripe_resume",Hi="flopay_wallet_resume";function Qi(e){return e instanceof u.FloPayError&&(e.type==="validation_error"||e.statusCode===400||e.statusCode===422)}async function Jo(e,t,...n){let r=n[2].provider;t?.({class:"lifecycle",name:"payment.intent.started",provider:r});try{return await new mr.PaymentAPI(e).createSessionIntent(...n)}catch(o){throw Qi(o)||t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"intent_create",provider:r}),o}}var fo="flopay_paypal_resume",ul=250,Ki="Just a moment \u2014 we are finalizing your order. Please press pay again.";function Aa(e,t,n){e?.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:"provider_runtime",stage:"provider_load",provider:t,paymentMethodCategory:n,requestCategory:"provider_sdk"})}async function Xo({billingApiUrl:e,sessionId:t,nonce:n,request:r}){if(!(!t||!n))try{await new mr.PaymentAPI(e,{telemetry:!1}).reportSessionIntentDecline(t,n,r)}catch{}}function pl(e){return e instanceof u.FloPayError&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function Ra(e){return e?.html?{html:e.html,...e.messageToken?{messageToken:e.messageToken}:{},...e.expectedOrigin?{expectedOrigin:e.expectedOrigin}:{}}:null}function ml({event:e,fallbackEmail:t,fallbackName:n}){let r=e.billingDetails,o=kn(r?.name),i=kn(n);return{email:r?.email?.trim()||t?.trim(),firstName:o.firstName??i.firstName,lastName:o.lastName??i.lastName}}async function es({event:e,prepared:t,email:n,billingName:r,methodLabel:o,collect:i}){let d=ml({event:e,fallbackEmail:t?.accountPatch?.email??n,fallbackName:[t?.accountPatch?.firstName,t?.accountPatch?.lastName].filter(Boolean).join(" ")||r});return!(0,u.isValidEmail)(d.email)||!io(d)?i(o,d):d}var yl=`
10
10
  .paypal-buttons { margin: 0 !important; vertical-align: top !important; }
11
11
  @keyframes flopay-spin { to { transform: rotate(360deg); } }
12
12
  @keyframes flopay-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }
@@ -27,7 +27,7 @@ ${Mt.join(`
27
27
  0% { opacity: 1; transform: translateX(0) scale(1); }
28
28
  100% { opacity: 0; transform: translateX(16px) scale(0.97); }
29
29
  }
30
- `,Go=44;function Ma(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 fl={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"},ts={width:"100%",minHeight:Go,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 gl(e){switch(e){case"paypal":return"PayPal";case"apple_pay":return"Apple Pay";case"google_pay":return"Google Pay";default:return"Card"}}function Yi(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function xa(e){return e==="paypal"?"PayPal":(0,u.getStripeMethodDisplayName)(e)}function hl(e,t){let n=`We couldn't open ${xa(e)}. Try again or choose another payment method.`;return t?`${n} Allow pop-ups for this site, then try again.`:n}function ns(e){let t=(0,a.useRef)(0),n=(0,a.useRef)(null),r=(0,a.useRef)(null),o=(0,a.useCallback)((p=r.current)=>{let C=p;C?.timer&&(clearTimeout(C.timer),C.timer=null)},[]),i=(0,a.useCallback)((p,C)=>{typeof document<"u"&&document.visibilityState!=="visible"||(o(p),p.timer=setTimeout(()=>{p.timer=null,r.current?.generation===p.generation&&(r.current=null,n.current=p.generation,e(p.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}))},C))},[o,e]),d=(0,a.useCallback)(p=>{p.yieldedControl&&i(p,600)},[i]),c=(0,a.useCallback)(p=>{o();let C=t.current+1;t.current=C,n.current=null;let he={generation:C,method:p,timer:null,yieldedControl:!1};return r.current=he,C},[o]),v=(0,a.useCallback)(p=>{let C=r.current;return typeof p=="number"&&C?.generation!==p?!1:(o(C),r.current=null,(typeof p!="number"||n.current===p)&&(n.current=null),!0)},[o]),g=(0,a.useCallback)(p=>{let C=r.current,he=p??C?.generation??t.current;(!p||C?.generation===p)&&(o(C),r.current=null),n.current=he},[o]),h=(0,a.useCallback)(p=>n.current===(p??t.current),[]),f=(0,a.useCallback)(p=>r.current?.generation===p&&n.current!==p,[]),D=(0,a.useCallback)(()=>{let p=r.current;p&&d(p)},[d]),B=(0,a.useCallback)(()=>{let p=r.current;p&&(p.yieldedControl=!0,o(p))},[o]);return(0,a.useEffect)(()=>{let p=()=>{document.visibilityState==="visible"?D():B()},C=()=>{B()};return document.addEventListener("visibilitychange",p),window.addEventListener("blur",C),window.addEventListener("focus",D),()=>{document.removeEventListener("visibilitychange",p),window.removeEventListener("blur",C),window.removeEventListener("focus",D),o()}},[o,B,D]),{startAttempt:c,finishAttempt:v,invalidateAttempt:g,isAttemptInvalidated:h,isAttemptCurrent:f}}function bl(e){let t=(0,u.getPostalCodeExample)(e);return`Enter a valid ${(0,u.getPostalCodeLabel)(e)}${t?` (e.g. ${t})`:""}`}function vl(e,t,n){let r=(0,u.isPostalCodeSupported)(e),o=t.trim(),i=n&&r,d=i&&!o,c=i&&!!o&&!(0,u.isValidPostalCode)(e,o);return{visible:n,supported:r,required:i,empty:d,malformed:c}}function Pl(e,t){let n=e.trim(),r=t&&!n,o=t&&!!n&&!(0,u.isValidEmail)(n);return{required:t,empty:r,malformed:o,value:n}}function Wi(e,t){return t instanceof u.FloPayError?t:new u.FloPayError(t instanceof Error?t.message:`${gl(e)} before-click hook failed.`,"validation_error")}function _a(){return(0,s.jsx)("style",{children:yl})}function Cl(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 os({state:e,placeholderTestId:t,borderRadius:n=8,children:r}){return e==="unavailable"||e==="load_error"?null:(0,s.jsxs)("div",{style:{position:"relative",minHeight:44},children:[(0,s.jsx)("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"}}),(0,s.jsx)("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 Gi(e){return e!=="unavailable"&&e!=="load_error"}function Zo(e){return(0,s.jsx)(wl,{...e})}function Ji({sessionId:e,nonce:t,email:n,billingApiUrl:r,onTokenizedBody:o,onErrorChange:i,isProcessing:d=!1,onButtonClick:c,onDecline:v,onTechnicalFailure:g,runBeforeButtonClick:h,billingName:f,onBuyerIdentityReady:D,onLoadStateChange:B,placeholderBorderRadius:p}){let C=rr(),{emitInstrument:he}=(0,a.useContext)(In),V=(0,Et.useStripe)(),S=(0,Et.useElements)(),[me,H]=(0,a.useState)("loading");(0,a.useEffect)(()=>{B?.(me)},[me,B]);let[de,K]=(0,a.useState)(!1),be=!(0,u.isValidEmail)(n?.trim())||!f?.trim(),{request:$e,collect:we,finish:gt}=Nr(),Fe=(0,a.useRef)(!1),Ee=(0,a.useRef)(null),Re=(0,a.useRef)(null),[oe,ne]=(0,a.useState)(0),[O,ue]=(0,a.useState)(!1),We=(0,a.useRef)(!1),re=(0,a.useRef)(new Map),{startAttempt:Te,finishAttempt:Z,invalidateAttempt:T,isAttemptInvalidated:j,isAttemptCurrent:Ae}=ns((ie,ae,X)=>{g?.(ie,ae,{...X,popupBlocked:X?.popupBlocked??ur(ae)}),ue(!0),ne(xe=>xe+1)});(0,a.useEffect)(()=>{O&&Re.current?.focus()},[O,oe]);let ye=(0,a.useCallback)(()=>{ne(ie=>ie+1)},[]),Q=(0,a.useCallback)((ie,ae,X)=>{T(X),g?.("paypal",ie,{code:ae,popupBlocked:ur(ie)}),ue(!0),ye()},[T,g,ye]),De=(0,a.useCallback)(()=>{window.setTimeout(()=>{(Ee.current?.querySelector("iframe")??Ee.current)?.focus()},0)},[]);(0,a.useEffect)(()=>{We.current&&(We.current=!1,De())},[De,oe]);let Qe=(0,a.useCallback)(()=>{ue(!1),i?.(null),De()},[De,i]);(0,a.useEffect)(()=>{if(!V||Fe.current)return;let ie=new URLSearchParams(window.location.search),ae=ie.get("payment_intent"),X=ie.get("payment_intent_client_secret"),xe=ie.get("redirect_status");if(!ae||!X)return;Fe.current=!0;let Le;try{let ee=localStorage.getItem(fo);if(ee){let A=JSON.parse(ee);A.clientSecret===X&&(Le={...A.accountPatch?{accountPatch:A.accountPatch}:{},...A.sessionId?{sessionId:A.sessionId}:{},...A.nonce?{nonce:A.nonce}:{}})}}catch{}try{localStorage.removeItem(fo)}catch{}let L=new URL(window.location.href);L.searchParams.delete("payment_intent"),L.searchParams.delete("payment_intent_client_secret"),L.searchParams.delete("redirect_status"),window.history.replaceState({},"",L.toString()),(async()=>{try{if(K(!0),xe==="failed"){let R="PayPal payment was declined. Please try again.";i?.(R),v?.($t("paypal",R));return}let{paymentIntent:ee,error:A}=await V.retrievePaymentIntent(X);if(A){i?.(A.message??"Failed to retrieve PayPal payment status.");return}if(ee&&(ee.status==="requires_capture"||ee.status==="succeeded")){let R=typeof ee.payment_method=="string"?ee.payment_method:ee.payment_method?.id;o({id:R??ee.id,type:"card",threeDSecureActionResultTokenId:ee.id,isPaypal:!0},Le)}else{let R="PayPal payment was not completed. Please try again.";i?.(R),v?.($t("paypal",R))}}catch(ee){i?.(ee instanceof Error?ee.message:"Failed to complete PayPal payment.")}finally{K(!1)}})()},[V,o,i,v]);let Ze=(0,a.useCallback)(async ie=>{if(d||de){ie.reject();return}let ae=h?await h("paypal"):{proceed:!0};if(!ae.proceed){re.current.delete(oe),ie.reject();return}let X=Te("paypal");re.current.set(oe,{generation:X,accountPatch:ae.accountPatch,sessionId:ae.sessionId,nonce:ae.nonce}),ue(!1),c?.("paypal"),ie.resolve()},[re,d,c,h,Te,de,oe]),_e=(0,a.useCallback)(async ie=>{if(!V||!S)return;let ae=re.current.get(oe);if(ae&&!Ae(ae.generation)){re.current.delete(oe);return}if(!ae&&j()||ae&&!Z(ae.generation))return;ae||Z();let X=ae??null;if(re.current.delete(oe),!X&&h){let R=await h("paypal");if(!R.proceed){ie.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}X={accountPatch:R.accountPatch,sessionId:R.sessionId,nonce:R.nonce}}let xe=X?.sessionId??e,Le=X?.nonce??t,L=await es({event:ie,prepared:X,email:n,billingName:f,methodLabel:"PayPal",collect:we});if(!L){ie.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let ee=L.email,A={...X?.accountPatch,...L};try{if(K(!0),i?.(null),!xe||!(0,u.isValidEmail)(ee))throw new Error("Missing sessionId or email for PayPal payment");await D?.(L);let R=V.createPaymentMethod,{error:rt,paymentMethod:St}=await R({type:"paypal"});if(rt){Q(rt,"stripe_paypal_create_payment_method_failed",ae?.generation),ie.paymentFailed({reason:"fail"});return}let ve=await Jo(r,he,xe,Le??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:St?.id??null,intentKind:"payment"});if(ve.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let ct=ve.clientSecret,st={return_url:window.location.href};if(St?.id&&(st.payment_method=St.id),typeof window<"u")try{localStorage.setItem(fo,JSON.stringify({clientSecret:ct,sessionId:xe,nonce:Le,accountPatch:A}))}catch{}let{error:ot,paymentIntent:Ge}=await V.confirmPayment({clientSecret:ct,confirmParams:st,redirect:"if_required"});if(ot){if(typeof window<"u")try{localStorage.removeItem(fo)}catch{}if(so(ot)){let G=ot.message??"Your payment was declined.";i?.(G),v?.($t("paypal",G,{code:nr(ot),declineCode:Lr(ot)})),await Xo({billingApiUrl:r,sessionId:xe,nonce:Le,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:nr(ot)??"provider_declined"}})}else Q(ot,"stripe_paypal_confirm_failed",ae?.generation);return}if(typeof window<"u")try{localStorage.removeItem(fo)}catch{}let b=typeof Ge?.payment_method=="string"?Ge.payment_method:Ge?.payment_method?.id;o({id:b??Ge?.id,type:"card",threeDSecureActionResultTokenId:Ge?.id,isPaypal:!0},{accountPatch:A,sessionId:xe,nonce:Le});return}catch(R){Q(R,"stripe_paypal_failed",ae?.generation)}finally{K(!1)}},[V,S,e,t,n,f,we,D,r,he,o,i,v,h,Q,Z,Ae,j,oe]);return(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(os,{state:me,placeholderTestId:"flopay-paypal-placeholder",borderRadius:p,children:(0,s.jsxs)("div",{ref:Ee,tabIndex:-1,"data-testid":"flopay-paypal-focus-target",role:"group","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[O&&(0,s.jsx)("button",{ref:Re,type:"button","data-testid":"flopay-paypal-retry-button",onClick:Qe,style:ts,children:"Try PayPal again"}),$e&&(0,s.jsx)(Cr,{identity:$e.identity,methodLabel:$e.methodLabel,onComplete:gt,onCancel:()=>gt(null)},$e.id),(0,s.jsx)("div",{style:{display:$e?"none":void 0},children:(0,s.jsx)(Et.ExpressCheckoutElement,{onReady:ie=>H(rs(ie,["paypal"])),onLoadError:()=>{H("load_error"),Aa(jt(C),"paypal","paypal")},onClick:Ze,onConfirm:_e,onCancel:()=>{let ie=re.current.get(oe);re.current.delete(oe),jt(C)?.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),T(ie?.generation),ue(!1),We.current=!0,ye()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:be,emailRequired:be,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},oe)})]})}),de&&(0,s.jsx)(Rn,{status:"processing"})]})}function Xi({sessionId:e,nonce:t,email:n,billingApiUrl:r,intentKind:o,expressMethods:i,onTokenizedBody:d,onErrorChange:c,onButtonClick:v,onDecline:g,onTechnicalFailure:h,runBeforeButtonClick:f,billingName:D,onBuyerIdentityReady:B,onLoadStateChange:p,placeholderBorderRadius:C}){let he=rr(),{emitInstrument:V}=(0,a.useContext)(In),S=(0,Et.useStripe)(),me=(0,Et.useElements)(),[H,de]=(0,a.useState)("loading");(0,a.useEffect)(()=>{p?.(H)},[H,p]);let[K,be]=(0,a.useState)(!1),$e=!(0,u.isValidEmail)(n?.trim())||!D?.trim(),{request:we,collect:gt,finish:Fe}=Nr(),Ee=(0,a.useRef)(null),Re=(0,a.useRef)(null),[oe,ne]=(0,a.useState)(0),[O,ue]=(0,a.useState)(!1),[We,re]=(0,a.useState)("google_pay"),Te=(0,a.useRef)(!1),Z=(0,a.useRef)("google_pay"),T=(0,a.useRef)("google_pay"),j=(0,a.useRef)(new Map),{startAttempt:Ae,finishAttempt:ye,invalidateAttempt:Q,isAttemptInvalidated:De,isAttemptCurrent:Qe}=ns((L,ee,A)=>{h?.(L,ee,{...A,popupBlocked:A?.popupBlocked??ur(ee)}),re(L),ue(!0),ne(R=>R+1)});(0,a.useEffect)(()=>{O&&Re.current?.focus()},[O,oe]);let Ze=(0,a.useCallback)(()=>{ne(L=>L+1)},[]),_e=(0,a.useCallback)((L,ee,A,R)=>{Q(R),h?.(L,ee,{code:A,popupBlocked:ur(ee)}),re(L),ue(!0),Ze()},[Q,h,Ze]),ie=(0,a.useCallback)(()=>{window.setTimeout(()=>{(Ee.current?.querySelector("iframe")??Ee.current)?.focus()},0)},[]);(0,a.useEffect)(()=>{Te.current&&(Te.current=!1,ie())},[ie,oe]);let ae=(0,a.useCallback)(()=>{ue(!1),c?.(null),ie()},[ie,c]),X=(0,a.useCallback)(async L=>{if(!S||!me)return;let ee=j.current.get(oe);if(ee&&!Qe(ee.generation)){j.current.delete(oe);return}if(!ee&&De()||ee&&!ye(ee.generation))return;ee||ye();let A=L.expressPaymentType??ee?.method??Z.current,R=ee??null;j.current.delete(oe);let rt=Yi(A);if(!R&&f){let b=await f(rt);if(!b.proceed){L.paymentFailed({reason:"fail",message:"Wallet checkout was cancelled."});return}R={accountPatch:b.accountPatch,sessionId:b.sessionId,nonce:b.nonce}}let St=rt,ve=R?.sessionId??e,ct=R?.nonce??t,st=await es({event:L,prepared:R,email:n,billingName:D,methodLabel:xa(A),collect:gt});if(!st){L.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let ot=st.email,Ge={...R?.accountPatch,...st};try{if(be(!0),c?.(null),!(0,u.isValidEmail)(ot))throw new Error("Missing sessionId or email for wallet payment");await B?.(st);let{error:b}=await me.submit();if(b){_e(A,b,"stripe_wallet_submit_failed",ee?.generation);return}let{error:G,paymentMethod:et}=await S.createPaymentMethod({elements:me});if(G||!et){_e(A,G??new Error("Failed to create payment method."),"stripe_wallet_create_payment_method_failed",ee?.generation);return}if(!ve)throw new Error("Missing sessionId or email for wallet payment");let dt=await Jo(r,V,ve,ct??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:A??rt,paymentMethodId:et.id,intentKind:o});if(dt.provider!=="stripe")throw new Error("Invalid provider returned for wallet intent");let Mt=dt.clientSecret,{error:Bt,intentId:se}=(0,u.isSetupIntentClientSecret)(Mt)?await S.confirmCardSetup(Mt,{payment_method:et.id}).then(Ve=>({error:Ve.error,intentId:Ve.setupIntent?.id})):await S.confirmCardPayment(Mt,{payment_method:et.id}).then(Ve=>({error:Ve.error,intentId:Ve.paymentIntent?.id}));if(Bt){if(so(Bt)){let Ve=Bt.message??"Your payment was declined.";c?.(Ve),g?.($t(St,Ve,{code:nr(Bt),declineCode:Lr(Bt)})),await Xo({billingApiUrl:r,sessionId:ve,nonce:ct,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:A??rt,providerDeclineReason:nr(Bt)??"provider_declined"}})}else _e(A,Bt,"stripe_wallet_confirm_failed",ee?.generation);return}d({id:et.id,type:"card",threeDSecureActionResultTokenId:se},{accountPatch:Ge,sessionId:ve,nonce:ct})}catch(b){_e(A,b,"stripe_wallet_failed",ee?.generation)}finally{be(!1)}},[S,me,e,t,n,D,gt,B,r,V,o,d,c,g,f,_e,ye,Qe,De,oe]),xe=(0,a.useMemo)(()=>{let L=["applePay","googlePay","paypal","link","amazonPay","klarna"],ee=new Set(["applePay","googlePay"]),A=new Set(i.map(u.stripeExpressMethodToOptionKey)),R={};for(let rt of L)A.has(rt)?R[rt]=ee.has(rt)?"always":"auto":R[rt]="never";return R},[i]),Le=(0,a.useMemo)(()=>i.map(u.stripeExpressMethodToOptionKey),[i]);return(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(os,{state:H,placeholderTestId:"flopay-wallet-placeholder",borderRadius:C,children:(0,s.jsxs)("div",{ref:Ee,tabIndex:-1,"data-testid":"flopay-wallet-focus-target",role:"group","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[O&&(0,s.jsxs)("button",{ref:Re,type:"button","data-testid":"flopay-wallet-retry-button",onClick:ae,style:ts,children:["Try ",xa(We)," again"]}),we&&(0,s.jsx)(Cr,{identity:we.identity,methodLabel:we.methodLabel,onComplete:Fe,onCancel:()=>Fe(null)},we.id),(0,s.jsx)("div",{style:{display:we?"none":void 0},children:(0,s.jsx)(Et.ExpressCheckoutElement,{onReady:L=>{de(rs(L,Le))},onLoadError:L=>{de("load_error"),Aa(jt(he),"stripe","wallet")},onClick:async L=>{Z.current=L.expressPaymentType,T.current=Yi(L.expressPaymentType);let ee=f?await f(T.current):{proceed:!0};if(!ee.proceed){j.current.delete(oe),L.reject();return}let A=Ae(L.expressPaymentType);j.current.set(oe,{generation:A,method:L.expressPaymentType,accountPatch:ee.accountPatch,sessionId:ee.sessionId,nonce:ee.nonce}),ue(!1),v?.(T.current),L.resolve()},onConfirm:X,onCancel:()=>{let L=j.current.get(oe);j.current.delete(oe),jt(he)?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet"}),Q(L?.generation),ue(!1),Te.current=!0,Ze()},options:{buttonType:{applePay:"plain",googlePay:"plain"},paymentMethods:xe,emailRequired:$e,billingAddressRequired:$e,layout:{maxColumns:1,overflow:"never"}}},oe)})]})}),K&&(0,s.jsx)(Rn,{status:"processing"})]})}function Sl({method:e,themeId:t,submitting:n=!1,disabled:r=!1,highlighted:o=!1,hasNextStep:i=!1,onClick:d,backgroundColor:c,borderColor:v,textColor:g,borderRadius:h,fontFamily:f}){let D=(0,u.resolveStripeMethodBrandVariant)(e,t),B=ji[e],[p,C]=(0,a.useState)(!1),he=D?.backgroundColor??c??"#ffffff",V=D?.borderColor??v??"#d1d5db",S=D?.textColor??g??"#262833";return(0,s.jsx)("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:Go,padding:"0 1rem",backgroundColor:he,color:S,border:`1px solid ${V}`,borderRadius:h??8,fontSize:"0.95rem",fontWeight:600,fontFamily:f,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?(0,s.jsx)("span",{style:{margin:"0 auto"},children:`Connecting to ${(0,u.getStripeMethodDisplayName)(e)}\u2026`}):(0,s.jsxs)(s.Fragment,{children:[(0,s.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:(0,u.hasVendoredStripeMethodLogo)(e)?8:0},children:[B&&!p?(0,s.jsx)("img",{src:B,alt:"","aria-hidden":"true",onError:()=>C(!0),loading:"lazy",decoding:"async",width:30,height:20,style:{width:30,height:20,flexShrink:0,borderRadius:3,objectFit:"contain",display:"inline-flex"}}):D?.logoSvg?(0,s.jsx)("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:D.logoSvg}}):null,(0,s.jsx)("span",{children:(0,u.getStripeMethodDisplayName)(e)})]}),i&&(0,s.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:S,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:(0,s.jsx)("path",{d:"M9 18l6-6-6-6"})})]})})}function Ta({method:e,sessionId:t,nonce:n,email:r,billingName:o,onBuyerIdentityReady:i,billingApiUrl:d,onTokenizedBody:c,onErrorChange:v,onDecline:g,onCancel:h,runBeforeButtonClick:f,onButtonClick:D,isProcessing:B,submitButtonColor:p,submitButtonBorderRadius:C,submitButtonStyle:he,errorText:V}){let S=rr(),{emitInstrument:me}=(0,a.useContext)(In),H=(0,Et.useStripe)(),de=(0,Et.useElements)(),[K,be]=(0,a.useState)(!1),$e=(0,a.useRef)(!1),[we,gt]=(0,a.useState)(!1),[Fe,Ee]=(0,a.useState)("loading"),[Re,oe]=(0,a.useState)(""),[ne,O]=(0,a.useState)(""),ue=!(0,u.isValidEmail)(r?.trim()),We=!o?.trim(),re=(!ue||(0,u.isValidEmail)(Re.trim()))&&(!We||!!ne.trim()),Te=(0,a.useCallback)(async()=>{if(!H||!de||B||$e.current||!we)return;$e.current=!0,be(!0);let Z=f?await f("card"):{proceed:!0};if(!Z.proceed){$e.current=!1,be(!1);return}D?.("card");let T=Z.sessionId??t,j=Z.nonce??n,Ae=kn(o?.trim()||ne.trim()),ye={email:Z.accountPatch?.email?.trim()||r?.trim()||Re.trim(),firstName:Z.accountPatch?.firstName?.trim()||Ae.firstName,lastName:Z.accountPatch?.lastName?.trim()||Ae.lastName},Q=ye.email,De={...Z.accountPatch,...ye};try{if(v?.(null),!(0,u.isValidEmail)(Q)||!io(ye))throw new Error("A valid email address and full name are required for payment.");await i?.(ye);let Qe=await de.submit();if(Qe.error){v?.(Qe.error.message??"Payment failed.");return}let Ze=await H.createPaymentMethod({elements:de,params:{billing_details:{email:Q,name:[ye.firstName,ye.lastName].filter(Boolean).join(" ")}}});if(Ze.error||!Ze.paymentMethod){v?.(Ze.error?.message??"Failed to create payment method.");return}let _e=Ze.paymentMethod;if(!T||!Q)throw new Error("Missing sessionId or email for payment.");let ie=_e.type||e,ae=await Jo(d,me,T,j??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:ie,paymentMethodId:null,intentKind:"payment"});if(ae.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let X=ae.clientSecret;if(typeof window<"u")try{localStorage.setItem(Jn,JSON.stringify({clientSecret:X,sessionId:T,nonce:j,accountPatch:De,paymentMethodId:_e.id,paymentMethodType:_e.type??e,gateway:"stripe"}))}catch{}let{error:xe,paymentIntent:Le}=await H.confirmPayment({clientSecret:X,confirmParams:{return_url:window.location.href,payment_method:_e.id},redirect:"if_required"});if(xe){if(typeof window<"u")try{localStorage.removeItem(Jn)}catch{}let A=xe.message??"Payment failed.";v?.(A),g?.($t("card",A,{code:xe.code})),await Xo({billingApiUrl:d,sessionId:T,nonce:j,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:xe.code??"provider_declined"}});return}let L=Le?.status;if(!No(L)){if(typeof window<"u")try{localStorage.removeItem(Jn)}catch{}let A=L==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";v?.(A),g?.($t("card",A,{code:L??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(Jn)}catch{}let ee=typeof Le?.payment_method=="string"?Le.payment_method:Le?.payment_method?.id;c({id:ee??_e.id,type:"card",threeDSecureActionResultTokenId:Le?.id,gateway:"stripe",paymentMethodType:_e.type??e},{accountPatch:De,sessionId:T,nonce:j})}catch(Qe){v?.(Qe instanceof Error?Qe.message:"Payment failed. Please try again.")}finally{$e.current=!1,be(!1)}},[H,de,B,we,f,D,t,n,r,o,Re,ne,i,d,me,e,c,v,g]);return(0,s.jsxs)("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[(ue||We)&&(0,s.jsxs)("div",{"data-testid":"flopay-apm-identity-fields",style:{display:"flex",flexDirection:"column",gap:"0.75rem",marginBottom:"0.75rem"},children:[ue&&(0,s.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",(0,s.jsx)("input",{type:"email",autoComplete:"email",required:!0,value:Re,onChange:Z=>oe(Z.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]}),We&&(0,s.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Full name",(0,s.jsx)("input",{type:"text",autoComplete:"name",required:!0,value:ne,onChange:Z=>O(Z.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]})]}),(0,s.jsx)(Et.PaymentElement,{onReady:()=>Ee("ready"),onLoadError:()=>{Ee("load_error"),Aa(jt(S),"stripe","apm")},onChange:Z=>{gt(!!Z.complete)},options:{layout:{type:"accordion",defaultCollapsed:!1,radios:"never"},defaultValues:{billingDetails:{...o?.trim()?{name:o.trim()}:{},...(0,u.isValidEmail)(r?.trim())?{email:r?.trim()}:{}}}}}),(0,s.jsx)("button",{type:"button","data-testid":`flopay-stripe-method-pay-${e}`,onClick:()=>{Te()},disabled:!we||!re||K||B||Fe!=="ready",style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:p,color:"white",border:"none",borderRadius:C,fontSize:"1rem",fontWeight:600,cursor:!we||!re||K||B||Fe!=="ready"?"not-allowed":"pointer",opacity:!we||!re||K||B||Fe!=="ready"?.5:1,transition:"opacity 120ms ease-out",...he??{}},children:K?"Processing\u2026":`Pay with ${(0,u.getStripeMethodDisplayName)(e)}`}),V&&(0,s.jsx)(zr,{margin:"0.75rem 0 0",children:V})]})}function Zi({sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:i,paymentElementMethods:d,stripeInstance:c,paymentElementBaseOptions:v,onTokenizedBody:g,onErrorChange:h,onButtonClick:f,onDecline:D,runBeforeButtonClick:B,onLoadStateChange:p,isProcessing:C=!1,submitButtonColor:he="#4A49FF",submitButtonBorderRadius:V=8,submitButtonStyle:S,buttonAppearance:me,themeId:H,onExpandApm:de,expandedApmMethod:K}){let{emitInstrument:be}=(0,a.useContext)(In),[$e,we]=(0,a.useState)(null),[gt,Fe]=(0,a.useState)(null),Ee=(0,a.useRef)(!1),{request:Re,collect:oe,finish:ne}=Nr();(0,a.useEffect)(()=>{d.length>0&&c?p?.("ready"):c||p?.("loading")},[d.length,c,p]);let O=(0,a.useCallback)(async T=>{if(!c||Ee.current||C)return;Ee.current=!0,Fe(T);let j=B?await B("card"):{proceed:!0};if(!j.proceed){Ee.current=!1,Fe(null);return}f?.("card");let Ae=j.sessionId??e,ye=j.nonce??t,Q=kn([j.accountPatch?.firstName,j.accountPatch?.lastName].filter(Boolean).join(" ")||r),De={email:j.accountPatch?.email?.trim()||n?.trim(),firstName:j.accountPatch?.firstName?.trim()||Q.firstName,lastName:j.accountPatch?.lastName?.trim()||Q.lastName};if(!(0,u.isValidEmail)(De.email)||!io(De)){Fe(null);let _e=await oe((0,u.getStripeMethodDisplayName)(T),De);if(!_e){Ee.current=!1;return}De=_e,Fe(T)}let Qe=De.email,Ze={...j.accountPatch,...De};try{if(h?.(null),!Ae||!(0,u.isValidEmail)(Qe)||!io(De))throw new Error("Missing sessionId or email for payment.");await o?.(De);let _e=await Jo(i,be,Ae,ye??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:T,paymentMethodId:null,intentKind:"payment"});if(_e.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let ie=_e.clientSecret;if(typeof window<"u")try{localStorage.setItem(Jn,JSON.stringify({clientSecret:ie,sessionId:Ae,nonce:ye,accountPatch:Ze,paymentMethodType:T,gateway:"stripe"}))}catch{}let{error:ae,paymentIntent:X}=await c.confirmPayment({clientSecret:ie,confirmParams:{return_url:window.location.href,payment_method_data:{type:T,billing_details:{name:[De.firstName,De.lastName].filter(Boolean).join(" "),...Qe?{email:Qe}:{}}}},redirect:"if_required"});if(ae){if(typeof window<"u")try{localStorage.removeItem(Jn)}catch{}let L=ae.message??"Payment failed.";h?.(L),D?.($t("card",L,{code:ae.code})),await Xo({billingApiUrl:i,sessionId:Ae,nonce:ye,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:T,providerDeclineReason:ae.code??"provider_declined"}});return}let xe=X?.status;if(!No(xe)){if(typeof window<"u")try{localStorage.removeItem(Jn)}catch{}let L=xe==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";h?.(L),D?.($t("card",L,{code:xe??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(Jn)}catch{}let Le=typeof X?.payment_method=="string"?X.payment_method:X?.payment_method?.id;g({id:Le??X?.id,type:"card",threeDSecureActionResultTokenId:X?.id,gateway:"stripe",paymentMethodType:T},{accountPatch:Ze,sessionId:Ae,nonce:ye})}catch(_e){h?.(_e instanceof Error?_e.message:"Payment failed. Please try again.")}finally{Ee.current=!1,Fe(null)}},[c,C,B,f,e,t,n,oe,i,be,r,o,g,h,D]),[ue,We]=(0,a.useState)(null),re=de?K??null:ue,Te=(0,a.useCallback)(T=>{Ee.current||C||re&&re!==T||((0,u.needsStripeMethodExplicitConfirm)(T)?de?de(T):We(T):O(T))},[re,C,O,de]),Z=(0,a.useMemo)(()=>ue?{...v,paymentMethodTypes:[ue]}:null,[ue,v]);return(0,s.jsx)("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:Re?(0,s.jsx)(Cr,{identity:Re.identity,methodLabel:Re.methodLabel,onComplete:ne,onCancel:()=>ne(null)},Re.id):d.map(T=>{let j=K===T,Ae=gt===T,ye=gt!==null&&gt!==T||K!=null&&K!==T;return(0,s.jsxs)(a.default.Fragment,{children:[(0,s.jsx)(Sl,{method:T,themeId:H,submitting:Ae,disabled:ye,highlighted:j,hasNextStep:(0,u.needsStripeMethodExplicitConfirm)(T),onClick:()=>Te(T),backgroundColor:me?.backgroundColor,borderColor:me?.borderColor,textColor:me?.textColor,borderRadius:me?.borderRadius,fontFamily:me?.fontFamily}),!de&&ue===T&&Z&&c&&(0,s.jsx)(Et.Elements,{stripe:c,options:Z,children:(0,s.jsx)(Ta,{method:T,sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:i,onTokenizedBody:g,onErrorChange:h,onDecline:D,onCancel:()=>We(null),runBeforeButtonClick:B,onButtonClick:f,isProcessing:C,submitButtonColor:he,submitButtonBorderRadius:V,submitButtonStyle:S})},T)]},T)})})}function wl({sessionId:e,nonce:t,billingApiUrl:n,email:r,userId:o,onComplete:i,onError:d,onDecline:c,onTokenizedBody:v,firstName:g,lastName:h,chv:f,className:D,isProcessing:B,error:p,onErrorChange:C,showPayPal:he=!0,showStripe:V=!0,enabledPaymentMethods:S,enabledPaymentMethodCountries:me,showApplePay:H=!0,showGooglePay:de=!0,layout:K="default",theme:be,buttonsTheme:$e,buttonsStyles:we,appearance:gt,cardButtonContent:Fe,cardBackButtonContent:Ee,cardTitleContent:Re,showSecurityFooter:oe,onButtonClick:ne,onBeforeButtonClick:O,onBuyerIdentityReady:ue,enableAVS:We,cardFieldOrder:re,cardPreFormSlot:Te,avsLayout:Z="row",country:T,zip:j,addressLine1:Ae,addressLine2:ye,city:Q,state:De,onCountryChange:Qe,onZipChange:Ze,avsCheck:_e,checkoutType:ie,checkoutLayout:ae,totalAmount:X=0,currency:xe="usd",initialCardOpen:Le=!1,directPaypal:L,isSubscription:ee=!1,session:A,dataAttachmentPending:R=!1,dataAttachmentRequiresIdentity:rt=!1,debug:St=!1}){let ve=rr(),ct=Lo(),st=(0,a.useContext)(zn),{emitInstrument:ot}=(0,a.useContext)(In),Ge=R||st.claimPending===!0,b=rt||st.claimRequiresIdentity===!0,G=Ge&&!b,et=Ti(),[dt,Mt]=(0,a.useState)(!1),[Bt,se]=(0,a.useState)(null),[Ve,Wt]=(0,a.useState)(T??"US"),[wt,Ot]=(0,a.useState)(j??""),[xn,Tn]=(0,a.useState)(Ae??""),[Qn,Gt]=(0,a.useState)(ye??""),[sn,ln]=(0,a.useState)(Q??""),[Ft,Pn]=(0,a.useState)(De??""),[bt,sr]=(0,a.useState)(""),[Vt,lr]=(0,a.useState)(""),[Dt,$n]=(0,a.useState)({}),at=(0,a.useRef)(j??""),Rt=(0,a.useRef)(T??"US"),_t=(0,a.useRef)(Ae??""),Qt=(0,a.useRef)(ye??""),cn=(0,a.useRef)(Q??""),dn=(0,a.useRef)(De??""),jn=(0,a.useRef)(""),Vn=(0,a.useRef)(""),zt=(0,a.useRef)({});(0,a.useEffect)(()=>{let l=(F,$,Ie,W,Be)=>{if(zt.current[F])return;let je=$?.trim();!je||je===Ie.current||(Ie.current=je,W(je),Be?.(je))};l("country",T,Rt,Wt,Qe),l("zip",j,at,Ot,Ze),l("addressLine1",Ae,_t,Tn),l("addressLine2",ye,Qt,Gt),l("city",Q,cn,ln),l("state",De,dn,Pn)},[T,j,Ae,ye,Q,De,Qe,Ze]);let le=(0,a.useMemo)(()=>(0,u.resolveAVSConfig)(We),[We]),Cn=le!==null,An=(0,a.useMemo)(()=>(0,u.isAuthorizationOnlySession)(A),[A]),er=!!A?.vault?.html,yr=!!A?.gateways?.pcivault,Mn=!!(A?.gateways?.stripe?.enabledPaymentMethods??S)?.includes("card"),un=er||Mn||yr,Oe=!!(V&&un&&ve&&e),[Jt,Nt]=(0,a.useState)(()=>K!=="buttons"||Le?e??null:null),[Hn,k]=(0,a.useState)(0),ut=K!=="buttons"||Le||!!e&&Jt===e,Ke=(0,a.useMemo)(()=>!ve||!Oe||!e||!ut?null:ve.cardCapture({sessionId:e,captureMethod:A?.captureMethod}),[ve,Oe,e,ut,A?.captureMethod]),pn=(0,a.useMemo)(()=>{let l=Ve,F=le?(0,u.isAVSFieldVisible)(le.postal_code,l):!1;return vl(l,wt,F)},[le,Ve,wt]),{avsInvalid:tt,invalidAvsFields:Ut}=(0,a.useMemo)(()=>{let l={line1:!1,city:!1,state:!1,zip:!1};if(!Oe||!le)return{avsInvalid:!1,invalidAvsFields:l};let F=Ve,$=(Be,je)=>(0,u.isAVSFieldVisible)(Be,F)&&!je.trim(),Ie={line1:$(le.address_line_1,xn),city:$(le.city,sn),state:$(le.state,Ft),zip:pn.empty||pn.malformed};return{avsInvalid:Ie.line1||Ie.city||Ie.state||Ie.zip,invalidAvsFields:Ie}},[Oe,le,Ve,xn,sn,Ft,pn]),[cr,Kn]=(0,a.useState)(!1),[Sn,Xt]=(0,a.useState)(!1),[mn,yn]=(0,a.useState)(()=>Ra(A?.vault)),[Ne,kt]=(0,a.useState)(Le&&un?"card":"buttons"),[xt,Bn]=(0,a.useState)(null),fn=Ne==="expanding"||Ne==="card",Fn=A?.gateways?.stripe?"stripe":void 0,Dn=(0,a.useCallback)(()=>{ot?.({class:"card_surface",provider:Fn})},[Fn,ot]),qt=280,nn=(0,a.useRef)(null),rn=(0,a.useCallback)(l=>{nn.current&&clearTimeout(nn.current),nn.current=setTimeout(()=>{nn.current=null,l()},qt)},[qt]);(0,a.useEffect)(()=>()=>{nn.current&&clearTimeout(nn.current)},[]);let tr=(0,a.useCallback)(()=>{Dn(),Nt(e??null),k(l=>l+1),kt("expanding"),rn(()=>kt("card"))},[rn,Dn,e]),Rr=(0,a.useCallback)(()=>{kt("collapsing"),rn(()=>kt("buttons"))},[rn]),Nn=(0,a.useCallback)(l=>{Bn(l),kt("apm-expanding"),rn(()=>kt("apm-form"))},[rn]),Yn=(0,a.useCallback)(()=>{kt("apm-collapsing"),rn(()=>{kt("buttons"),Bn(null)})},[rn]);(0,a.useEffect)(()=>{K==="buttons"&&Le&&un&&(Nt(e??null),kt("card"))},[K,Le,un,e]);let[Zt,it]=(0,a.useState)(null),Ht=(0,a.useRef)(!1),N=(0,a.useRef)(null),M=(0,a.useRef)("idle"),[te,ce]=(0,a.useState)(null),Ye=(0,a.useRef)(te);(0,a.useEffect)(()=>{Ye.current=te},[te]);let pe=n||et,U=p??Bt,w=(0,a.useMemo)(()=>(0,u.resolveTheme)(be),[be]),P=(0,a.useMemo)(()=>{let l=w?.buttonsLayout??(0,u.resolveButtonsLayoutTheme)($e);return we?{...l,...we,cardButton:{...l.cardButton,...we.cardButton},cardFormContainer:{...l.cardFormContainer,...we.cardFormContainer},backButton:{...l.backButton,...we.backButton},backButtonIcon:{...l.backButtonIcon,...we.backButtonIcon},submitButton:{...l.submitButton,...we.submitButton},title:{...l.title,...we.title}}:l},[w,$e,we]),Y=gt??w?.appearance,pt=(0,a.useMemo)(()=>Wo({appearance:Y,buttonsStyles:P,layout:K}),[Y,P,K]),vt=st.inlineSessionPatchProcessing??!1,m=(B??dt)||vt,y=pe.replace(/\/+$/,""),x=(0,a.useMemo)(()=>va({userId:o,email:r,firstName:g,lastName:h,country:T,zip:j},Dt),[o,r,g,h,T,j,Dt]),Me=[x.firstName,x.lastName].filter(l=>!!l?.trim()).join(" "),J=!(0,u.isValidEmail)(x.email?.trim()),q=!Me.trim(),Xe=(0,a.useRef)(null),nt=(0,a.useRef)(null);Oe&&(Xe.current===null&&(Xe.current=J),nt.current===null&&(nt.current=q));let fe=Oe&&(Xe.current??J),Pe=Oe&&(nt.current??q),z=fe||Pe,ge=(0,a.useMemo)(()=>Pl(bt,fe),[bt,fe]),lt=ge.empty||ge.malformed,Lt=Pe&&!Vt.trim(),ke=(0,a.useMemo)(()=>ve?ve.getRawProvider():null,[ve]),gn=(0,a.useMemo)(()=>ct?ct.getRawProvider():null,[ct]),Kr=X||100,Po=(0,a.useMemo)(()=>Y?(0,mr.toStripeAppearance)(Y):null,[Y]),Co=Po?{appearance:Po}:null,Va=(0,a.useMemo)(()=>{let l=Po??{},F=l.rules??{};return{...l,rules:{...F,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...F[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...F[".AccordionItemContents"]??{}}}}},[Po]),Ha=(0,a.useMemo)(()=>{let l=Ei(X);return{...l,currency:xe.toLowerCase(),paymentMethodCreation:"manual",...l.mode==="payment"?{captureMethod:"manual"}:{},...Co}},[X,xe,Co]),Ka=(0,a.useMemo)(()=>({mode:"payment",amount:Kr,currency:xe.toLowerCase(),captureMethod:"manual",setupFutureUsage:"off_session",...Co}),[Kr,xe,Co]),Ce=(0,a.useCallback)(l=>{se(l),C?.(l)},[C]),aa=(0,a.useRef)(""),[Ya,fs]=(0,a.useState)(!1),So=(0,a.useCallback)(()=>{fs(!0)},[]);(0,a.useEffect)(()=>{if(!Oe||!z||!ue||!Ya||lt||Lt||aa.current)return;let l=kn(Vn.current),F={email:(0,u.isValidEmail)(x.email?.trim())?x.email?.trim():jn.current.trim(),firstName:x.firstName?.trim()||l.firstName,lastName:x.lastName?.trim()||l.lastName};aa.current=JSON.stringify(F),$n($=>({...$,...F})),Promise.resolve(ue(F)).catch($=>{aa.current="",Ce($ instanceof Error?$.message:"Failed to attach buyer details.")})},[Oe,z,ue,Ya,lt,Lt,x.email,x.firstName,x.lastName,Ce]),(0,a.useEffect)(()=>{!Oe||!Ke||Ke.setCardFieldOrder?.(re??null,le==null&&!z)},[Oe,Ke,re,le,z]),(0,a.useEffect)(()=>{(Ne==="expanding"||Ne==="collapsing"||Ne==="apm-expanding"||Ne==="apm-collapsing")&&Ce(null)},[Ne,Ce]);let Ln=(0,a.useCallback)((l,F,$)=>{c?.($t(l,F,$))},[c]),_r=(0,a.useCallback)((l,F,$)=>{let Ie=$?.popupBlocked??ur(F),W=hl(l,Ie),Be=Sr($?.code)??nr(F)??"external_payment_method_failed",je=new u.FloPayError(W,"api_error",{code:"external_payment_method_failed",param:l});it(null),K==="buttons"&&(kt("buttons"),Bn(null)),Ce(W),d?.(je),console.error("[FloPay] External payment method failed:",{method:l,code:Be,popupBlocked:Ie})},[K,d,Ce]);(0,a.useEffect)(()=>{if(!Oe||!e){yn(null);return}let l=Ra(A?.vault);if(l){yn(l);return}if(!ut){yn(null);return}yn(null);let F=!0;return new mr.PaymentAPI(y).getVaultCapture(e,t).then($=>{if(!F)return;let Ie=Ra($);Ie?yn(Ie):Ce("Failed to load the secure card form.")}).catch($=>{F&&Ce($ instanceof Error?$.message:"Failed to load the secure card form.")}),()=>{F=!1}},[Oe,ut,Hn,e,A?.vault?.html,A?.vault?.messageToken,A?.vault?.expectedOrigin,y,t,Ce]);let Wn=(0,a.useRef)({onComplete:i,onError:d,updateError:Ce,emitDecline:Ln,resolvedAccount:x,avsConfig:le,avsCheckProp:_e,sessionId:e,nonce:t,baseUrl:y,captureMethod:A?.captureMethod,paymentId:A?.paymentId,authorizationExpiresAt:A?.authorizationExpiresAt});Wn.current={onComplete:i,onError:d,updateError:Ce,emitDecline:Ln,resolvedAccount:x,avsConfig:le,avsCheckProp:_e,sessionId:e,nonce:t,baseUrl:y,captureMethod:A?.captureMethod,paymentId:A?.paymentId,authorizationExpiresAt:A?.authorizationExpiresAt};let ia=(0,a.useRef)(!1),gs=(0,a.useCallback)(()=>{let{resolvedAccount:l,avsConfig:F,avsCheckProp:$}=Wn.current,Ie=l.email?.trim(),W=(0,u.isValidEmail)(Ie)?Ie:jn.current.trim();if(!(0,u.isValidEmail)(W))return null;let Be=kn(Vn.current),je=l.firstName?.trim()||Be.firstName,It=l.lastName?.trim()||Be.lastName;if(!je&&!It)return null;let Ct=Rt.current||l.country||"US",mt=F?(0,u.isAVSFieldVisible)(F.state,Ct):!1,yt=F?(0,u.isAVSFieldVisible)(F.address_line_1,Ct):!1,Je=F?(0,u.isAVSFieldVisible)(F.postal_code,Ct):!1,en=F?(0,u.isAVSFieldVisible)(F.city,Ct):!1,He=F?(0,u.isAVSFieldVisible)(F.address_line_2,Ct):!1,an=yt&&!mt&&Je?(0,u.getStateFromPostalCode)(Ct,(at.current??"").trim()):null,tn=mt?dn.current:an;return{accountData:{userId:l.userId??"",email:W,firstName:je??"",lastName:It??"",...Je&&at.current?{zip:at.current}:{},...en&&cn.current?{city:cn.current}:{},...tn?{state:tn}:{},...yt&&_t.current?{addressLine1:_t.current}:{},...He&&Qt.current?{addressLine2:Qt.current}:{},country:Ct},...$!==void 0?{avsCheck:$}:{},...F?{avsConfig:{country:(0,u.isAVSFieldVisible)(F.country,Ct),postal_code:Je,address_line_1:yt,address_line_2:He,city:en,state:mt}}:{}}},[]),Wa=(0,a.useRef)(Ge);Wa.current=Ge,(0,a.useEffect)(()=>{Ge||U!==Ki||Wn.current.updateError(null)},[Ge,U]),(0,a.useEffect)(()=>{!Oe||!Ke||Ke.setSubmitGate?.(tt||Ge||lt||Lt)},[Oe,Ke,tt,Ge,lt,Lt]),(0,a.useEffect)(()=>{if(!Oe||!Ke)return;ia.current=!1;let l=!1,F=Ke.on("submitting",()=>{Kn(!0),N.current&&clearTimeout(N.current),M.current="validation-window",N.current=setTimeout(()=>{N.current=null,M.current==="validation-window"&&(M.current="processing")},ul),it("processing");let{baseUrl:je,sessionId:It,nonce:Ct,updateError:mt,onError:yt}=Wn.current;if(!It||!Ct)return;let Je=gs();if(!Je){mt("Enter a valid email address."),M.current="idle",it(null);return}new mr.PaymentAPI(je).patchAccountSnapshot(It,Ct,Je,{telemetryMode:"best_effort"}).catch(en=>{if(!pl(en))return;let He=en instanceof Error?en.message:"Please check your billing address and try again.";mt(He),M.current="idle",it(null),yt?.(en instanceof u.FloPayError?en:new u.FloPayError(He,"api_error"))})}),$=Ke.on("complete",async je=>{if(Ur(je.sessionId??Wn.current.sessionId),M.current="terminal",it("success"),await new Promise(mt=>setTimeout(mt,1200)),ia.current)return;ia.current=!0;let It=Wn.current,Ct=(0,u.isAuthorizationOnlySession)(It)||je.outcome==="authorized";Wn.current.onComplete?.(Ct?{status:"authorized",paymentIntentId:je.intentId,paymentId:je.paymentId??It.paymentId,sessionId:je.sessionId??It.sessionId,authorizationExpiresAt:je.authorizationExpiresAt??It.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",paymentIntentId:je.intentId,checkoutMethod:"card"})}),Ie=Ke.on("decline",async je=>{let{updateError:It,emitDecline:Ct}=Wn.current,mt=je.message??"Your payment was declined. Please try another card or contact your bank.";M.current="terminal",It(mt),it("error");let yt=je.failureOutcome??(0,u.normalizeCheckoutFailureOutcome)(je.declineReason)??"authorization_declined";Ct("card",mt,{code:yt,declineCode:yt}),await new Promise(Je=>setTimeout(Je,1500)),!l&&(M.current="idle",it(null))}),W=Ke.on("error",async je=>{let{updateError:It,onError:Ct}=Wn.current,mt=je.message??"There was a problem processing your payment. Please try again.";M.current="terminal",It(mt),it("error"),Ct?.(new u.FloPayError(mt,"api_error",{code:je.failureOutcome??"capture_failed"})),await new Promise(yt=>setTimeout(yt,1500)),!l&&(M.current="idle",it(null))}),Be=Ke.on("blocked",()=>{if(!Wa.current){Kn(!0);return}So(),Wn.current.updateError(Ki)});return()=>{l=!0,N.current&&(clearTimeout(N.current),N.current=null),M.current="idle",F(),$(),Ie(),W(),Be()}},[Oe,Ke,So]);let Gn=!!L?.clientId,Yr=Array.isArray(S),wo=Yr&&S.length>0,hs=Yr&&S.includes("paypal"),{expressMethods:ko,paymentElementMethods:Wr}=(0,a.useMemo)(()=>(0,u.partitionStripeMethods)(S,{excludePaypal:Gn}),[S,Gn]),Ga=Gn||!!ct,bs=(0,a.useMemo)(()=>Ga?ko.filter(l=>l!=="paypal"):ko,[ko,Ga]),vs=(0,a.useMemo)(()=>{let l=[];return H&&l.push("apple_pay"),de&&l.push("google_pay"),l},[H,de]),Io=Yr?bs:vs,Ps=V&&Io.length>0,sa=Cn?Ve:T,Eo=(0,a.useMemo)(()=>{let l=sa?.trim().toUpperCase();return l?me?Wr.filter(F=>{let $=me[F];return!$||$.length===0||$.includes(l)}):(0,u.filterStripeMethodsByCountry)(Wr,sa):Wr},[Wr,sa,me]),la=(0,a.useMemo)(()=>({mode:"payment",amount:Kr,currency:xe.toLowerCase(),paymentMethodCreation:"manual",appearance:Va}),[Kr,xe,Va]),[Ja,Xa]=(0,a.useState)("loading"),[Za,Qa]=(0,a.useState)("loading"),[ei,ti]=(0,a.useState)("loading"),[Cs,ca]=(0,a.useState)(!1),[ni,da]=(0,a.useState)("loading"),[Ro,Ss]=(0,a.useState)();(0,a.useEffect)(()=>{Ss($i())},[]);let ri=he&&(Gn||(Yr?hs:Ro===!1)),oi=V&&Ps,Gr=!G&&ri&&Gn,ai=ni==="retrying"||ni==="exhausted",Jr=!G&&ri&&!!gn&&(!Gn||ai),Xr=!G&&oi&&!!ke,Zr=!G&&V&&wo&&Eo.length>0&&!!ke,ws=Gr&&!ai?Cs:Jr&&Gi(Ja),ks=Xr&&Gi(Za),Is=Zr&&ei!=="load_error",ii=l=>l==="loading"||l==="ready",si=Gr||Jr&&ii(Ja)||Xr&&ii(Za)||Zr&&ei!=="load_error",_o=(0,a.useRef)(!1);(0,a.useEffect)(()=>{if(!_o.current){if(!V&&!he){_o.current=!0;let l=new u.FloPayError("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");d?.(l),Ce(l.message)}else if(!V&&he&&!Gn&&!gn){_o.current=!0;let l=new u.FloPayError("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");d?.(l),Ce(l.message)}else if(Ro!==void 0&&!G&&!un&&!si){_o.current=!0;let l=new u.FloPayError("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?.(l),Ce(l.message)}}},[V,he,Gn,gn,Ro,G,un,si,d,Ce]);let li=(0,a.useRef)(!1);(0,a.useEffect)(()=>{if(li.current||!wo)return;let l=[];H!==!0&&l.push("showApplePay"),de!==!0&&l.push("showGooglePay"),l.length!==0&&(li.current=!0,console.warn(`[FloPay] ${l.join(" / ")} ${l.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.`))},[wo,H,de]);let ci=(0,a.useCallback)((l,F)=>st.applyInlineSessionPatch?st.applyInlineSessionPatch(l).then($=>({error:null,sessionId:$.sessionId||e,nonce:$.session?.clientSecret||t})).catch($=>{let Ie=Wi(F,$);return Ce(Ie.message),d?.(Ie),{error:Ie,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[st.applyInlineSessionPatch,t,d,e,Ce]),On=(0,a.useCallback)(async l=>{if(!O)return{proceed:!0};try{let F=await O({method:l,sessionId:e||void 0,createSession:st.inlineSessionDraft});if(F===!1)return{proceed:!1};if(F&&typeof F=="object"){F.account&&$n(Ie=>({...Ie??{},...F.account}));let $=await ci(F,l);return $.error?{proceed:!1,accountPatch:F.account}:{proceed:!0,accountPatch:F.account,sessionId:$.sessionId,nonce:$.nonce}}return{proceed:!0}}catch(F){let $=Wi(l,F);return Ce($.message),d?.($),{proceed:!1}}},[ci,st.inlineSessionDraft,O,d,e,Ce]),di=(0,a.useCallback)(async(l,F)=>{if(Ht.current)return;Ht.current=!0,Mt(!0),it("processing"),Ce(null);let $=F?.sessionId??e,Ie=F?.nonce??t,W=va(x,F?.accountPatch),Be=F?.completionPaymentMethodId??ao(l),je=l.originalPaymentMethodId?{...l,originalPaymentMethodId:void 0}:l,It=l.gateway==="stripe"?"stripe":l.gateway==="paypal"||l.isPaypal?"paypal":void 0,Ct=()=>{ot?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"process_payment",provider:It})};try{let yt=await new mr.PaymentAPI(y).processPayment(W.userId??"",{sessionId:$,nonce:Ie,tokenizedData:je,accountData:{userId:W.userId??"",email:W.email??"",firstName:W.firstName??"",lastName:W.lastName??"",...le?(()=>{let He=Rt.current,an=(0,u.isAVSFieldVisible)(le.state,He),tn=(0,u.isAVSFieldVisible)(le.address_line_1,He),Kt=(0,u.isAVSFieldVisible)(le.postal_code,He),no=tn&&!an&&Kt?(0,u.getStateFromPostalCode)(He,(at.current??"").trim()):null,ro=an?dn.current:no;return{country:He,...Kt&&at.current?{zip:at.current}:{},...(0,u.isAVSFieldVisible)(le.city,He)&&cn.current?{city:cn.current}:{},...ro?{state:ro}:{},...tn&&_t.current?{addressLine1:_t.current}:{},...(0,u.isAVSFieldVisible)(le.address_line_2,He)&&Qt.current?{addressLine2:Qt.current}:{}}})():{}},chv:f,avsCheck:_e??!1,checkoutType:ie,checkoutLayout:ae,avsConfig:le?{country:(0,u.isAVSFieldVisible)(le.country,Rt.current),postal_code:(0,u.isAVSFieldVisible)(le.postal_code,Rt.current),address_line_1:(0,u.isAVSFieldVisible)(le.address_line_1,Rt.current),address_line_2:(0,u.isAVSFieldVisible)(le.address_line_2,Rt.current),city:(0,u.isAVSFieldVisible)(le.city,Rt.current),state:(0,u.isAVSFieldVisible)(le.state,Rt.current)}:void 0});if(yt.ok){let He=yt.status===204?null:await yt.json().catch(()=>null),an=(0,u.isAuthorizationOnlySession)(A)||He?.status==="authorized";Ur($),it("success"),ce(null),await new Promise(tn=>setTimeout(tn,1200)),i?.(an?{status:"authorized",...typeof He?.paymentId=="string"?{paymentId:He.paymentId}:A?.paymentId?{paymentId:A.paymentId}:{},sessionId:typeof He?.sessionId=="string"?He.sessionId:$,...typeof He?.authorizationExpiresAt=="string"?{authorizationExpiresAt:He.authorizationExpiresAt}:A?.authorizationExpiresAt?{authorizationExpiresAt:A.authorizationExpiresAt}:{},paymentIntentId:l.threeDSecureActionResultTokenId,paymentMethodId:Be,checkoutMethod:l.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:l.threeDSecureActionResultTokenId,paymentMethodId:Be,checkoutMethod:l.isPaypal?"paypal":"card"});return}let Je=await yt.json().catch(()=>null);if(Je?.type==="paypal_redirect_required"){let He=Je.threeDSecureToken,an=Je.paymentMethodId||l.id||"";if(!ve||!He){it("error"),Ce("PayPal authorization required but no token provided.");return}try{let tn=ct?.getRawProvider();if(!tn){Ce("PayPal is not available.");return}let Kt={return_url:window.location.href};an&&(Kt.payment_method=an);let{error:no}=await tn.confirmPayment({clientSecret:He,confirmParams:Kt,redirect:"if_required"});if(no){it("error");let ro=no.message??"PayPal payment failed.";Ce(ro),Ln("paypal",ro,{code:no.code})}}catch(tn){it("error"),Ce(tn instanceof Error?tn.message:"PayPal authorization failed.")}return}if(Je?.type==="paypal_direct_required"){let He=Je.orderId;if(!He){it("error"),Ce("PayPal retry required but no order id provided.");return}let an=Ye.current?.attempts??0;if(an>=2){it("error"),Ce("PayPal payment could not be completed after multiple attempts."),Ln("paypal","paypal_direct_required retry limit exceeded");return}ca(!1),da("loading"),ce({orderId:He,attempts:an+1}),it(null);return}(0,u.classifyPaymentRejection)(yt.status,Je)||Ct(),it("error");let en=Je?.message??"Payment failed. Please try again.";Ce(en),Ln(l.isPaypal?"paypal":"card",en,{code:Je?.code??Je?.gatewayErrorCode,declineCode:Je?.declineCode??Je?.gatewayDeclineReason}),await new Promise(He=>setTimeout(He,1500))}catch(mt){Qi(mt)||Ct(),it("error"),Ce(mt instanceof Error?mt.message:"An unexpected error occurred"),await new Promise(yt=>setTimeout(yt,1500))}finally{Mt(!1),it(null),Ht.current=!1}},[y,e,t,x,Me,f,ve,ct,A,i,d,Ce,Ln,ot]),wn=(0,a.useCallback)((l,F)=>{v?v(l):di(l,F)},[v,di]),ui=(0,a.useRef)(!1);(0,a.useEffect)(()=>{if(typeof window>"u"||ui.current)return;let l=new URLSearchParams(window.location.search),F=l.get("payment_intent"),$=l.get("payment_intent_client_secret"),Ie=l.get("redirect_status");if(!F||!$)return;let W=yt=>{let Je=localStorage.getItem(yt);if(!Je)return null;try{return JSON.parse(Je)}catch{return localStorage.removeItem(yt),null}},Be=W(Jn)??W(Hi),je;if(Be?.clientSecret){if(Be.clientSecret!==$)return;je={...Be.accountPatch?{accountPatch:Be.accountPatch}:{},...Be.sessionId?{sessionId:Be.sessionId}:{},...Be.nonce?{nonce:Be.nonce}:{}}}else if(Be?.sessionId&&Be.sessionId!==e)return;ui.current=!0,localStorage.removeItem(Jn),localStorage.removeItem(Hi);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=Be?.paymentMethodType??Be?.tokenType??"card",mt="card";(async()=>{let yt=ve?.getRawProvider();if(!yt){let Kt="Payment is not available \u2014 please refresh and try again.";Ce(Kt),Ln(mt,Kt);return}if(Ie==="failed"){let Kt="Payment was declined. Please try again.";Ce(Kt),Ln(mt,Kt);return}let{paymentIntent:Je,error:en}=await yt.retrievePaymentIntent($);if(en){let Kt=en.message??"Failed to retrieve payment status.";Ce(Kt),Ln(mt,Kt,{code:en.code});return}let He=Je?.status,an=No(He);if(!Je||!an){let Kt=He==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";Ce(Kt),Ln(mt,Kt,{code:He??"missing_payment_intent"});return}let tn=typeof Je.payment_method=="string"?Je.payment_method:Je.payment_method?.id;wn({id:tn??Be?.paymentMethodId??Be?.tokenId??Je.id,type:"card",threeDSecureActionResultTokenId:Je.id,gateway:Be?.gateway??"stripe",paymentMethodType:Ct},je)})()},[e,wn,ve,Ce,Ln]);let ua=(0,a.useCallback)(l=>{l.preventDefault()},[]);if(!(ve!==null))return(0,s.jsx)("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let Qr=K==="buttons",on=Y?.variables,Es=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),pa=on?.colorBackground,Rs=pa&&!Es.has(pa)?pa:void 0,fr=P.cardInputBorder??(Qr?"#e5e7eb":"#A4A4FF"),ma=on?.colorDanger??"#dc2626",gr=l=>cr&&l?ma:fr,xo=(pn.malformed||pn.empty)&&(Sn||cr),_s=xo?ma:gr(Ut.zip),ya=P.cardFormContainer?.backgroundColor??Rs??(Qr?"white":"#EDEDFF"),hr=P.cardInputBackground??on?.colorBackground??"white",fa=Ar(Ee),pi=Ar(Re),xr=P.nameInput,mi=P.cardInputFontSize??Cl(xr?.fontSize)??on?.fontSizeBase??"16px",yi=typeof xr?.fontFamily=="string"?xr.fontFamily:on?.fontFamily??"Poppins, sans-serif",fi=Ea(xr?.fontWeight)??400,xs=P.cardInputColor??(typeof xr?.color=="string"?xr.color:void 0)??on?.colorText??"#262833",Ts=P.cardInputPlaceholderColor??"#9ca3af",Pt=on?.borderRadius??"8px",br=on?.borderRadius??P.cardButton?.borderRadius??Pt,vr=on?.colorPrimary??"#4A49FF",As=on?.colorPrimaryHover??Vr(vr,.12),eo=on?.colorText??"#262833",Tr={fontSize:mi,fontFamily:yi,fontWeight:fi,color:xs,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},Ms={"--flopay-input-placeholder-color":Ts,"--flopay-input-font-size":mi,"--flopay-input-font-family":yi,"--flopay-input-font-weight":String(fi)},to=P.cardFormContainer??{},ga=to.padding??(Qr?"0":"1rem"),ha=to.borderRadius??Pt,Bs=Ke&&mn?(0,s.jsx)(jr,{capture:Ke,html:mn.html,messageToken:mn.messageToken,expectedOrigin:mn.expectedOrigin,theme:pt,onReady:()=>{if(!z&&!le||typeof document>"u")return;let l=()=>{(document.querySelector('[data-testid="flopay-vault-identity-fields"]')??document.querySelector('[data-testid="flopay-avs-fields"]'))?.querySelector("input:not([disabled]), select:not([disabled])")?.focus()};l();let F=0,$=window.setInterval(()=>{F+=1;let Ie=document.activeElement;!!Ie&&Ie.tagName==="IFRAME"&&Ie.id==="flopay_vault_form_iframe"?(l(),window.clearInterval($)):F>=50&&window.clearInterval($)},100)},onError:l=>Ce(l),onValidation:l=>{let F=M.current;(F==="idle"||F==="validation-window")&&(Ce(l),l&&M.current==="validation-window"&&(N.current&&(clearTimeout(N.current),N.current=null),M.current="idle",it(null)))}}):(0,s.jsx)("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"}),gi=(0,s.jsxs)("div",{onFocusCapture:l=>{["INPUT","SELECT","TEXTAREA","IFRAME"].includes(l.target.tagName)&&Dn()},style:{backgroundColor:ya,borderRadius:ha,...to,padding:ga,...Ms,display:"flex",flexDirection:"column"},children:[(0,s.jsx)("style",{children:`
30
+ `,Go=44;function Ma(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 fl={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"},ts={width:"100%",minHeight:Go,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 gl(e){switch(e){case"paypal":return"PayPal";case"apple_pay":return"Apple Pay";case"google_pay":return"Google Pay";default:return"Card"}}function Yi(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function xa(e){return e==="paypal"?"PayPal":(0,u.getStripeMethodDisplayName)(e)}function hl(e,t){let n=`We couldn't open ${xa(e)}. Try again or choose another payment method.`;return t?`${n} Allow pop-ups for this site, then try again.`:n}function ns(e){let t=(0,a.useRef)(0),n=(0,a.useRef)(null),r=(0,a.useRef)(null),o=(0,a.useCallback)((p=r.current)=>{let C=p;C?.timer&&(clearTimeout(C.timer),C.timer=null)},[]),i=(0,a.useCallback)((p,C)=>{typeof document<"u"&&document.visibilityState!=="visible"||(o(p),p.timer=setTimeout(()=>{p.timer=null,r.current?.generation===p.generation&&(r.current=null,n.current=p.generation,e(p.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}))},C))},[o,e]),d=(0,a.useCallback)(p=>{p.yieldedControl&&i(p,600)},[i]),c=(0,a.useCallback)(p=>{o();let C=t.current+1;t.current=C,n.current=null;let he={generation:C,method:p,timer:null,yieldedControl:!1};return r.current=he,C},[o]),v=(0,a.useCallback)(p=>{let C=r.current;return typeof p=="number"&&C?.generation!==p?!1:(o(C),r.current=null,(typeof p!="number"||n.current===p)&&(n.current=null),!0)},[o]),g=(0,a.useCallback)(p=>{let C=r.current,he=p??C?.generation??t.current;(!p||C?.generation===p)&&(o(C),r.current=null),n.current=he},[o]),h=(0,a.useCallback)(p=>n.current===(p??t.current),[]),f=(0,a.useCallback)(p=>r.current?.generation===p&&n.current!==p,[]),N=(0,a.useCallback)(()=>{let p=r.current;p&&d(p)},[d]),B=(0,a.useCallback)(()=>{let p=r.current;p&&(p.yieldedControl=!0,o(p))},[o]);return(0,a.useEffect)(()=>{let p=()=>{document.visibilityState==="visible"?N():B()},C=()=>{B()};return document.addEventListener("visibilitychange",p),window.addEventListener("blur",C),window.addEventListener("focus",N),()=>{document.removeEventListener("visibilitychange",p),window.removeEventListener("blur",C),window.removeEventListener("focus",N),o()}},[o,B,N]),{startAttempt:c,finishAttempt:v,invalidateAttempt:g,isAttemptInvalidated:h,isAttemptCurrent:f}}function bl(e){let t=(0,u.getPostalCodeExample)(e);return`Enter a valid ${(0,u.getPostalCodeLabel)(e)}${t?` (e.g. ${t})`:""}`}function vl(e,t,n){let r=(0,u.isPostalCodeSupported)(e),o=t.trim(),i=n&&r,d=i&&!o,c=i&&!!o&&!(0,u.isValidPostalCode)(e,o);return{visible:n,supported:r,required:i,empty:d,malformed:c}}function Pl(e,t){let n=e.trim(),r=t&&!n,o=t&&!!n&&!(0,u.isValidEmail)(n);return{required:t,empty:r,malformed:o,value:n}}function Wi(e,t){return t instanceof u.FloPayError?t:new u.FloPayError(t instanceof Error?t.message:`${gl(e)} before-click hook failed.`,"validation_error")}function _a(){return(0,s.jsx)("style",{children:yl})}function Cl(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 os({state:e,placeholderTestId:t,borderRadius:n=8,children:r}){return e==="unavailable"||e==="load_error"?null:(0,s.jsxs)("div",{style:{position:"relative",minHeight:44},children:[(0,s.jsx)("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"}}),(0,s.jsx)("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 Gi(e){return e!=="unavailable"&&e!=="load_error"}function Zo(e){return(0,s.jsx)(wl,{...e})}function Ji({sessionId:e,nonce:t,email:n,billingApiUrl:r,onTokenizedBody:o,onErrorChange:i,isProcessing:d=!1,onButtonClick:c,onDecline:v,onTechnicalFailure:g,runBeforeButtonClick:h,billingName:f,onBuyerIdentityReady:N,onLoadStateChange:B,placeholderBorderRadius:p}){let C=rr(),{emitInstrument:he}=(0,a.useContext)(In),V=(0,Et.useStripe)(),S=(0,Et.useElements)(),[me,H]=(0,a.useState)("loading");(0,a.useEffect)(()=>{B?.(me)},[me,B]);let[de,K]=(0,a.useState)(!1),be=!(0,u.isValidEmail)(n?.trim())||!f?.trim(),{request:$e,collect:we,finish:gt}=Dr(),Fe=(0,a.useRef)(!1),Ee=(0,a.useRef)(null),Re=(0,a.useRef)(null),[oe,ne]=(0,a.useState)(0),[O,ue]=(0,a.useState)(!1),We=(0,a.useRef)(!1),re=(0,a.useRef)(new Map),{startAttempt:Ae,finishAttempt:Z,invalidateAttempt:T,isAttemptInvalidated:j,isAttemptCurrent:Me}=ns((ie,ae,X)=>{g?.(ie,ae,{...X,popupBlocked:X?.popupBlocked??ur(ae)}),ue(!0),ne(xe=>xe+1)});(0,a.useEffect)(()=>{O&&Re.current?.focus()},[O,oe]);let ye=(0,a.useCallback)(()=>{ne(ie=>ie+1)},[]),Q=(0,a.useCallback)((ie,ae,X)=>{T(X),g?.("paypal",ie,{code:ae,popupBlocked:ur(ie)}),ue(!0),ye()},[T,g,ye]),Ne=(0,a.useCallback)(()=>{window.setTimeout(()=>{(Ee.current?.querySelector("iframe")??Ee.current)?.focus()},0)},[]);(0,a.useEffect)(()=>{We.current&&(We.current=!1,Ne())},[Ne,oe]);let Qe=(0,a.useCallback)(()=>{ue(!1),i?.(null),Ne()},[Ne,i]);(0,a.useEffect)(()=>{if(!V||Fe.current)return;let ie=new URLSearchParams(window.location.search),ae=ie.get("payment_intent"),X=ie.get("payment_intent_client_secret"),xe=ie.get("redirect_status");if(!ae||!X)return;Fe.current=!0;let Le;try{let ee=localStorage.getItem(fo);if(ee){let A=JSON.parse(ee);A.clientSecret===X&&(Le={...A.accountPatch?{accountPatch:A.accountPatch}:{},...A.sessionId?{sessionId:A.sessionId}:{},...A.nonce?{nonce:A.nonce}:{}})}}catch{}try{localStorage.removeItem(fo)}catch{}let L=new URL(window.location.href);L.searchParams.delete("payment_intent"),L.searchParams.delete("payment_intent_client_secret"),L.searchParams.delete("redirect_status"),window.history.replaceState({},"",L.toString()),(async()=>{try{if(K(!0),xe==="failed"){let E="PayPal payment was declined. Please try again.";i?.(E),v?.(jt("paypal",E));return}let{paymentIntent:ee,error:A}=await V.retrievePaymentIntent(X);if(A){i?.(A.message??"Failed to retrieve PayPal payment status.");return}if(ee&&(ee.status==="requires_capture"||ee.status==="succeeded")){let E=typeof ee.payment_method=="string"?ee.payment_method:ee.payment_method?.id;o({id:E??ee.id,type:"card",threeDSecureActionResultTokenId:ee.id,isPaypal:!0},Le)}else{let E="PayPal payment was not completed. Please try again.";i?.(E),v?.(jt("paypal",E))}}catch(ee){i?.(ee instanceof Error?ee.message:"Failed to complete PayPal payment.")}finally{K(!1)}})()},[V,o,i,v]);let Ze=(0,a.useCallback)(async ie=>{if(d||de){ie.reject();return}let ae=h?await h("paypal"):{proceed:!0};if(!ae.proceed){re.current.delete(oe),ie.reject();return}let X=Ae("paypal");re.current.set(oe,{generation:X,accountPatch:ae.accountPatch,sessionId:ae.sessionId,nonce:ae.nonce}),ue(!1),c?.("paypal"),ie.resolve()},[re,d,c,h,Ae,de,oe]),_e=(0,a.useCallback)(async ie=>{if(!V||!S)return;let ae=re.current.get(oe);if(ae&&!Me(ae.generation)){re.current.delete(oe);return}if(!ae&&j()||ae&&!Z(ae.generation))return;ae||Z();let X=ae??null;if(re.current.delete(oe),!X&&h){let E=await h("paypal");if(!E.proceed){ie.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}X={accountPatch:E.accountPatch,sessionId:E.sessionId,nonce:E.nonce}}let xe=X?.sessionId??e,Le=X?.nonce??t,L=await es({event:ie,prepared:X,email:n,billingName:f,methodLabel:"PayPal",collect:we});if(!L){ie.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let ee=L.email,A={...X?.accountPatch,...L};try{if(K(!0),i?.(null),!xe||!(0,u.isValidEmail)(ee))throw new Error("Missing sessionId or email for PayPal payment");await N?.(L);let E=V.createPaymentMethod,{error:rt,paymentMethod:St}=await E({type:"paypal"});if(rt){Q(rt,"stripe_paypal_create_payment_method_failed",ae?.generation),ie.paymentFailed({reason:"fail"});return}let ve=await Jo(r,he,xe,Le??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:St?.id??null,intentKind:"payment"});if(ve.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let ct=ve.clientSecret,st={return_url:window.location.href};if(St?.id&&(st.payment_method=St.id),typeof window<"u")try{localStorage.setItem(fo,JSON.stringify({clientSecret:ct,sessionId:xe,nonce:Le,accountPatch:A}))}catch{}let{error:ot,paymentIntent:Ge}=await V.confirmPayment({clientSecret:ct,confirmParams:st,redirect:"if_required"});if(ot){if(typeof window<"u")try{localStorage.removeItem(fo)}catch{}if(so(ot)){let G=ot.message??"Your payment was declined.";i?.(G),v?.(jt("paypal",G,{code:nr(ot),declineCode:Lr(ot)})),await Xo({billingApiUrl:r,sessionId:xe,nonce:Le,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:nr(ot)??"provider_declined"}})}else Q(ot,"stripe_paypal_confirm_failed",ae?.generation);return}if(typeof window<"u")try{localStorage.removeItem(fo)}catch{}let b=typeof Ge?.payment_method=="string"?Ge.payment_method:Ge?.payment_method?.id;o({id:b??Ge?.id,type:"card",threeDSecureActionResultTokenId:Ge?.id,isPaypal:!0},{accountPatch:A,sessionId:xe,nonce:Le});return}catch(E){Q(E,"stripe_paypal_failed",ae?.generation)}finally{K(!1)}},[V,S,e,t,n,f,we,N,r,he,o,i,v,h,Q,Z,Me,j,oe]);return(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(os,{state:me,placeholderTestId:"flopay-paypal-placeholder",borderRadius:p,children:(0,s.jsxs)("div",{ref:Ee,tabIndex:-1,"data-testid":"flopay-paypal-focus-target",role:"group","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[O&&(0,s.jsx)("button",{ref:Re,type:"button","data-testid":"flopay-paypal-retry-button",onClick:Qe,style:ts,children:"Try PayPal again"}),$e&&(0,s.jsx)(Cr,{identity:$e.identity,methodLabel:$e.methodLabel,onComplete:gt,onCancel:()=>gt(null)},$e.id),(0,s.jsx)("div",{style:{display:$e?"none":void 0},children:(0,s.jsx)(Et.ExpressCheckoutElement,{onReady:ie=>H(rs(ie,["paypal"])),onLoadError:()=>{H("load_error"),Aa(Vt(C),"paypal","paypal")},onClick:Ze,onConfirm:_e,onCancel:()=>{let ie=re.current.get(oe);re.current.delete(oe),Vt(C)?.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),T(ie?.generation),ue(!1),We.current=!0,ye()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:be,emailRequired:be,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},oe)})]})}),de&&(0,s.jsx)(Rn,{status:"processing"})]})}function Xi({sessionId:e,nonce:t,email:n,billingApiUrl:r,intentKind:o,expressMethods:i,onTokenizedBody:d,onErrorChange:c,onButtonClick:v,onDecline:g,onTechnicalFailure:h,runBeforeButtonClick:f,billingName:N,onBuyerIdentityReady:B,onLoadStateChange:p,placeholderBorderRadius:C}){let he=rr(),{emitInstrument:V}=(0,a.useContext)(In),S=(0,Et.useStripe)(),me=(0,Et.useElements)(),[H,de]=(0,a.useState)("loading");(0,a.useEffect)(()=>{p?.(H)},[H,p]);let[K,be]=(0,a.useState)(!1),$e=!(0,u.isValidEmail)(n?.trim())||!N?.trim(),{request:we,collect:gt,finish:Fe}=Dr(),Ee=(0,a.useRef)(null),Re=(0,a.useRef)(null),[oe,ne]=(0,a.useState)(0),[O,ue]=(0,a.useState)(!1),[We,re]=(0,a.useState)("google_pay"),Ae=(0,a.useRef)(!1),Z=(0,a.useRef)("google_pay"),T=(0,a.useRef)("google_pay"),j=(0,a.useRef)(new Map),{startAttempt:Me,finishAttempt:ye,invalidateAttempt:Q,isAttemptInvalidated:Ne,isAttemptCurrent:Qe}=ns((L,ee,A)=>{h?.(L,ee,{...A,popupBlocked:A?.popupBlocked??ur(ee)}),re(L),ue(!0),ne(E=>E+1)});(0,a.useEffect)(()=>{O&&Re.current?.focus()},[O,oe]);let Ze=(0,a.useCallback)(()=>{ne(L=>L+1)},[]),_e=(0,a.useCallback)((L,ee,A,E)=>{Q(E),h?.(L,ee,{code:A,popupBlocked:ur(ee)}),re(L),ue(!0),Ze()},[Q,h,Ze]),ie=(0,a.useCallback)(()=>{window.setTimeout(()=>{(Ee.current?.querySelector("iframe")??Ee.current)?.focus()},0)},[]);(0,a.useEffect)(()=>{Ae.current&&(Ae.current=!1,ie())},[ie,oe]);let ae=(0,a.useCallback)(()=>{ue(!1),c?.(null),ie()},[ie,c]),X=(0,a.useCallback)(async L=>{if(!S||!me)return;let ee=j.current.get(oe);if(ee&&!Qe(ee.generation)){j.current.delete(oe);return}if(!ee&&Ne()||ee&&!ye(ee.generation))return;ee||ye();let A=L.expressPaymentType??ee?.method??Z.current,E=ee??null;j.current.delete(oe);let rt=Yi(A);if(!E&&f){let b=await f(rt);if(!b.proceed){L.paymentFailed({reason:"fail",message:"Wallet checkout was cancelled."});return}E={accountPatch:b.accountPatch,sessionId:b.sessionId,nonce:b.nonce}}let St=rt,ve=E?.sessionId??e,ct=E?.nonce??t,st=await es({event:L,prepared:E,email:n,billingName:N,methodLabel:xa(A),collect:gt});if(!st){L.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let ot=st.email,Ge={...E?.accountPatch,...st};try{if(be(!0),c?.(null),!(0,u.isValidEmail)(ot))throw new Error("Missing sessionId or email for wallet payment");await B?.(st);let{error:b}=await me.submit();if(b){_e(A,b,"stripe_wallet_submit_failed",ee?.generation);return}let{error:G,paymentMethod:et}=await S.createPaymentMethod({elements:me});if(G||!et){_e(A,G??new Error("Failed to create payment method."),"stripe_wallet_create_payment_method_failed",ee?.generation);return}if(!ve)throw new Error("Missing sessionId or email for wallet payment");let dt=await Jo(r,V,ve,ct??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:A??rt,paymentMethodId:et.id,intentKind:o});if(dt.provider!=="stripe")throw new Error("Invalid provider returned for wallet intent");let Mt=dt.clientSecret,{error:Bt,intentId:se}=(0,u.isSetupIntentClientSecret)(Mt)?await S.confirmCardSetup(Mt,{payment_method:et.id}).then(Ve=>({error:Ve.error,intentId:Ve.setupIntent?.id})):await S.confirmCardPayment(Mt,{payment_method:et.id}).then(Ve=>({error:Ve.error,intentId:Ve.paymentIntent?.id}));if(Bt){if(so(Bt)){let Ve=Bt.message??"Your payment was declined.";c?.(Ve),g?.(jt(St,Ve,{code:nr(Bt),declineCode:Lr(Bt)})),await Xo({billingApiUrl:r,sessionId:ve,nonce:ct,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:A??rt,providerDeclineReason:nr(Bt)??"provider_declined"}})}else _e(A,Bt,"stripe_wallet_confirm_failed",ee?.generation);return}d({id:et.id,type:"card",threeDSecureActionResultTokenId:se},{accountPatch:Ge,sessionId:ve,nonce:ct})}catch(b){_e(A,b,"stripe_wallet_failed",ee?.generation)}finally{be(!1)}},[S,me,e,t,n,N,gt,B,r,V,o,d,c,g,f,_e,ye,Qe,Ne,oe]),xe=(0,a.useMemo)(()=>{let L=["applePay","googlePay","paypal","link","amazonPay","klarna"],ee=new Set(["applePay","googlePay"]),A=new Set(i.map(u.stripeExpressMethodToOptionKey)),E={};for(let rt of L)A.has(rt)?E[rt]=ee.has(rt)?"always":"auto":E[rt]="never";return E},[i]),Le=(0,a.useMemo)(()=>i.map(u.stripeExpressMethodToOptionKey),[i]);return(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(os,{state:H,placeholderTestId:"flopay-wallet-placeholder",borderRadius:C,children:(0,s.jsxs)("div",{ref:Ee,tabIndex:-1,"data-testid":"flopay-wallet-focus-target",role:"group","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[O&&(0,s.jsxs)("button",{ref:Re,type:"button","data-testid":"flopay-wallet-retry-button",onClick:ae,style:ts,children:["Try ",xa(We)," again"]}),we&&(0,s.jsx)(Cr,{identity:we.identity,methodLabel:we.methodLabel,onComplete:Fe,onCancel:()=>Fe(null)},we.id),(0,s.jsx)("div",{style:{display:we?"none":void 0},children:(0,s.jsx)(Et.ExpressCheckoutElement,{onReady:L=>{de(rs(L,Le))},onLoadError:L=>{de("load_error"),Aa(Vt(he),"stripe","wallet")},onClick:async L=>{Z.current=L.expressPaymentType,T.current=Yi(L.expressPaymentType);let ee=f?await f(T.current):{proceed:!0};if(!ee.proceed){j.current.delete(oe),L.reject();return}let A=Me(L.expressPaymentType);j.current.set(oe,{generation:A,method:L.expressPaymentType,accountPatch:ee.accountPatch,sessionId:ee.sessionId,nonce:ee.nonce}),ue(!1),v?.(T.current),L.resolve()},onConfirm:X,onCancel:()=>{let L=j.current.get(oe);j.current.delete(oe),Vt(he)?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet"}),Q(L?.generation),ue(!1),Ae.current=!0,Ze()},options:{buttonType:{applePay:"plain",googlePay:"plain"},paymentMethods:xe,emailRequired:$e,billingAddressRequired:$e,layout:{maxColumns:1,overflow:"never"}}},oe)})]})}),K&&(0,s.jsx)(Rn,{status:"processing"})]})}function Sl({method:e,themeId:t,submitting:n=!1,disabled:r=!1,highlighted:o=!1,hasNextStep:i=!1,onClick:d,backgroundColor:c,borderColor:v,textColor:g,borderRadius:h,fontFamily:f}){let N=(0,u.resolveStripeMethodBrandVariant)(e,t),B=ji[e],[p,C]=(0,a.useState)(!1),he=N?.backgroundColor??c??"#ffffff",V=N?.borderColor??v??"#d1d5db",S=N?.textColor??g??"#262833";return(0,s.jsx)("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:Go,padding:"0 1rem",backgroundColor:he,color:S,border:`1px solid ${V}`,borderRadius:h??8,fontSize:"0.95rem",fontWeight:600,fontFamily:f,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?(0,s.jsx)("span",{style:{margin:"0 auto"},children:`Connecting to ${(0,u.getStripeMethodDisplayName)(e)}\u2026`}):(0,s.jsxs)(s.Fragment,{children:[(0,s.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:(0,u.hasVendoredStripeMethodLogo)(e)?8:0},children:[B&&!p?(0,s.jsx)("img",{src:B,alt:"","aria-hidden":"true",onError:()=>C(!0),loading:"lazy",decoding:"async",width:30,height:20,style:{width:30,height:20,flexShrink:0,borderRadius:3,objectFit:"contain",display:"inline-flex"}}):N?.logoSvg?(0,s.jsx)("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:N.logoSvg}}):null,(0,s.jsx)("span",{children:(0,u.getStripeMethodDisplayName)(e)})]}),i&&(0,s.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:S,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:(0,s.jsx)("path",{d:"M9 18l6-6-6-6"})})]})})}function Ta({method:e,sessionId:t,nonce:n,email:r,billingName:o,onBuyerIdentityReady:i,billingApiUrl:d,onTokenizedBody:c,onErrorChange:v,onDecline:g,onCancel:h,runBeforeButtonClick:f,onButtonClick:N,isProcessing:B,submitButtonColor:p,submitButtonBorderRadius:C,submitButtonStyle:he,errorText:V}){let S=rr(),{emitInstrument:me}=(0,a.useContext)(In),H=(0,Et.useStripe)(),de=(0,Et.useElements)(),[K,be]=(0,a.useState)(!1),$e=(0,a.useRef)(!1),[we,gt]=(0,a.useState)(!1),[Fe,Ee]=(0,a.useState)("loading"),[Re,oe]=(0,a.useState)(""),[ne,O]=(0,a.useState)(""),ue=!(0,u.isValidEmail)(r?.trim()),We=!o?.trim(),re=(!ue||(0,u.isValidEmail)(Re.trim()))&&(!We||!!ne.trim()),Ae=(0,a.useCallback)(async()=>{if(!H||!de||B||$e.current||!we)return;$e.current=!0,be(!0);let Z=f?await f("card"):{proceed:!0};if(!Z.proceed){$e.current=!1,be(!1);return}N?.("card");let T=Z.sessionId??t,j=Z.nonce??n,Me=kn(o?.trim()||ne.trim()),ye={email:Z.accountPatch?.email?.trim()||r?.trim()||Re.trim(),firstName:Z.accountPatch?.firstName?.trim()||Me.firstName,lastName:Z.accountPatch?.lastName?.trim()||Me.lastName},Q=ye.email,Ne={...Z.accountPatch,...ye};try{if(v?.(null),!(0,u.isValidEmail)(Q)||!io(ye))throw new Error("A valid email address and full name are required for payment.");await i?.(ye);let Qe=await de.submit();if(Qe.error){v?.(Qe.error.message??"Payment failed.");return}let Ze=await H.createPaymentMethod({elements:de,params:{billing_details:{email:Q,name:[ye.firstName,ye.lastName].filter(Boolean).join(" ")}}});if(Ze.error||!Ze.paymentMethod){v?.(Ze.error?.message??"Failed to create payment method.");return}let _e=Ze.paymentMethod;if(!T||!Q)throw new Error("Missing sessionId or email for payment.");let ie=_e.type||e,ae=await Jo(d,me,T,j??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:ie,paymentMethodId:null,intentKind:"payment"});if(ae.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let X=ae.clientSecret;if(typeof window<"u")try{localStorage.setItem(Jn,JSON.stringify({clientSecret:X,sessionId:T,nonce:j,accountPatch:Ne,paymentMethodId:_e.id,paymentMethodType:_e.type??e,gateway:"stripe"}))}catch{}let{error:xe,paymentIntent:Le}=await H.confirmPayment({clientSecret:X,confirmParams:{return_url:window.location.href,payment_method:_e.id},redirect:"if_required"});if(xe){if(typeof window<"u")try{localStorage.removeItem(Jn)}catch{}let A=xe.message??"Payment failed.";v?.(A),g?.(jt("card",A,{code:xe.code})),await Xo({billingApiUrl:d,sessionId:T,nonce:j,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:xe.code??"provider_declined"}});return}let L=Le?.status;if(!Do(L)){if(typeof window<"u")try{localStorage.removeItem(Jn)}catch{}let A=L==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";v?.(A),g?.(jt("card",A,{code:L??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(Jn)}catch{}let ee=typeof Le?.payment_method=="string"?Le.payment_method:Le?.payment_method?.id;c({id:ee??_e.id,type:"card",threeDSecureActionResultTokenId:Le?.id,gateway:"stripe",paymentMethodType:_e.type??e},{accountPatch:Ne,sessionId:T,nonce:j})}catch(Qe){v?.(Qe instanceof Error?Qe.message:"Payment failed. Please try again.")}finally{$e.current=!1,be(!1)}},[H,de,B,we,f,N,t,n,r,o,Re,ne,i,d,me,e,c,v,g]);return(0,s.jsxs)("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[(ue||We)&&(0,s.jsxs)("div",{"data-testid":"flopay-apm-identity-fields",style:{display:"flex",flexDirection:"column",gap:"0.75rem",marginBottom:"0.75rem"},children:[ue&&(0,s.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",(0,s.jsx)("input",{type:"email",autoComplete:"email",required:!0,value:Re,onChange:Z=>oe(Z.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]}),We&&(0,s.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Full name",(0,s.jsx)("input",{type:"text",autoComplete:"name",required:!0,value:ne,onChange:Z=>O(Z.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]})]}),(0,s.jsx)(Et.PaymentElement,{onReady:()=>Ee("ready"),onLoadError:()=>{Ee("load_error"),Aa(Vt(S),"stripe","apm")},onChange:Z=>{gt(!!Z.complete)},options:{layout:{type:"accordion",defaultCollapsed:!1,radios:"never"},defaultValues:{billingDetails:{...o?.trim()?{name:o.trim()}:{},...(0,u.isValidEmail)(r?.trim())?{email:r?.trim()}:{}}}}}),(0,s.jsx)("button",{type:"button","data-testid":`flopay-stripe-method-pay-${e}`,onClick:()=>{Ae()},disabled:!we||!re||K||B||Fe!=="ready",style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:p,color:"white",border:"none",borderRadius:C,fontSize:"1rem",fontWeight:600,cursor:!we||!re||K||B||Fe!=="ready"?"not-allowed":"pointer",opacity:!we||!re||K||B||Fe!=="ready"?.5:1,transition:"opacity 120ms ease-out",...he??{}},children:K?"Processing\u2026":`Pay with ${(0,u.getStripeMethodDisplayName)(e)}`}),V&&(0,s.jsx)(zr,{margin:"0.75rem 0 0",children:V})]})}function Zi({sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:i,paymentElementMethods:d,stripeInstance:c,paymentElementBaseOptions:v,onTokenizedBody:g,onErrorChange:h,onButtonClick:f,onDecline:N,runBeforeButtonClick:B,onLoadStateChange:p,isProcessing:C=!1,submitButtonColor:he="#4A49FF",submitButtonBorderRadius:V=8,submitButtonStyle:S,buttonAppearance:me,themeId:H,onExpandApm:de,expandedApmMethod:K}){let{emitInstrument:be}=(0,a.useContext)(In),[$e,we]=(0,a.useState)(null),[gt,Fe]=(0,a.useState)(null),Ee=(0,a.useRef)(!1),{request:Re,collect:oe,finish:ne}=Dr();(0,a.useEffect)(()=>{d.length>0&&c?p?.("ready"):c||p?.("loading")},[d.length,c,p]);let O=(0,a.useCallback)(async T=>{if(!c||Ee.current||C)return;Ee.current=!0,Fe(T);let j=B?await B("card"):{proceed:!0};if(!j.proceed){Ee.current=!1,Fe(null);return}f?.("card");let Me=j.sessionId??e,ye=j.nonce??t,Q=kn([j.accountPatch?.firstName,j.accountPatch?.lastName].filter(Boolean).join(" ")||r),Ne={email:j.accountPatch?.email?.trim()||n?.trim(),firstName:j.accountPatch?.firstName?.trim()||Q.firstName,lastName:j.accountPatch?.lastName?.trim()||Q.lastName};if(!(0,u.isValidEmail)(Ne.email)||!io(Ne)){Fe(null);let _e=await oe((0,u.getStripeMethodDisplayName)(T),Ne);if(!_e){Ee.current=!1;return}Ne=_e,Fe(T)}let Qe=Ne.email,Ze={...j.accountPatch,...Ne};try{if(h?.(null),!Me||!(0,u.isValidEmail)(Qe)||!io(Ne))throw new Error("Missing sessionId or email for payment.");await o?.(Ne);let _e=await Jo(i,be,Me,ye??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:T,paymentMethodId:null,intentKind:"payment"});if(_e.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let ie=_e.clientSecret;if(typeof window<"u")try{localStorage.setItem(Jn,JSON.stringify({clientSecret:ie,sessionId:Me,nonce:ye,accountPatch:Ze,paymentMethodType:T,gateway:"stripe"}))}catch{}let{error:ae,paymentIntent:X}=await c.confirmPayment({clientSecret:ie,confirmParams:{return_url:window.location.href,payment_method_data:{type:T,billing_details:{name:[Ne.firstName,Ne.lastName].filter(Boolean).join(" "),...Qe?{email:Qe}:{}}}},redirect:"if_required"});if(ae){if(typeof window<"u")try{localStorage.removeItem(Jn)}catch{}let L=ae.message??"Payment failed.";h?.(L),N?.(jt("card",L,{code:ae.code})),await Xo({billingApiUrl:i,sessionId:Me,nonce:ye,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:T,providerDeclineReason:ae.code??"provider_declined"}});return}let xe=X?.status;if(!Do(xe)){if(typeof window<"u")try{localStorage.removeItem(Jn)}catch{}let L=xe==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";h?.(L),N?.(jt("card",L,{code:xe??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(Jn)}catch{}let Le=typeof X?.payment_method=="string"?X.payment_method:X?.payment_method?.id;g({id:Le??X?.id,type:"card",threeDSecureActionResultTokenId:X?.id,gateway:"stripe",paymentMethodType:T},{accountPatch:Ze,sessionId:Me,nonce:ye})}catch(_e){h?.(_e instanceof Error?_e.message:"Payment failed. Please try again.")}finally{Ee.current=!1,Fe(null)}},[c,C,B,f,e,t,n,oe,i,be,r,o,g,h,N]),[ue,We]=(0,a.useState)(null),re=de?K??null:ue,Ae=(0,a.useCallback)(T=>{Ee.current||C||re&&re!==T||((0,u.needsStripeMethodExplicitConfirm)(T)?de?de(T):We(T):O(T))},[re,C,O,de]),Z=(0,a.useMemo)(()=>ue?{...v,paymentMethodTypes:[ue]}:null,[ue,v]);return(0,s.jsx)("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:Re?(0,s.jsx)(Cr,{identity:Re.identity,methodLabel:Re.methodLabel,onComplete:ne,onCancel:()=>ne(null)},Re.id):d.map(T=>{let j=K===T,Me=gt===T,ye=gt!==null&&gt!==T||K!=null&&K!==T;return(0,s.jsxs)(a.default.Fragment,{children:[(0,s.jsx)(Sl,{method:T,themeId:H,submitting:Me,disabled:ye,highlighted:j,hasNextStep:(0,u.needsStripeMethodExplicitConfirm)(T),onClick:()=>Ae(T),backgroundColor:me?.backgroundColor,borderColor:me?.borderColor,textColor:me?.textColor,borderRadius:me?.borderRadius,fontFamily:me?.fontFamily}),!de&&ue===T&&Z&&c&&(0,s.jsx)(Et.Elements,{stripe:c,options:Z,children:(0,s.jsx)(Ta,{method:T,sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:i,onTokenizedBody:g,onErrorChange:h,onDecline:N,onCancel:()=>We(null),runBeforeButtonClick:B,onButtonClick:f,isProcessing:C,submitButtonColor:he,submitButtonBorderRadius:V,submitButtonStyle:S})},T)]},T)})})}function wl({sessionId:e,nonce:t,billingApiUrl:n,email:r,userId:o,onComplete:i,onError:d,onDecline:c,onTokenizedBody:v,firstName:g,lastName:h,chv:f,className:N,isProcessing:B,error:p,onErrorChange:C,showPayPal:he=!0,showStripe:V=!0,enabledPaymentMethods:S,enabledPaymentMethodCountries:me,showApplePay:H=!0,showGooglePay:de=!0,layout:K="default",theme:be,buttonsTheme:$e,buttonsStyles:we,appearance:gt,cardButtonContent:Fe,cardBackButtonContent:Ee,cardTitleContent:Re,showSecurityFooter:oe,onButtonClick:ne,onBeforeButtonClick:O,onBuyerIdentityReady:ue,enableAVS:We,cardFieldOrder:re,cardPreFormSlot:Ae,avsLayout:Z="row",country:T,zip:j,addressLine1:Me,addressLine2:ye,city:Q,state:Ne,onCountryChange:Qe,onZipChange:Ze,avsCheck:_e,checkoutType:ie,checkoutLayout:ae,totalAmount:X=0,currency:xe="usd",initialCardOpen:Le=!1,directPaypal:L,isSubscription:ee=!1,session:A,dataAttachmentPending:E=!1,dataAttachmentRequiresIdentity:rt=!1,debug:St=!1}){let ve=rr(),ct=Lo(),st=(0,a.useContext)(zn),{emitInstrument:ot}=(0,a.useContext)(In),Ge=E||st.claimPending===!0,b=rt||st.claimRequiresIdentity===!0,G=Ge&&!b,et=Ti(),[dt,Mt]=(0,a.useState)(!1),[Bt,se]=(0,a.useState)(null),[Ve,Gt]=(0,a.useState)(T??"US"),[wt,zt]=(0,a.useState)(j??""),[xn,Tn]=(0,a.useState)(Me??""),[Qn,Jt]=(0,a.useState)(ye??""),[sn,ln]=(0,a.useState)(Q??""),[Ft,Pn]=(0,a.useState)(Ne??""),[bt,sr]=(0,a.useState)(""),[Ht,lr]=(0,a.useState)(""),[Nt,$n]=(0,a.useState)({}),at=(0,a.useRef)(j??""),Rt=(0,a.useRef)(T??"US"),_t=(0,a.useRef)(Me??""),Qt=(0,a.useRef)(ye??""),cn=(0,a.useRef)(Q??""),dn=(0,a.useRef)(Ne??""),jn=(0,a.useRef)(""),Vn=(0,a.useRef)(""),Ut=(0,a.useRef)({});(0,a.useEffect)(()=>{let l=(F,$,Ie,W,Be)=>{if(Ut.current[F])return;let je=$?.trim();!je||je===Ie.current||(Ie.current=je,W(je),Be?.(je))};l("country",T,Rt,Gt,Qe),l("zip",j,at,zt,Ze),l("addressLine1",Me,_t,Tn),l("addressLine2",ye,Qt,Jt),l("city",Q,cn,ln),l("state",Ne,dn,Pn)},[T,j,Me,ye,Q,Ne,Qe,Ze]);let le=(0,a.useMemo)(()=>(0,u.resolveAVSConfig)(We),[We]),Cn=le!==null,An=(0,a.useMemo)(()=>(0,u.isAuthorizationOnlySession)(A),[A]),er=!!A?.vault?.html,yr=!!A?.gateways?.pcivault,Mn=!!(A?.gateways?.stripe?.enabledPaymentMethods??S)?.includes("card"),un=er||Mn||yr,Oe=!!(V&&un&&ve&&e),[Xt,Dt]=(0,a.useState)(()=>K!=="buttons"||Le?e??null:null),[Hn,k]=(0,a.useState)(0),ut=K!=="buttons"||Le||!!e&&Xt===e,Ke=(0,a.useMemo)(()=>!ve||!Oe||!e||!ut?null:ve.cardCapture({sessionId:e,captureMethod:A?.captureMethod}),[ve,Oe,e,ut,A?.captureMethod]),pn=(0,a.useMemo)(()=>{let l=Ve,F=le?(0,u.isAVSFieldVisible)(le.postal_code,l):!1;return vl(l,wt,F)},[le,Ve,wt]),{avsInvalid:tt,invalidAvsFields:qt}=(0,a.useMemo)(()=>{let l={line1:!1,city:!1,state:!1,zip:!1};if(!Oe||!le)return{avsInvalid:!1,invalidAvsFields:l};let F=Ve,$=(Be,je)=>(0,u.isAVSFieldVisible)(Be,F)&&!je.trim(),Ie={line1:$(le.address_line_1,xn),city:$(le.city,sn),state:$(le.state,Ft),zip:pn.empty||pn.malformed};return{avsInvalid:Ie.line1||Ie.city||Ie.state||Ie.zip,invalidAvsFields:Ie}},[Oe,le,Ve,xn,sn,Ft,pn]),[cr,Kn]=(0,a.useState)(!1),[Sn,Lt]=(0,a.useState)(!1),[mn,yn]=(0,a.useState)(()=>Ra(A?.vault)),[De,kt]=(0,a.useState)(Le&&un?"card":"buttons"),[xt,Bn]=(0,a.useState)(null),fn=De==="expanding"||De==="card",Fn=A?.gateways?.stripe?"stripe":void 0,Nn=(0,a.useCallback)(()=>{ot?.({class:"card_surface",provider:Fn})},[Fn,ot]),$t=280,en=(0,a.useRef)(null),rn=(0,a.useCallback)(l=>{en.current&&clearTimeout(en.current),en.current=setTimeout(()=>{en.current=null,l()},$t)},[$t]);(0,a.useEffect)(()=>()=>{en.current&&clearTimeout(en.current)},[]);let tr=(0,a.useCallback)(()=>{Nn(),Dt(e??null),k(l=>l+1),kt("expanding"),rn(()=>kt("card"))},[rn,Nn,e]),Rr=(0,a.useCallback)(()=>{kt("collapsing"),rn(()=>kt("buttons"))},[rn]),Dn=(0,a.useCallback)(l=>{Bn(l),kt("apm-expanding"),rn(()=>kt("apm-form"))},[rn]),Yn=(0,a.useCallback)(()=>{kt("apm-collapsing"),rn(()=>{kt("buttons"),Bn(null)})},[rn]);(0,a.useEffect)(()=>{K==="buttons"&&Le&&un&&(Dt(e??null),kt("card"))},[K,Le,un,e]);let[Zt,it]=(0,a.useState)(null),Kt=(0,a.useRef)(!1),D=(0,a.useRef)(null),M=(0,a.useRef)("idle"),[te,ce]=(0,a.useState)(null),Ye=(0,a.useRef)(te);(0,a.useEffect)(()=>{Ye.current=te},[te]);let pe=n||et,U=p??Bt,w=(0,a.useMemo)(()=>(0,u.resolveTheme)(be),[be]),P=(0,a.useMemo)(()=>{let l=w?.buttonsLayout??(0,u.resolveButtonsLayoutTheme)($e);return we?{...l,...we,cardButton:{...l.cardButton,...we.cardButton},cardFormContainer:{...l.cardFormContainer,...we.cardFormContainer},backButton:{...l.backButton,...we.backButton},backButtonIcon:{...l.backButtonIcon,...we.backButtonIcon},submitButton:{...l.submitButton,...we.submitButton},title:{...l.title,...we.title}}:l},[w,$e,we]),Y=gt??w?.appearance,pt=(0,a.useMemo)(()=>Wo({appearance:Y,buttonsStyles:P,layout:K}),[Y,P,K]),vt=st.inlineSessionPatchProcessing??!1,m=(B??dt)||vt,y=pe.replace(/\/+$/,""),x=(0,a.useMemo)(()=>va({userId:o,email:r,firstName:g,lastName:h,country:T,zip:j},Nt),[o,r,g,h,T,j,Nt]),Te=[x.firstName,x.lastName].filter(l=>!!l?.trim()).join(" "),J=!(0,u.isValidEmail)(x.email?.trim()),q=!Te.trim(),Xe=(0,a.useRef)(null),nt=(0,a.useRef)(null);Oe&&(Xe.current===null&&(Xe.current=J),nt.current===null&&(nt.current=q));let fe=Oe&&(Xe.current??J),Pe=Oe&&(nt.current??q),z=fe||Pe,ge=(0,a.useMemo)(()=>Pl(bt,fe),[bt,fe]),lt=ge.empty||ge.malformed,Ot=Pe&&!Ht.trim(),ke=(0,a.useMemo)(()=>ve?ve.getRawProvider():null,[ve]),gn=(0,a.useMemo)(()=>ct?ct.getRawProvider():null,[ct]),Kr=X||100,Po=(0,a.useMemo)(()=>Y?(0,mr.toStripeAppearance)(Y):null,[Y]),Co=Po?{appearance:Po}:null,Va=(0,a.useMemo)(()=>{let l=Po??{},F=l.rules??{};return{...l,rules:{...F,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...F[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...F[".AccordionItemContents"]??{}}}}},[Po]),Ha=(0,a.useMemo)(()=>{let l=Ei(X);return{...l,currency:xe.toLowerCase(),paymentMethodCreation:"manual",...l.mode==="payment"?{captureMethod:"manual"}:{},...Co}},[X,xe,Co]),Ka=(0,a.useMemo)(()=>({mode:"payment",amount:Kr,currency:xe.toLowerCase(),captureMethod:"manual",setupFutureUsage:"off_session",...Co}),[Kr,xe,Co]),Ce=(0,a.useCallback)(l=>{se(l),C?.(l)},[C]),aa=(0,a.useRef)(""),[Ya,fs]=(0,a.useState)(!1),So=(0,a.useCallback)(()=>{fs(!0)},[]);(0,a.useEffect)(()=>{if(!Oe||!z||!ue||!Ya||lt||Ot||aa.current)return;let l=kn(Vn.current),F={email:(0,u.isValidEmail)(x.email?.trim())?x.email?.trim():jn.current.trim(),firstName:x.firstName?.trim()||l.firstName,lastName:x.lastName?.trim()||l.lastName};aa.current=JSON.stringify(F),$n($=>({...$,...F})),Promise.resolve(ue(F)).catch($=>{aa.current="",Ce($ instanceof Error?$.message:"Failed to attach buyer details.")})},[Oe,z,ue,Ya,lt,Ot,x.email,x.firstName,x.lastName,Ce]),(0,a.useEffect)(()=>{!Oe||!Ke||Ke.setCardFieldOrder?.(re??null,le==null&&!z)},[Oe,Ke,re,le,z]),(0,a.useEffect)(()=>{(De==="expanding"||De==="collapsing"||De==="apm-expanding"||De==="apm-collapsing")&&Ce(null)},[De,Ce]);let Ln=(0,a.useCallback)((l,F,$)=>{c?.(jt(l,F,$))},[c]),_r=(0,a.useCallback)((l,F,$)=>{let Ie=$?.popupBlocked??ur(F),W=hl(l,Ie),Be=Sr($?.code)??nr(F)??"external_payment_method_failed",je=new u.FloPayError(W,"api_error",{code:"external_payment_method_failed",param:l});it(null),K==="buttons"&&(kt("buttons"),Bn(null)),Ce(W),d?.(je),console.error("[FloPay] External payment method failed:",{method:l,code:Be,popupBlocked:Ie})},[K,d,Ce]);(0,a.useEffect)(()=>{if(!Oe||!e){yn(null);return}let l=Ra(A?.vault);if(l){yn(l);return}if(!ut){yn(null);return}yn(null);let F=!0;return new mr.PaymentAPI(y).getVaultCapture(e,t).then($=>{if(!F)return;let Ie=Ra($);Ie?yn(Ie):Ce("Failed to load the secure card form.")}).catch($=>{F&&Ce($ instanceof Error?$.message:"Failed to load the secure card form.")}),()=>{F=!1}},[Oe,ut,Hn,e,A?.vault?.html,A?.vault?.messageToken,A?.vault?.expectedOrigin,y,t,Ce]);let Wn=(0,a.useRef)({onComplete:i,onError:d,updateError:Ce,emitDecline:Ln,resolvedAccount:x,avsConfig:le,avsCheckProp:_e,sessionId:e,nonce:t,baseUrl:y,captureMethod:A?.captureMethod,paymentId:A?.paymentId,authorizationExpiresAt:A?.authorizationExpiresAt});Wn.current={onComplete:i,onError:d,updateError:Ce,emitDecline:Ln,resolvedAccount:x,avsConfig:le,avsCheckProp:_e,sessionId:e,nonce:t,baseUrl:y,captureMethod:A?.captureMethod,paymentId:A?.paymentId,authorizationExpiresAt:A?.authorizationExpiresAt};let ia=(0,a.useRef)(!1),gs=(0,a.useCallback)(()=>{let{resolvedAccount:l,avsConfig:F,avsCheckProp:$}=Wn.current,Ie=l.email?.trim(),W=(0,u.isValidEmail)(Ie)?Ie:jn.current.trim();if(!(0,u.isValidEmail)(W))return null;let Be=kn(Vn.current),je=l.firstName?.trim()||Be.firstName,It=l.lastName?.trim()||Be.lastName;if(!je&&!It)return null;let Ct=Rt.current||l.country||"US",mt=F?(0,u.isAVSFieldVisible)(F.state,Ct):!1,yt=F?(0,u.isAVSFieldVisible)(F.address_line_1,Ct):!1,Je=F?(0,u.isAVSFieldVisible)(F.postal_code,Ct):!1,tn=F?(0,u.isAVSFieldVisible)(F.city,Ct):!1,He=F?(0,u.isAVSFieldVisible)(F.address_line_2,Ct):!1,an=yt&&!mt&&Je?(0,u.getStateFromPostalCode)(Ct,(at.current??"").trim()):null,nn=mt?dn.current:an;return{accountData:{userId:l.userId??"",email:W,firstName:je??"",lastName:It??"",...Je&&at.current?{zip:at.current}:{},...tn&&cn.current?{city:cn.current}:{},...nn?{state:nn}:{},...yt&&_t.current?{addressLine1:_t.current}:{},...He&&Qt.current?{addressLine2:Qt.current}:{},country:Ct},...$!==void 0?{avsCheck:$}:{},...F?{avsConfig:{country:(0,u.isAVSFieldVisible)(F.country,Ct),postal_code:Je,address_line_1:yt,address_line_2:He,city:tn,state:mt}}:{}}},[]),Wa=(0,a.useRef)(Ge);Wa.current=Ge,(0,a.useEffect)(()=>{Ge||U!==Ki||Wn.current.updateError(null)},[Ge,U]),(0,a.useEffect)(()=>{!Oe||!Ke||Ke.setSubmitGate?.(tt||Ge||lt||Ot)},[Oe,Ke,tt,Ge,lt,Ot]),(0,a.useEffect)(()=>{if(!Oe||!Ke)return;ia.current=!1;let l=!1,F=Ke.on("submitting",()=>{Kn(!0),D.current&&clearTimeout(D.current),M.current="validation-window",D.current=setTimeout(()=>{D.current=null,M.current==="validation-window"&&(M.current="processing")},ul),it("processing");let{baseUrl:je,sessionId:It,nonce:Ct,updateError:mt,onError:yt}=Wn.current;if(!It||!Ct)return;let Je=gs();if(!Je){mt("Enter a valid email address."),M.current="idle",it(null);return}new mr.PaymentAPI(je).patchAccountSnapshot(It,Ct,Je,{telemetryMode:"best_effort"}).catch(tn=>{if(!pl(tn))return;let He=tn instanceof Error?tn.message:"Please check your billing address and try again.";mt(He),M.current="idle",it(null),yt?.(tn instanceof u.FloPayError?tn:new u.FloPayError(He,"api_error"))})}),$=Ke.on("complete",async je=>{if(Ur(je.sessionId??Wn.current.sessionId),M.current="terminal",it("success"),await new Promise(mt=>setTimeout(mt,1200)),ia.current)return;ia.current=!0;let It=Wn.current,Ct=(0,u.isAuthorizationOnlySession)(It)||je.outcome==="authorized";Wn.current.onComplete?.(Ct?{status:"authorized",paymentIntentId:je.intentId,paymentId:je.paymentId??It.paymentId,sessionId:je.sessionId??It.sessionId,authorizationExpiresAt:je.authorizationExpiresAt??It.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",paymentIntentId:je.intentId,checkoutMethod:"card"})}),Ie=Ke.on("decline",async je=>{let{updateError:It,emitDecline:Ct}=Wn.current,mt=je.message??"Your payment was declined. Please try another card or contact your bank.";M.current="terminal",It(mt),it("error");let yt=je.failureOutcome??(0,u.normalizeCheckoutFailureOutcome)(je.declineReason)??"authorization_declined";Ct("card",mt,{code:yt,declineCode:yt}),await new Promise(Je=>setTimeout(Je,1500)),!l&&(M.current="idle",it(null))}),W=Ke.on("error",async je=>{let{updateError:It,onError:Ct}=Wn.current,mt=je.message??"There was a problem processing your payment. Please try again.";M.current="terminal",It(mt),it("error"),Ct?.(new u.FloPayError(mt,"api_error",{code:je.failureOutcome??"capture_failed"})),await new Promise(yt=>setTimeout(yt,1500)),!l&&(M.current="idle",it(null))}),Be=Ke.on("blocked",()=>{if(!Wa.current){Kn(!0);return}So(),Wn.current.updateError(Ki)});return()=>{l=!0,D.current&&(clearTimeout(D.current),D.current=null),M.current="idle",F(),$(),Ie(),W(),Be()}},[Oe,Ke,So]);let Gn=!!L?.clientId,Yr=Array.isArray(S),wo=Yr&&S.length>0,hs=Yr&&S.includes("paypal"),{expressMethods:ko,paymentElementMethods:Wr}=(0,a.useMemo)(()=>(0,u.partitionStripeMethods)(S,{excludePaypal:Gn}),[S,Gn]),Ga=Gn||!!ct,bs=(0,a.useMemo)(()=>Ga?ko.filter(l=>l!=="paypal"):ko,[ko,Ga]),vs=(0,a.useMemo)(()=>{let l=[];return H&&l.push("apple_pay"),de&&l.push("google_pay"),l},[H,de]),Io=Yr?bs:vs,Ps=V&&Io.length>0,sa=Cn?Ve:T,Eo=(0,a.useMemo)(()=>{let l=sa?.trim().toUpperCase();return l?me?Wr.filter(F=>{let $=me[F];return!$||$.length===0||$.includes(l)}):(0,u.filterStripeMethodsByCountry)(Wr,sa):Wr},[Wr,sa,me]),la=(0,a.useMemo)(()=>({mode:"payment",amount:Kr,currency:xe.toLowerCase(),paymentMethodCreation:"manual",appearance:Va}),[Kr,xe,Va]),[Ja,Xa]=(0,a.useState)("loading"),[Za,Qa]=(0,a.useState)("loading"),[ei,ti]=(0,a.useState)("loading"),[Cs,ca]=(0,a.useState)(!1),[ni,da]=(0,a.useState)("loading"),[Ro,Ss]=(0,a.useState)();(0,a.useEffect)(()=>{Ss($i())},[]);let ri=he&&(Gn||(Yr?hs:Ro===!1)),oi=V&&Ps,Gr=!G&&ri&&Gn,ai=ni==="retrying"||ni==="exhausted",Jr=!G&&ri&&!!gn&&(!Gn||ai),Xr=!G&&oi&&!!ke,Zr=!G&&V&&wo&&Eo.length>0&&!!ke,ws=Gr&&!ai?Cs:Jr&&Gi(Ja),ks=Xr&&Gi(Za),Is=Zr&&ei!=="load_error",ii=l=>l==="loading"||l==="ready",si=Gr||Jr&&ii(Ja)||Xr&&ii(Za)||Zr&&ei!=="load_error",_o=(0,a.useRef)(!1);(0,a.useEffect)(()=>{if(!_o.current){if(!V&&!he){_o.current=!0;let l=new u.FloPayError("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");d?.(l),Ce(l.message)}else if(!V&&he&&!Gn&&!gn){_o.current=!0;let l=new u.FloPayError("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");d?.(l),Ce(l.message)}else if(Ro!==void 0&&!G&&!un&&!si){_o.current=!0;let l=new u.FloPayError("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?.(l),Ce(l.message)}}},[V,he,Gn,gn,Ro,G,un,si,d,Ce]);let li=(0,a.useRef)(!1);(0,a.useEffect)(()=>{if(li.current||!wo)return;let l=[];H!==!0&&l.push("showApplePay"),de!==!0&&l.push("showGooglePay"),l.length!==0&&(li.current=!0,console.warn(`[FloPay] ${l.join(" / ")} ${l.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.`))},[wo,H,de]);let ci=(0,a.useCallback)((l,F)=>st.applyInlineSessionPatch?st.applyInlineSessionPatch(l).then($=>({error:null,sessionId:$.sessionId||e,nonce:$.session?.clientSecret||t})).catch($=>{let Ie=Wi(F,$);return Ce(Ie.message),d?.(Ie),{error:Ie,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[st.applyInlineSessionPatch,t,d,e,Ce]),On=(0,a.useCallback)(async l=>{if(!O)return{proceed:!0};try{let F=await O({method:l,sessionId:e||void 0,createSession:st.inlineSessionDraft});if(F===!1)return{proceed:!1};if(F&&typeof F=="object"){F.account&&$n(Ie=>({...Ie??{},...F.account}));let $=await ci(F,l);return $.error?{proceed:!1,accountPatch:F.account}:{proceed:!0,accountPatch:F.account,sessionId:$.sessionId,nonce:$.nonce}}return{proceed:!0}}catch(F){let $=Wi(l,F);return Ce($.message),d?.($),{proceed:!1}}},[ci,st.inlineSessionDraft,O,d,e,Ce]),di=(0,a.useCallback)(async(l,F)=>{if(Kt.current)return;Kt.current=!0,Mt(!0),it("processing"),Ce(null);let $=F?.sessionId??e,Ie=F?.nonce??t,W=va(x,F?.accountPatch),Be=F?.completionPaymentMethodId??ao(l),je=l.originalPaymentMethodId?{...l,originalPaymentMethodId:void 0}:l,It=l.gateway==="stripe"?"stripe":l.gateway==="paypal"||l.isPaypal?"paypal":void 0,Ct=()=>{ot?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"process_payment",provider:It})};try{let yt=await new mr.PaymentAPI(y).processPayment(W.userId??"",{sessionId:$,nonce:Ie,tokenizedData:je,accountData:{userId:W.userId??"",email:W.email??"",firstName:W.firstName??"",lastName:W.lastName??"",...le?(()=>{let He=Rt.current,an=(0,u.isAVSFieldVisible)(le.state,He),nn=(0,u.isAVSFieldVisible)(le.address_line_1,He),Yt=(0,u.isAVSFieldVisible)(le.postal_code,He),no=nn&&!an&&Yt?(0,u.getStateFromPostalCode)(He,(at.current??"").trim()):null,ro=an?dn.current:no;return{country:He,...Yt&&at.current?{zip:at.current}:{},...(0,u.isAVSFieldVisible)(le.city,He)&&cn.current?{city:cn.current}:{},...ro?{state:ro}:{},...nn&&_t.current?{addressLine1:_t.current}:{},...(0,u.isAVSFieldVisible)(le.address_line_2,He)&&Qt.current?{addressLine2:Qt.current}:{}}})():{}},chv:f,avsCheck:_e??!1,checkoutType:ie,checkoutLayout:ae,avsConfig:le?{country:(0,u.isAVSFieldVisible)(le.country,Rt.current),postal_code:(0,u.isAVSFieldVisible)(le.postal_code,Rt.current),address_line_1:(0,u.isAVSFieldVisible)(le.address_line_1,Rt.current),address_line_2:(0,u.isAVSFieldVisible)(le.address_line_2,Rt.current),city:(0,u.isAVSFieldVisible)(le.city,Rt.current),state:(0,u.isAVSFieldVisible)(le.state,Rt.current)}:void 0});if(yt.ok){let He=yt.status===204?null:await yt.json().catch(()=>null),an=(0,u.isAuthorizationOnlySession)(A)||He?.status==="authorized";Ur($),it("success"),ce(null),await new Promise(nn=>setTimeout(nn,1200)),i?.(an?{status:"authorized",...typeof He?.paymentId=="string"?{paymentId:He.paymentId}:A?.paymentId?{paymentId:A.paymentId}:{},sessionId:typeof He?.sessionId=="string"?He.sessionId:$,...typeof He?.authorizationExpiresAt=="string"?{authorizationExpiresAt:He.authorizationExpiresAt}:A?.authorizationExpiresAt?{authorizationExpiresAt:A.authorizationExpiresAt}:{},paymentIntentId:l.threeDSecureActionResultTokenId,paymentMethodId:Be,checkoutMethod:l.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:l.threeDSecureActionResultTokenId,paymentMethodId:Be,checkoutMethod:l.isPaypal?"paypal":"card"});return}let Je=await yt.json().catch(()=>null);if(Je?.type==="paypal_redirect_required"){let He=Je.threeDSecureToken,an=Je.paymentMethodId||l.id||"";if(!ve||!He){it("error"),Ce("PayPal authorization required but no token provided.");return}try{let nn=ct?.getRawProvider();if(!nn){Ce("PayPal is not available.");return}let Yt={return_url:window.location.href};an&&(Yt.payment_method=an);let{error:no}=await nn.confirmPayment({clientSecret:He,confirmParams:Yt,redirect:"if_required"});if(no){it("error");let ro=no.message??"PayPal payment failed.";Ce(ro),Ln("paypal",ro,{code:no.code})}}catch(nn){it("error"),Ce(nn instanceof Error?nn.message:"PayPal authorization failed.")}return}if(Je?.type==="paypal_direct_required"){let He=Je.orderId;if(!He){it("error"),Ce("PayPal retry required but no order id provided.");return}let an=Ye.current?.attempts??0;if(an>=2){it("error"),Ce("PayPal payment could not be completed after multiple attempts."),Ln("paypal","paypal_direct_required retry limit exceeded");return}ca(!1),da("loading"),ce({orderId:He,attempts:an+1}),it(null);return}(0,u.classifyPaymentRejection)(yt.status,Je)||Ct(),it("error");let tn=Je?.message??"Payment failed. Please try again.";Ce(tn),Ln(l.isPaypal?"paypal":"card",tn,{code:Je?.code??Je?.gatewayErrorCode,declineCode:Je?.declineCode??Je?.gatewayDeclineReason}),await new Promise(He=>setTimeout(He,1500))}catch(mt){Qi(mt)||Ct(),it("error"),Ce(mt instanceof Error?mt.message:"An unexpected error occurred"),await new Promise(yt=>setTimeout(yt,1500))}finally{Mt(!1),it(null),Kt.current=!1}},[y,e,t,x,Te,f,ve,ct,A,i,d,Ce,Ln,ot]),wn=(0,a.useCallback)((l,F)=>{v?v(l):di(l,F)},[v,di]),ui=(0,a.useRef)(!1);(0,a.useEffect)(()=>{if(typeof window>"u"||ui.current)return;let l=new URLSearchParams(window.location.search),F=l.get("payment_intent"),$=l.get("payment_intent_client_secret"),Ie=l.get("redirect_status");if(!F||!$)return;let W=yt=>{let Je=localStorage.getItem(yt);if(!Je)return null;try{return JSON.parse(Je)}catch{return localStorage.removeItem(yt),null}},Be=W(Jn)??W(Hi),je;if(Be?.clientSecret){if(Be.clientSecret!==$)return;je={...Be.accountPatch?{accountPatch:Be.accountPatch}:{},...Be.sessionId?{sessionId:Be.sessionId}:{},...Be.nonce?{nonce:Be.nonce}:{}}}else if(Be?.sessionId&&Be.sessionId!==e)return;ui.current=!0,localStorage.removeItem(Jn),localStorage.removeItem(Hi);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=Be?.paymentMethodType??Be?.tokenType??"card",mt="card";(async()=>{let yt=ve?.getRawProvider();if(!yt){let Yt="Payment is not available \u2014 please refresh and try again.";Ce(Yt),Ln(mt,Yt);return}if(Ie==="failed"){let Yt="Payment was declined. Please try again.";Ce(Yt),Ln(mt,Yt);return}let{paymentIntent:Je,error:tn}=await yt.retrievePaymentIntent($);if(tn){let Yt=tn.message??"Failed to retrieve payment status.";Ce(Yt),Ln(mt,Yt,{code:tn.code});return}let He=Je?.status,an=Do(He);if(!Je||!an){let Yt=He==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";Ce(Yt),Ln(mt,Yt,{code:He??"missing_payment_intent"});return}let nn=typeof Je.payment_method=="string"?Je.payment_method:Je.payment_method?.id;wn({id:nn??Be?.paymentMethodId??Be?.tokenId??Je.id,type:"card",threeDSecureActionResultTokenId:Je.id,gateway:Be?.gateway??"stripe",paymentMethodType:Ct},je)})()},[e,wn,ve,Ce,Ln]);let ua=(0,a.useCallback)(l=>{l.preventDefault()},[]);if(!(ve!==null))return(0,s.jsx)("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let Qr=K==="buttons",on=Y?.variables,Es=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),pa=on?.colorBackground,Rs=pa&&!Es.has(pa)?pa:void 0,fr=P.cardInputBorder??(Qr?"#e5e7eb":"#A4A4FF"),ma=on?.colorDanger??"#dc2626",gr=l=>cr&&l?ma:fr,xo=(pn.malformed||pn.empty)&&(Sn||cr),_s=xo?ma:gr(qt.zip),ya=P.cardFormContainer?.backgroundColor??Rs??(Qr?"white":"#EDEDFF"),hr=P.cardInputBackground??on?.colorBackground??"white",fa=Ar(Ee),pi=Ar(Re),xr=P.nameInput,mi=P.cardInputFontSize??Cl(xr?.fontSize)??on?.fontSizeBase??"16px",yi=typeof xr?.fontFamily=="string"?xr.fontFamily:on?.fontFamily??"Poppins, sans-serif",fi=Ea(xr?.fontWeight)??400,xs=P.cardInputColor??(typeof xr?.color=="string"?xr.color:void 0)??on?.colorText??"#262833",Ts=P.cardInputPlaceholderColor??"#9ca3af",Pt=on?.borderRadius??"8px",br=on?.borderRadius??P.cardButton?.borderRadius??Pt,vr=on?.colorPrimary??"#4A49FF",As=on?.colorPrimaryHover??Vr(vr,.12),eo=on?.colorText??"#262833",Tr={fontSize:mi,fontFamily:yi,fontWeight:fi,color:xs,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},Ms={"--flopay-input-placeholder-color":Ts,"--flopay-input-font-size":mi,"--flopay-input-font-family":yi,"--flopay-input-font-weight":String(fi)},to=P.cardFormContainer??{},ga=to.padding??(Qr?"0":"1rem"),ha=to.borderRadius??Pt,Bs=Ke&&mn?(0,s.jsx)(jr,{capture:Ke,html:mn.html,messageToken:mn.messageToken,expectedOrigin:mn.expectedOrigin,theme:pt,onReady:()=>{if(!z&&!le||typeof document>"u")return;let l=()=>{(document.querySelector('[data-testid="flopay-vault-identity-fields"]')??document.querySelector('[data-testid="flopay-avs-fields"]'))?.querySelector("input:not([disabled]), select:not([disabled])")?.focus()};l();let F=0,$=window.setInterval(()=>{F+=1;let Ie=document.activeElement;!!Ie&&Ie.tagName==="IFRAME"&&Ie.id==="flopay_vault_form_iframe"?(l(),window.clearInterval($)):F>=50&&window.clearInterval($)},100)},onError:l=>Ce(l),onValidation:l=>{let F=M.current;(F==="idle"||F==="validation-window")&&(Ce(l),l&&M.current==="validation-window"&&(D.current&&(clearTimeout(D.current),D.current=null),M.current="idle",it(null)))}}):(0,s.jsx)("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"}),gi=(0,s.jsxs)("div",{onFocusCapture:l=>{["INPUT","SELECT","TEXTAREA","IFRAME"].includes(l.target.tagName)&&Nn()},style:{backgroundColor:ya,borderRadius:ha,...to,padding:ga,...Ms,display:"flex",flexDirection:"column"},children:[(0,s.jsx)("style",{children:`
31
31
  .flopay-shared-input::placeholder {
32
32
  color: var(--flopay-input-placeholder-color);
33
33
  opacity: 1;
@@ -35,13 +35,13 @@ ${Mt.join(`
35
35
  font-family: var(--flopay-input-font-family);
36
36
  font-weight: var(--flopay-input-font-weight);
37
37
  }
38
- `}),Qr&&fn&&(0,s.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:Oe?-2:0},children:[(0,s.jsxs)("button",{type:"button",onClick:Rr,style:{display:"inline-flex",alignItems:"center",gap:fa?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:[(0,s.jsx)("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:(0,s.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,s.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,s.jsx)(Br,{content:Ee})]}),pi?(0,s.jsx)("div",{style:{flex:1}}):(0,s.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:P.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...P.title},children:(0,s.jsx)(oo,{content:Re})})]}),!Qr&&!pi&&(0,s.jsx)("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:eo,order:Oe?-3:0,...P.title},children:(0,s.jsx)(oo,{content:Re})}),Oe&&z&&(0,s.jsxs)("div",{"data-testid":"flopay-vault-identity-fields",style:{order:-1,marginTop:"0.5rem"},children:[fe&&(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)("label",{htmlFor:"flopay-buyer-email",style:{display:"block",color:eo,...Tr},children:"Email address"}),(0,s.jsx)("div",{style:{backgroundColor:hr,border:`1px solid ${fr}`,borderRadius:Pt,marginTop:"0.375rem",padding:"10px"},children:(0,s.jsx)("input",{className:"flopay-shared-input",id:"flopay-buyer-email",name:"email",type:"email",autoComplete:"email",value:bt,onChange:l=>{jn.current=l.target.value,sr(l.target.value)},onBlur:So,disabled:m,required:!0,"data-testid":"flopay-email",style:{width:"100%",border:"none",outline:"none",background:"transparent",...Tr}})})]}),Pe&&(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)("label",{htmlFor:"flopay-buyer-name",style:{display:"block",marginTop:fe?"0.75rem":void 0,color:eo,...Tr},children:"Full name"}),(0,s.jsx)("div",{style:{backgroundColor:hr,border:`1px solid ${fr}`,borderRadius:Pt,marginTop:"0.375rem",padding:"10px"},children:(0,s.jsx)("input",{className:"flopay-shared-input",id:"flopay-buyer-name",name:"name",autoComplete:"name",value:Vt,onChange:l=>{Vn.current=l.target.value,lr(l.target.value)},onBlur:So,disabled:m,required:!0,"data-testid":"flopay-name",style:{width:"100%",border:"none",outline:"none",background:"transparent",...Tr}})})]})]}),le&&(0,s.jsx)("div",{style:{order:Oe?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let l=Ve,F=(W=!1)=>({backgroundColor:hr,border:`1px solid ${gr(W)}`,borderRadius:Pt,marginTop:"0.5rem",padding:"10px"}),$=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...Tr}),Ie=(0,u.getStateOptions)(l);return(0,s.jsxs)(s.Fragment,{children:[(0,u.isAVSFieldVisible)(le.address_line_1,l)&&(0,s.jsx)("div",{style:F(Ut.line1),children:(0,s.jsx)("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:xn,onChange:W=>{zt.current.addressLine1=!0,_t.current=W.target.value,Tn(W.target.value)},disabled:m,required:!0,"data-testid":"flopay-address-line1",style:$()})}),(0,u.isAVSFieldVisible)(le.address_line_2,l)&&(0,s.jsx)("div",{style:F(),children:(0,s.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-address-line2",name:"billing-address-line2",placeholder:"Apt, Suite, Unit (optional)",autoComplete:"billing address-line2",value:Qn,onChange:W=>{zt.current.addressLine2=!0,Qt.current=W.target.value,Gt(W.target.value)},disabled:m,"data-testid":"flopay-address-line2",style:$()})}),((0,u.isAVSFieldVisible)(le.city,l)||(0,u.isAVSFieldVisible)(le.state,l))&&(0,s.jsxs)("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[(0,u.isAVSFieldVisible)(le.city,l)&&(0,s.jsx)("div",{style:{flex:1,backgroundColor:hr,borderTop:`1px solid ${gr(Ut.city)}`,borderRight:`1px solid ${gr(Ut.city)}`,borderBottom:`1px solid ${gr(Ut.city)}`,borderLeft:`1px solid ${gr(Ut.city)}`,padding:"10px",borderTopLeftRadius:Pt,borderBottomLeftRadius:Pt,...(0,u.isAVSFieldVisible)(le.state,l)?{borderRight:"none",borderTopRightRadius:0,borderBottomRightRadius:0}:{borderRadius:Pt}},children:(0,s.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-city",name:"billing-city",placeholder:"City",autoComplete:"billing address-level2",value:sn,onChange:W=>{zt.current.city=!0,cn.current=W.target.value,ln(W.target.value)},disabled:m,required:!0,"data-testid":"flopay-city",style:$()})}),(0,u.isAVSFieldVisible)(le.state,l)&&(0,s.jsx)("div",{style:{flex:1,backgroundColor:hr,border:`1px solid ${gr(Ut.state)}`,padding:"10px",borderTopRightRadius:Pt,borderBottomRightRadius:Pt,...(0,u.isAVSFieldVisible)(le.city,l)?{borderTopLeftRadius:0,borderBottomLeftRadius:0}:{borderRadius:Pt}},children:Ie?(0,s.jsxs)("select",{id:"flopay-billing-state",name:"billing-state",value:Ft,onChange:W=>{zt.current.state=!0,dn.current=W.target.value,Pn(W.target.value)},disabled:m,autoComplete:"billing address-level1",required:!0,"data-testid":"flopay-state",style:{...$(),cursor:"pointer"},children:[(0,s.jsx)("option",{value:"",children:(0,u.getStateLabel)(l)}),Ie.map(W=>(0,s.jsx)("option",{value:W.code,children:W.name},W.code))]}):(0,s.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-state",name:"billing-state",placeholder:(0,u.getStateLabel)(l),autoComplete:"billing address-level1",value:Ft,onChange:W=>{zt.current.state=!0,dn.current=W.target.value,Pn(W.target.value)},disabled:m,required:!0,"data-testid":"flopay-state",style:$()})})]}),((0,u.isAVSFieldVisible)(le.country,l)||(0,u.isAVSFieldVisible)(le.postal_code,l))&&(0,s.jsxs)("div",{style:{display:"flex",flexDirection:Z==="column"?"column":"row",gap:Z==="column"?"0.5rem":"0",marginTop:"0.5rem"},children:[(0,u.isAVSFieldVisible)(le.country,l)&&(0,s.jsx)("div",{style:{flex:Z==="row"?1:void 0,backgroundColor:hr,borderTop:`1px solid ${fr}`,borderRight:`1px solid ${fr}`,borderBottom:`1px solid ${fr}`,borderLeft:`1px solid ${fr}`,padding:"10px",...Z==="row"&&(0,u.isAVSFieldVisible)(le.postal_code,l)?{borderRadius:"0",borderTopLeftRadius:Pt,borderBottomLeftRadius:Pt,borderRight:"none"}:{borderRadius:Pt}},children:(0,s.jsx)("select",{id:"flopay-billing-country",name:"billing-country",value:Ve,onChange:W=>{zt.current.country=!0,Rt.current=W.target.value,Wt(W.target.value),Qe?.(W.target.value),dn.current="",Pn("")},disabled:m,autoComplete:"billing country","data-testid":"flopay-country",style:{...$(),cursor:"pointer"},children:u.COUNTRY_OPTIONS.map(W=>(0,s.jsxs)("option",{value:W.code,children:[W.flag," ",W.name]},W.code))})}),(0,u.isAVSFieldVisible)(le.postal_code,l)&&(0,s.jsx)("div",{style:{flex:Z==="row"?1:void 0,backgroundColor:hr,border:`1px solid ${_s}`,padding:"10px",...Z==="row"&&(0,u.isAVSFieldVisible)(le.country,l)?{borderRadius:"0",borderTopRightRadius:Pt,borderBottomRightRadius:Pt}:{borderRadius:Pt}},children:(0,s.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-postal-code",name:"billing-postal-code",placeholder:(0,u.getPostalCodeLabel)(Ve),autoComplete:"billing postal-code",value:wt,onChange:W=>{zt.current.zip=!0,at.current=W.target.value,Ot(W.target.value),Ze?.(W.target.value)},onBlur:()=>Xt(!0),disabled:m,required:pn.required,"aria-invalid":xo||void 0,"aria-describedby":xo?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:$()})})]}),xo&&(0,s.jsx)("div",{id:"flopay-billing-postal-code-error",role:"alert","data-testid":"flopay-zip-error",style:{marginTop:"0.375rem",color:ma,...Tr,fontSize:"0.75rem"},children:pn.empty?`${(0,u.getPostalCodeLabel)(l)} is required`:bl(l)})]})})()}),Oe&&Te&&(0,s.jsx)("div",{style:{order:-2,width:"100%"},children:Te}),Oe&&Bs,U&&(0,s.jsx)(zr,{margin:"0.75rem 0",styleOverride:P.errorBanner,children:U})]}),To={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"},hi=l=>St?!he||!Gn?(0,s.jsx)("pre",{"data-testid":l,style:To,children:"FloPay/DirectPayPal-debug - not enabled"}):(0,s.jsx)("pre",{"data-testid":l,style:To,children:["FloPay/DirectPayPal-debug (parent gate)",` showPayPal=${he}`,` directPaypalConfigured=${Gn}`,` inAppBrowserDetected=${String(Ro)}`,` shouldRenderDirectPayPal=${Gr}`,` shouldRenderStripePayPal=${Jr}`,` hasPaypalStripeInstance=${!!gn}`].join(`
38
+ `}),Qr&&fn&&(0,s.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:Oe?-2:0},children:[(0,s.jsxs)("button",{type:"button",onClick:Rr,style:{display:"inline-flex",alignItems:"center",gap:fa?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:[(0,s.jsx)("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:(0,s.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,s.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,s.jsx)(Br,{content:Ee})]}),pi?(0,s.jsx)("div",{style:{flex:1}}):(0,s.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:P.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...P.title},children:(0,s.jsx)(oo,{content:Re})})]}),!Qr&&!pi&&(0,s.jsx)("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:eo,order:Oe?-3:0,...P.title},children:(0,s.jsx)(oo,{content:Re})}),Oe&&z&&(0,s.jsxs)("div",{"data-testid":"flopay-vault-identity-fields",style:{order:-1,marginTop:"0.5rem"},children:[fe&&(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)("label",{htmlFor:"flopay-buyer-email",style:{display:"block",color:eo,...Tr},children:"Email address"}),(0,s.jsx)("div",{style:{backgroundColor:hr,border:`1px solid ${fr}`,borderRadius:Pt,marginTop:"0.375rem",padding:"10px"},children:(0,s.jsx)("input",{className:"flopay-shared-input",id:"flopay-buyer-email",name:"email",type:"email",autoComplete:"email",value:bt,onChange:l=>{jn.current=l.target.value,sr(l.target.value)},onBlur:So,disabled:m,required:!0,"data-testid":"flopay-email",style:{width:"100%",border:"none",outline:"none",background:"transparent",...Tr}})})]}),Pe&&(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)("label",{htmlFor:"flopay-buyer-name",style:{display:"block",marginTop:fe?"0.75rem":void 0,color:eo,...Tr},children:"Full name"}),(0,s.jsx)("div",{style:{backgroundColor:hr,border:`1px solid ${fr}`,borderRadius:Pt,marginTop:"0.375rem",padding:"10px"},children:(0,s.jsx)("input",{className:"flopay-shared-input",id:"flopay-buyer-name",name:"name",autoComplete:"name",value:Ht,onChange:l=>{Vn.current=l.target.value,lr(l.target.value)},onBlur:So,disabled:m,required:!0,"data-testid":"flopay-name",style:{width:"100%",border:"none",outline:"none",background:"transparent",...Tr}})})]})]}),le&&(0,s.jsx)("div",{style:{order:Oe?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let l=Ve,F=(W=!1)=>({backgroundColor:hr,border:`1px solid ${gr(W)}`,borderRadius:Pt,marginTop:"0.5rem",padding:"10px"}),$=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...Tr}),Ie=(0,u.getStateOptions)(l);return(0,s.jsxs)(s.Fragment,{children:[(0,u.isAVSFieldVisible)(le.address_line_1,l)&&(0,s.jsx)("div",{style:F(qt.line1),children:(0,s.jsx)("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:xn,onChange:W=>{Ut.current.addressLine1=!0,_t.current=W.target.value,Tn(W.target.value)},disabled:m,required:!0,"data-testid":"flopay-address-line1",style:$()})}),(0,u.isAVSFieldVisible)(le.address_line_2,l)&&(0,s.jsx)("div",{style:F(),children:(0,s.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-address-line2",name:"billing-address-line2",placeholder:"Apt, Suite, Unit (optional)",autoComplete:"billing address-line2",value:Qn,onChange:W=>{Ut.current.addressLine2=!0,Qt.current=W.target.value,Jt(W.target.value)},disabled:m,"data-testid":"flopay-address-line2",style:$()})}),((0,u.isAVSFieldVisible)(le.city,l)||(0,u.isAVSFieldVisible)(le.state,l))&&(0,s.jsxs)("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[(0,u.isAVSFieldVisible)(le.city,l)&&(0,s.jsx)("div",{style:{flex:1,backgroundColor:hr,borderTop:`1px solid ${gr(qt.city)}`,borderRight:`1px solid ${gr(qt.city)}`,borderBottom:`1px solid ${gr(qt.city)}`,borderLeft:`1px solid ${gr(qt.city)}`,padding:"10px",borderTopLeftRadius:Pt,borderBottomLeftRadius:Pt,...(0,u.isAVSFieldVisible)(le.state,l)?{borderRight:"none",borderTopRightRadius:0,borderBottomRightRadius:0}:{borderRadius:Pt}},children:(0,s.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-city",name:"billing-city",placeholder:"City",autoComplete:"billing address-level2",value:sn,onChange:W=>{Ut.current.city=!0,cn.current=W.target.value,ln(W.target.value)},disabled:m,required:!0,"data-testid":"flopay-city",style:$()})}),(0,u.isAVSFieldVisible)(le.state,l)&&(0,s.jsx)("div",{style:{flex:1,backgroundColor:hr,border:`1px solid ${gr(qt.state)}`,padding:"10px",borderTopRightRadius:Pt,borderBottomRightRadius:Pt,...(0,u.isAVSFieldVisible)(le.city,l)?{borderTopLeftRadius:0,borderBottomLeftRadius:0}:{borderRadius:Pt}},children:Ie?(0,s.jsxs)("select",{id:"flopay-billing-state",name:"billing-state",value:Ft,onChange:W=>{Ut.current.state=!0,dn.current=W.target.value,Pn(W.target.value)},disabled:m,autoComplete:"billing address-level1",required:!0,"data-testid":"flopay-state",style:{...$(),cursor:"pointer"},children:[(0,s.jsx)("option",{value:"",children:(0,u.getStateLabel)(l)}),Ie.map(W=>(0,s.jsx)("option",{value:W.code,children:W.name},W.code))]}):(0,s.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-state",name:"billing-state",placeholder:(0,u.getStateLabel)(l),autoComplete:"billing address-level1",value:Ft,onChange:W=>{Ut.current.state=!0,dn.current=W.target.value,Pn(W.target.value)},disabled:m,required:!0,"data-testid":"flopay-state",style:$()})})]}),((0,u.isAVSFieldVisible)(le.country,l)||(0,u.isAVSFieldVisible)(le.postal_code,l))&&(0,s.jsxs)("div",{style:{display:"flex",flexDirection:Z==="column"?"column":"row",gap:Z==="column"?"0.5rem":"0",marginTop:"0.5rem"},children:[(0,u.isAVSFieldVisible)(le.country,l)&&(0,s.jsx)("div",{style:{flex:Z==="row"?1:void 0,backgroundColor:hr,borderTop:`1px solid ${fr}`,borderRight:`1px solid ${fr}`,borderBottom:`1px solid ${fr}`,borderLeft:`1px solid ${fr}`,padding:"10px",...Z==="row"&&(0,u.isAVSFieldVisible)(le.postal_code,l)?{borderRadius:"0",borderTopLeftRadius:Pt,borderBottomLeftRadius:Pt,borderRight:"none"}:{borderRadius:Pt}},children:(0,s.jsx)("select",{id:"flopay-billing-country",name:"billing-country",value:Ve,onChange:W=>{Ut.current.country=!0,Rt.current=W.target.value,Gt(W.target.value),Qe?.(W.target.value),dn.current="",Pn("")},disabled:m,autoComplete:"billing country","data-testid":"flopay-country",style:{...$(),cursor:"pointer"},children:u.COUNTRY_OPTIONS.map(W=>(0,s.jsxs)("option",{value:W.code,children:[W.flag," ",W.name]},W.code))})}),(0,u.isAVSFieldVisible)(le.postal_code,l)&&(0,s.jsx)("div",{style:{flex:Z==="row"?1:void 0,backgroundColor:hr,border:`1px solid ${_s}`,padding:"10px",...Z==="row"&&(0,u.isAVSFieldVisible)(le.country,l)?{borderRadius:"0",borderTopRightRadius:Pt,borderBottomRightRadius:Pt}:{borderRadius:Pt}},children:(0,s.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-postal-code",name:"billing-postal-code",placeholder:(0,u.getPostalCodeLabel)(Ve),autoComplete:"billing postal-code",value:wt,onChange:W=>{Ut.current.zip=!0,at.current=W.target.value,zt(W.target.value),Ze?.(W.target.value)},onBlur:()=>Lt(!0),disabled:m,required:pn.required,"aria-invalid":xo||void 0,"aria-describedby":xo?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:$()})})]}),xo&&(0,s.jsx)("div",{id:"flopay-billing-postal-code-error",role:"alert","data-testid":"flopay-zip-error",style:{marginTop:"0.375rem",color:ma,...Tr,fontSize:"0.75rem"},children:pn.empty?`${(0,u.getPostalCodeLabel)(l)} is required`:bl(l)})]})})()}),Oe&&Ae&&(0,s.jsx)("div",{style:{order:-2,width:"100%"},children:Ae}),Oe&&Bs,U&&(0,s.jsx)(zr,{margin:"0.75rem 0",styleOverride:P.errorBanner,children:U})]}),To={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"},hi=l=>St?!he||!Gn?(0,s.jsx)("pre",{"data-testid":l,style:To,children:"FloPay/DirectPayPal-debug - not enabled"}):(0,s.jsx)("pre",{"data-testid":l,style:To,children:["FloPay/DirectPayPal-debug (parent gate)",` showPayPal=${he}`,` directPaypalConfigured=${Gn}`,` inAppBrowserDetected=${String(Ro)}`,` shouldRenderDirectPayPal=${Gr}`,` shouldRenderStripePayPal=${Jr}`,` hasPaypalStripeInstance=${!!gn}`].join(`
39
39
  `)}):null,bi=l=>St?!V||!ke?(0,s.jsx)("pre",{"data-testid":l,style:To,children:"FloPay/Stripe-debug - not enabled"}):(0,s.jsx)("pre",{"data-testid":l,style:To,children:["FloPay/Stripe-debug (parent gate)",` showStripe=${V}`,` currency=${xe}`,` amountInCents=${Kr}`,` enabledPaymentMethods: ${JSON.stringify(S??[])}`,` enabledPaymentMethodsProvided=${Yr}`,` hasEnabledMethods=${wo}`,` expressMethods: ${JSON.stringify(ko)}`,` walletExpressMethods: ${JSON.stringify(Io)}`,` paymentElementMethods: ${JSON.stringify(Wr)}`,` paymentElementMethodsForCurrency: ${JSON.stringify(Eo)}`,` hasStripeInstance=${!!ke}`,` shouldRenderWallets=${Xr}`,` shouldRenderPaymentElement=${Zr}`].join(`
40
- `)}):null,vi=Ne==="apm-expanding"||Ne==="apm-form"||Ne==="apm-collapsing",Ao=Ne==="apm-expanding"?`flopay-card-enter ${qt}ms cubic-bezier(0, 0, 0.2, 1) both`:Ne==="apm-collapsing"?`flopay-card-exit ${qt}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0,Mo=xt?{...la,paymentMethodTypes:[xt]}:null;if(K==="buttons"){let l=Ne==="buttons"||Ne==="expanding"||Ne==="apm-expanding",F=Ne==="expanding"||Ne==="card"||Ne==="collapsing",$=Fe===void 0?{boxSizing:"border-box",height:Go,padding:"0 1rem"}:{padding:"0.9rem 1rem"},Ie=Ne==="expanding"||Ne==="apm-expanding"?`flopay-buttons-exit ${qt}ms cubic-bezier(0.4, 0, 0.2, 1) both`:Ne==="collapsing"||Ne==="apm-collapsing"?`flopay-buttons-enter ${qt}ms cubic-bezier(0, 0, 0.2, 1) both`:void 0,W=Ne==="expanding"?`flopay-card-enter ${qt}ms cubic-bezier(0, 0, 0.2, 1) both`:Ne==="collapsing"?`flopay-card-exit ${qt}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0;return(0,s.jsxs)("form",{onSubmit:ua,className:D,style:{position:"relative"},children:[(0,s.jsx)(_a,{}),Zt&&(0,s.jsx)(Rn,{status:Zt,errorMessage:U,authorized:An}),(0,s.jsxs)("div",{style:{display:"grid"},children:[(0,s.jsxs)("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!l&&!Ie?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!l&&!Ie?fl:{},...Ie?{animation:Ie,pointerEvents:"none"}:{}},children:[hi("flopay-direct-paypal-gate-debug"),bi("flopay-stripe-gate-debug"),Gr&&L&&(0,s.jsxs)(s.Fragment,{children:[te&&(0,s.jsx)("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."}),(0,s.jsx)(co,{sessionId:e,nonce:t,billingApiUrl:pe,email:x.email,billingName:Me||void 0,onBuyerIdentityReady:ue,clientId:L.clientId,environment:L.environment,currency:xe.toUpperCase(),isSubscription:ee,providerObjectType:L.providerObjectType,onTokenizedBody:wn,onComplete:i,onErrorChange:Ce,onDecline:c,onTechnicalFailure:_r,onButtonClick:ne,runBeforeButtonClick:On,isProcessing:m,onLoadStateChange:ca,onInitializationStateChange:da,session:A??null,existingOrderId:te?.orderId,debug:St},te?.orderId??"fresh")]}),Jr&&(0,s.jsx)(Et.Elements,{stripe:gn,options:Ka,children:(0,s.jsx)(Ji,{sessionId:e,nonce:t,email:x.email,billingName:Me||void 0,onBuyerIdentityReady:ue,billingApiUrl:pe,onTokenizedBody:wn,onErrorChange:Ce,isProcessing:m,onButtonClick:ne,onDecline:c,onTechnicalFailure:_r,runBeforeButtonClick:On,onLoadStateChange:Xa,placeholderBorderRadius:br})}),Xr?(0,s.jsx)(Et.Elements,{stripe:ke,options:Ha,children:(0,s.jsx)(Xi,{sessionId:e,nonce:t,email:x.email,billingName:Me||void 0,onBuyerIdentityReady:ue,billingApiUrl:pe,intentKind:X>0?"payment":"setup",expressMethods:Io,onTokenizedBody:wn,onErrorChange:Ce,onButtonClick:ne,onDecline:c,onTechnicalFailure:_r,runBeforeButtonClick:On,onLoadStateChange:Qa,placeholderBorderRadius:br})}):oi?(0,s.jsx)("div",{style:{height:Go,borderRadius:br,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,Zr&&(0,s.jsx)(Zi,{sessionId:e,nonce:t,email:x.email,billingName:[x.firstName,x.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:ue,billingApiUrl:pe,paymentElementMethods:Eo,stripeInstance:ke,paymentElementBaseOptions:la,onTokenizedBody:wn,onErrorChange:Ce,onButtonClick:ne,onDecline:c,runBeforeButtonClick:On,onLoadStateChange:ti,isProcessing:m,submitButtonColor:vr,submitButtonBorderRadius:Pt,submitButtonStyle:P.submitButton,onExpandApm:Nn,expandedApmMethod:xt,themeId:be,buttonAppearance:{backgroundColor:P.cardButton?.backgroundColor,borderColor:P.cardInputBorder,textColor:P.cardButton?.color,borderRadius:br}}),Oe&&(0,s.jsx)("button",{type:"button",onClick:async()=>{m||!(await On("card")).proceed||(ne?.("card"),tr())},disabled:m,style:{width:"100%",...$,...P.cardButton,...Ma({themeBundle:w,resolvedPrimaryColor:vr,resolvedBorderRadius:Pt,submitButtonStyle:P.submitButton,explicitPrimaryColor:on?.colorPrimary}),fontSize:P.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:m?"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:m?.6:1},onMouseEnter:Be=>{!m&&(w||on?.colorPrimary)&&(Be.currentTarget.style.backgroundColor=As)},onMouseLeave:Be=>{(w||on?.colorPrimary)&&(Be.currentTarget.style.backgroundColor=vr)},onMouseDown:Be=>{Be.currentTarget.style.transform="scale(0.985)"},onMouseUp:Be=>{Be.currentTarget.style.transform="scale(1)"},children:(0,s.jsx)(Mr,{content:Fe})}),U&&Ne==="buttons"&&(0,s.jsx)(zr,{margin:"0.25rem 0",styleOverride:P.errorBanner,children:U})]}),Oe&&F&&(0,s.jsx)("div",{style:{gridArea:"1 / 1",...W?{animation:W}:{},...Ne==="collapsing"?{pointerEvents:"none"}:{}},children:gi}),V&&vi&&xt&&Mo&&ke&&(0,s.jsx)("div",{style:{gridArea:"1 / 1",...Ao?{animation:Ao}:{},...Ne==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,s.jsxs)("div",{style:{backgroundColor:ya,borderRadius:ha,...to,padding:ga},children:[(0,s.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,s.jsxs)("button",{type:"button","data-testid":"flopay-apm-back-button",onClick:Yn,style:{display:"inline-flex",alignItems:"center",gap:fa?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:[(0,s.jsx)("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:(0,s.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,s.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,s.jsx)(Br,{content:Ee})]}),(0,s.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:P.titleFontSize??"1.05rem",color:eo,paddingRight:80,...P.title},children:`Pay with ${(0,u.getStripeMethodDisplayName)(xt)}`})]}),(0,s.jsx)(Et.Elements,{stripe:ke,options:Mo,children:(0,s.jsx)(Ta,{method:xt,sessionId:e,nonce:t,email:x.email,billingName:[x.firstName,x.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:ue,billingApiUrl:pe,onTokenizedBody:wn,onErrorChange:Ce,onDecline:c,onCancel:Yn,runBeforeButtonClick:On,onButtonClick:ne,isProcessing:m,submitButtonColor:vr,submitButtonBorderRadius:Pt,submitButtonStyle:P.submitButton,errorText:U})},xt)]})})]})]})}return vi&&xt&&Mo&&ke&&V?(0,s.jsxs)("form",{onSubmit:ua,className:D,style:{position:"relative"},children:[(0,s.jsx)(_a,{}),Zt&&(0,s.jsx)(Rn,{status:Zt,errorMessage:U,authorized:An}),(0,s.jsx)("div",{style:{...Ao?{animation:Ao}:{},...Ne==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,s.jsxs)("div",{style:{backgroundColor:ya,borderRadius:ha,...to,padding:ga},children:[(0,s.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,s.jsxs)("button",{type:"button","data-testid":"flopay-apm-back-button-default",onClick:Yn,style:{display:"inline-flex",alignItems:"center",gap:fa?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:[(0,s.jsx)("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:(0,s.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,s.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,s.jsx)(Br,{content:Ee})]}),(0,s.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:P.titleFontSize??"1.05rem",color:eo,paddingRight:80,...P.title},children:`Pay with ${(0,u.getStripeMethodDisplayName)(xt)}`})]}),(0,s.jsx)(Et.Elements,{stripe:ke,options:Mo,children:(0,s.jsx)(Ta,{method:xt,sessionId:e,nonce:t,email:x.email,billingName:[x.firstName,x.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:ue,billingApiUrl:pe,onTokenizedBody:wn,onErrorChange:Ce,onDecline:c,onCancel:Yn,runBeforeButtonClick:On,onButtonClick:ne,isProcessing:m,submitButtonColor:vr,submitButtonBorderRadius:Pt,submitButtonStyle:P.submitButton,errorText:U})},xt)]})})]}):(0,s.jsxs)("form",{onSubmit:ua,className:D,style:{position:"relative"},children:[(0,s.jsx)(_a,{}),Zt&&(0,s.jsx)(Rn,{status:Zt,errorMessage:U,authorized:An}),(0,s.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[hi("flopay-direct-paypal-gate-debug-default"),bi("flopay-stripe-gate-debug-default"),Gr&&L&&(0,s.jsxs)(s.Fragment,{children:[te&&(0,s.jsx)("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."}),(0,s.jsx)(co,{sessionId:e,nonce:t,billingApiUrl:pe,email:x.email,clientId:L.clientId,environment:L.environment,currency:xe.toUpperCase(),isSubscription:ee,providerObjectType:L.providerObjectType,onTokenizedBody:wn,onComplete:i,onErrorChange:Ce,onDecline:c,onTechnicalFailure:_r,onButtonClick:ne,runBeforeButtonClick:On,isProcessing:m,onLoadStateChange:ca,onInitializationStateChange:da,session:A??null,existingOrderId:te?.orderId,debug:St},te?.orderId??"fresh")]}),Jr&&(0,s.jsx)(Et.Elements,{stripe:gn,options:Ka,children:(0,s.jsx)(Ji,{sessionId:e,nonce:t,email:x.email,billingName:Me||void 0,onBuyerIdentityReady:ue,billingApiUrl:pe,onTokenizedBody:wn,onErrorChange:Ce,isProcessing:m,onButtonClick:ne,onDecline:c,onTechnicalFailure:_r,runBeforeButtonClick:On,onLoadStateChange:Xa,placeholderBorderRadius:br})}),Xr&&(0,s.jsx)(Et.Elements,{stripe:ke,options:Ha,children:(0,s.jsx)(Xi,{sessionId:e,nonce:t,email:x.email,billingName:Me||void 0,onBuyerIdentityReady:ue,billingApiUrl:pe,intentKind:X>0?"payment":"setup",expressMethods:Io,onTokenizedBody:wn,onErrorChange:Ce,onButtonClick:ne,onDecline:c,onTechnicalFailure:_r,runBeforeButtonClick:On,onLoadStateChange:Qa,placeholderBorderRadius:br})}),Zr&&(0,s.jsx)(Zi,{sessionId:e,nonce:t,email:x.email,billingName:[x.firstName,x.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:pe,paymentElementMethods:Eo,stripeInstance:ke,paymentElementBaseOptions:la,onTokenizedBody:wn,onErrorChange:Ce,onButtonClick:ne,onDecline:c,runBeforeButtonClick:On,onLoadStateChange:ti,isProcessing:m,submitButtonColor:vr,submitButtonBorderRadius:Pt,submitButtonStyle:P.submitButton,themeId:be,onExpandApm:Nn,expandedApmMethod:xt,buttonAppearance:{backgroundColor:P.cardButton?.backgroundColor,borderColor:P.cardInputBorder,textColor:P.cardButton?.color,borderRadius:br}})]}),Oe&&(ks||ws||Is)&&(0,s.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem",margin:"0.5rem 0 0.75rem",color:"#999",fontSize:"0.85rem"},children:[(0,s.jsx)("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}}),(0,s.jsx)("span",{children:"or pay with card"}),(0,s.jsx)("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}})]}),Oe&&gi]})}var E=require("react/jsx-runtime"),Hr=44,$a="flopay_checkout_saved_payment_resume",ta=new Map,Qo=new Map;function as(e,t){t.settled&&t.consumers===0&&ta.get(e)===t&&ta.delete(e)}function kl(e,t,n){let r=Qo.get(e);if(r&&(!r.sdkGeneratedIdempotencyKey||!t||r.sdkGeneratedIdempotencyKey===t))return r.attempt;let o=n(),i={attempt:o,sdkGeneratedIdempotencyKey:t};Qo.set(e,i);let d=()=>{Qo.get(e)===i&&Qo.delete(e)};return o.then(d,d),o}function go(e){return new Promise(t=>setTimeout(t,e))}function ea(e,t,n){let r=Uo({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:Se.SDK_VERSION,enabled:t!==!1});return r.beginCheckout(n),r}function ho(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function Ba(e,t,n,r,o){let i=ea(e,t,n);i.error({errorCode:r,stage:o,paymentMethodCategory:"unknown",...o==="session_read"?{requestCategory:"session_read"}:{}}),ho(i)}function Il(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 Ua(e){let t=e?.data.paypal?.publishableKey;if(t)return{clientId:t,environment:e?.data.paypal?.environment,providerObjectType:e?.data.paypal?.providerObjectType}}function Fa(e){return!e||e.data.stripe?.publishableKey?!1:!!Ua(e)?.clientId}function ir(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function El(){if(!ir())return null;try{let e=window.sessionStorage.getItem($a);return e?JSON.parse(e):null}catch{return null}}function is(e){if(ir())try{window.sessionStorage.setItem($a,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function Da(){if(ir())try{window.sessionStorage.removeItem($a)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}var ja=":idempotency-key";function ls(e,t){if(!ir())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 Na(e,t,n,r){if(ir())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 qa(e,t){if(ir())try{ls(e,t)&&window.sessionStorage.removeItem(e)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout session cache.",n)}}function cs(e,t){if(!ir())return null;try{let n=window.sessionStorage.getItem(e+ja);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 La(e,t,n){if(ir())try{window.sessionStorage.setItem(e+ja,JSON.stringify({canonicalIdentity:t,idempotencyKey:n}))}catch(r){console.warn("[FloPayCheckout] Failed to persist checkout idempotency key.",r)}}function Oa(e,t){if(qa(e,t),!!ir())try{cs(e,t)&&window.sessionStorage.removeItem(e+ja)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout idempotency key.",n)}}function Rl(){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 ss(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 _l(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 za(e,t){return`${e}:${t.totalAmount??""}:${t.overrideAmount??""}:${t.quantity??1}:${t.currency??""}`}function bo(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=>za(`${o.type??""}:${o.code??o.providerItemId??o.providerPlanId??""}`,o)).sort(),i:e?.items?.map(o=>za(o.code??o.providerItemId??"",o)).sort(),s:e?.subscriptions?.map(o=>za(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 xl(e,t=!1){let n=bo(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 Tl(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=(0,Se.resolveSessionCurrency)(t.currency,t.items,t.subscriptions,t.products);if(!o||e.currency.toUpperCase()!==o.toUpperCase())return!1;let i=(t.products??(0,Se.foldIntoProducts)(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(i.length!==d.length)return!1;for(let g=0;g<i.length;g+=1){let h=i[g],f=d[g];if(h.code!==f.code||h.type!==void 0&&h.type!==f.type||h.quantity!==f.quantity||h.totalAmount!==f.totalAmount||h.overrideAmount!==f.overrideAmount||h.currency!==f.currency)return!1}let c=[...t.couponCodes??[]].sort(),v=[...e.coupons??[]].sort();return c.length===v.length&&c.every((g,h)=>g===v[h])}function na({sessionId:e,nonce:t,createSession:n,billingApiUrl:r,telemetry:o,appearance:i,locale:d,loading:c,error:v,onComplete:g,onError:h,onInstrument:f,onDecline:D,onCountryChange:B,onZipChange:p,showPayPal:C=!0,showStripe:he=!0,enabledPaymentMethods:V,showApplePay:S=!0,showGooglePay:me=!0,debug:H=!1,layout:de,theme:K,buttonsTheme:be,buttonsStyles:$e,cardButtonContent:we,cardBackButtonContent:gt,cardTitleContent:Fe,showSecurityFooter:Ee,onButtonClick:Re,onBeforeButtonClick:oe,enableAVS:ne,cardFieldOrder:O,cardPreFormSlot:ue,avsLayout:We,className:re,initialErrorMessage:Te=null,children:Z,checkoutMode:T,confirmLabel:j,renderConfirmButton:Ae,onSessionCompleted:ye}){let Q=(0,Se.resolveBillingApiUrl)(r),De=(0,I.useMemo)(()=>(0,Se.resolveTheme)(K),[K]),Qe=i??De?.appearance,Ze=n?"embedded_checkout":"standard_checkout",_e=Z?"custom_layout":de==="buttons"?"buttons_layout":"default_layout",[ie,ae]=(0,I.useState)(null),[X,xe]=(0,I.useState)(null),Le=(0,I.useRef)(null),[L,ee]=(0,I.useState)(null),A=(0,I.useRef)(null),[R,rt]=(0,I.useState)(null),St=(0,I.useMemo)(()=>n?bo(n):"",[n]),ve=n?`create:${St}`:`session:${e??""}`,ct=R?.gateways?.stripe?"stripe":R?.gateways?.paypal?"paypal":void 0,st=(0,I.useRef)(new Set),ot=(0,I.useRef)(ve),Ge=(0,I.useRef)(ve);zo(()=>{Ge.current=ve,ot.current!==ve&&(ot.current=ve,st.current.clear())},[ve]);let b=(0,I.useCallback)(N=>{if(Ge.current===ve){if(Ca.has(N.name)){if(st.current.has(N.name))return;st.current.add(N.name)}ze(()=>f?.(N))}},[ve,f]),G=Or(b,ve),et=(0,I.useRef)(!1),dt=(0,I.useCallback)(N=>{if(et.current)return;let M=N.gateway||!ct?N:{...N,gateway:ct};b(M)},[b,ct]);(0,I.useEffect)(()=>{G({class:"lifecycle",name:"checkout.mount"})},[G]);let[Mt,Bt]=(0,I.useState)(e??""),se=e??Mt,Ve=n?"":se,[Wt,wt]=(0,I.useState)(!0),[Ot,xn]=(0,I.useState)(null),[Tn,Qn]=(0,I.useState)("full"),[Gt,sn]=(0,I.useState)(!1),[ln,Ft]=(0,I.useState)(Te),[Pn,bt]=(0,I.useState)(null),[sr,Vt]=(0,I.useState)(null),[lr,Dt]=(0,I.useState)(!1),[$n,at]=(0,I.useState)(void 0),[Rt,_t]=(0,I.useState)(""),[Qt,cn]=(0,I.useState)(!1),[dn,jn]=(0,I.useState)(!1),[Vn,zt]=(0,I.useState)(!1),le=(0,I.useRef)(0),Cn=(0,I.useRef)(void 0),[An,er]=(0,I.useState)("loading"),[yr,Er]=(0,I.useState)(0),Mn=(0,I.useRef)(!1),un=(0,I.useRef)(!1),Oe=(0,I.useRef)(!1),Jt=(0,I.useRef)(null),Nt=(0,I.useMemo)(()=>({checkoutMode:T??Tn,layout:Z?"unknown":de==="buttons"?"buttons":"embedded"}),[T,Z,Tn,de]),Hn=(0,I.useRef)(g);Hn.current=g;let k=(0,I.useRef)(h);k.current=h;let ut=(0,I.useRef)(D);ut.current=D,(0,I.useEffect)(()=>{jt(X)?.setCheckoutContext(Nt),L&&L!==X&&jt(L)?.setCheckoutContext(Nt)},[X,L,Nt]);let Ke=(0,I.useRef)(ye);Ke.current=ye;let pn=(0,I.useCallback)(N=>{er(N),!(N!=="exhausted"||Oe.current)&&(Oe.current=!0,k.current?.(new Se.FloPayError("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),tt=(0,I.useCallback)(()=>{er("retrying"),Er(N=>N+1)},[]);(0,I.useEffect)(()=>{er("loading"),Er(0),Oe.current=!1},[se]),(0,I.useEffect)(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:Se.SDK_VERSION,checkout_type:Ze,checkout_layout:_e,billing_api_url:Q})},[_e,Ze,Q]);let Ut=(0,I.useMemo)(()=>n?bo(n,!0):"",[n]),cr=(0,I.useMemo)(()=>Rt===Ut?$n:void 0,[$n,Rt,Ut]),Kn=(0,I.useMemo)(()=>n?ba(n,cr):void 0,[n,cr]),Sn=T??Kn?.checkoutMode??"full",Xt=(0,I.useMemo)(()=>Kn?{...Kn,checkoutMode:Sn}:void 0,[Kn,Sn]);(0,I.useEffect)(()=>{at(void 0),_t(Ut),Cn.current=void 0,zt(!1)},[Ut]),(0,I.useEffect)(()=>{Ft(Te)},[Te]);let mn=(0,I.useCallback)((N,M,te)=>{ze(()=>{ut.current?.($t(N,M,te))})},[ze]),yn=(0,I.useCallback)(async(N,M)=>{Ft(null),Vt(null),Dt(!1),bt("processing");let te=M?.sessionId??N.id,ce=N.gateways?.stripe?"stripe":N.gateways?.paypal?"paypal":void 0,Ye=Le.current??A.current,pe=jt(Ye),U=Ye?null:ea(Q,o,Nt),w={log:J=>{pe?pe.log(J):U?.log(J)},error:J=>{pe?pe.error(J):U?.error(J)},terminal:J=>{pe?pe.terminal(J):U?.terminal(J)},performance:J=>{pe?pe.performance(J):U?.performance(J)},now:()=>pe?.now()??U?.now()??0,elapsed:J=>pe?.elapsed(J)??Math.max(0,(U?.now()??J)-J)},P=w.now(),Y=!!(M?.initialAutoProcessingError||M?.initialAutoProcessingPending),pt=!1,vt,m=()=>{pt||(pt=!0,Y=!0,vt=w.now(),w.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),w.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},y=!1,x=()=>{y||(y=!0,w.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),w.performance({stage:"processing",durationMs:w.elapsed(P),durationMode:"machine",paymentMethodCategory:"saved"}),vt!==void 0&&w.performance({stage:"recovery",durationMs:w.elapsed(vt),durationMode:"machine",paymentMethodCategory:"saved"}))};w.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),et.current=!0;try{w.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"})}finally{et.current=!1}G({class:"lifecycle",name:"payment.processing.started",provider:ce}),Y&&m();let Me;try{let J=zi(M?.initialAutoProcessingError),q;if(J)m(),J.type==="paypal_redirect_required"&&Jt.current?.publishableKey&&is({sessionId:te,publishableKey:Jt.current.publishableKey,paypalPublishableKey:Jt.current.paypalPublishableKey}),q=await Ho(J,{flopay:Le.current,paypalFlopay:A.current,attempt3DS:M?.attempt3DS,billingApiUrl:Q,sessionId:te,session:N,telemetry:!1}),J.type==="paypal_redirect_required"&&Da();else if(M?.initialAutoProcessingPending){let fe=(await new Ir.PaymentAPI(Q,{telemetry:!1}).waitForCheckoutSessionCompletion(M.initialAutoProcessingPending.sessionId,{initialDelayMs:M.initialAutoProcessingPending.retryAfterMs})).data.session;if(!Dr(fe))throw Do(fe);q=Pr(fe,te)}else{if(M?.initialAutoProcessingError)throw pr(M.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:M.initialAutoProcessingError.checkoutMethod});if(M?.fromCreateSession)return M?.fallbackToFull&&(Qn("full"),ss("full")),!1;{let Xe=await $r({billingApiUrl:Q,sessionId:te,session:N,telemetry:!1});Xe.type==="success"?q=Xe.result:(m(),Xe.type==="paypal_redirect_required"&&Jt.current?.publishableKey&&is({sessionId:te,publishableKey:Jt.current.publishableKey,paypalPublishableKey:Jt.current.paypalPublishableKey}),q=await Ho(Xe,{flopay:Le.current,paypalFlopay:A.current,attempt3DS:M?.attempt3DS,billingApiUrl:Q,sessionId:te,session:N,telemetry:!1}),Xe.type==="paypal_redirect_required"&&Da())}}te&&Ur(te),x(),Y&&(w.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),w.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),w.terminal({outcome:q.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),Dt(q.status==="authorized"),bt("success"),await go(1200),Me=()=>Hn.current?.(q)}catch(J){let q=kr(J),Xe=q.checkoutMethod??yo;Ft(q.message),Vt(q.message),Dt(!1),M?.fallbackToFull&&(w.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),Qn("full"),ss("full")),x();let nt=q.statusCode!==void 0?(0,Se.telemetryStatusClass)(q.statusCode,"unknown"):void 0,fe=nt==="4xx"?{requestCategory:"process_payment",statusClass:nt}:{},Pe=nt===void 0||nt==="4xx";if(Pe&&(q.telemetryOutcome==="payment_declined"||!!(q.declineCode||q.code?.toLowerCase().includes("declin"))))w.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...fe});else if(Pe&&(q.telemetryOutcome==="validation_rejected"||q.type==="validation_error"))w.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...fe});else{let lt=(0,Se.classifyTelemetryFailure)(J,Y?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown"),Lt=q.telemetryRequestCategory??"process_payment";et.current=!0;try{w.error({...lt,...q.telemetryFailureCategory?{failureCategory:q.telemetryFailureCategory}:{},stage:Y?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:Lt})}finally{et.current=!1}G({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:Lt,provider:ce})}return ze(()=>k.current?.(q)),mn(Xe,q,{code:q.code,declineCode:q.declineCode}),bt("error"),await Promise.allSettled([go(1500),M?.ensureProvidersReady?M.ensureProvidersReady():Promise.resolve()]),Y&&(w.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),w.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{x(),U&&ho(U),bt(null),Vt(null)}return ze(Me),!0},[mn,G,ze,kr,Q,o,Nt]);(0,I.useEffect)(()=>{if(typeof window>"u"||un.current)return;let N=new URLSearchParams(window.location.search),M=N.get("payment_intent_client_secret");if(!M)return;let te=El();te&&(un.current=!0,(async()=>{let ce,Ye=0;Ft(null),Vt(null),bt("processing"),sn(!0);try{if(N.get("redirect_status")==="failed")throw Object.assign(new Se.FloPayError("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:pe,paypalFlopay:U}=await Yo({publishableKey:te.publishableKey,paypalPublishableKey:te.paypalPublishableKey,billingApiUrl:Q,locale:d,telemetry:o});ce=jt(U??pe),Ye=ce?.now()??0,ce?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),ce?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let w=(U??pe)?.getRawProvider();if(!w)throw Object.assign(new Se.FloPayError("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:P,error:Y}=await w.retrievePaymentIntent(M);if(Y)throw Object.assign(new Se.FloPayError(Y.message??"Failed to retrieve PayPal payment status.","api_error",{code:Y.code}),{checkoutMethod:"paypal"});let pt=Ii(P?.status);if(!P||pt==="failed")throw Object.assign(new Se.FloPayError("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let vt=typeof P.payment_method=="string"?P.payment_method:P.payment_method?.id,m=pt;if(te.sessionId){let Me=(await new Ir.PaymentAPI(Q,{telemetry:!1}).getUnifiedCheckoutSession(te.sessionId)).data.session;if(Me&&Me.status!=="complete"){let J=await $r({billingApiUrl:Q,sessionId:te.sessionId,session:Me,telemetry:!1,tokenizedData:{id:vt??P.id,type:"card",threeDSecureActionResultTokenId:P.id,isPaypal:!0}});if(J.type!=="success")throw Object.assign(new Se.FloPayError("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});m=J.result.status}}te.sessionId&&Ur(te.sessionId),ce?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),ce?.performance({stage:"redirect_resume",durationMs:ce.elapsed(Ye),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),ce?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),bt("success"),await go(1200),ze(()=>Hn.current?.({status:m,paymentIntentId:P.id,paymentMethodId:vt,checkoutMethod:"paypal"}))}catch(pe){let U=kr(pe),w=U.checkoutMethod??"paypal",P=!!(U.declineCode||U.code?.toLowerCase().includes("declin"));if(ce)ce.performance({stage:"redirect_resume",durationMs:ce.elapsed(Ye),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),P?ce.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):ce.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(P){let Y=ea(Q,o,Nt);Y.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),ho(Y)}else Ba(Q,o,Nt,"REDIRECT_RESUME_FAILED","redirect_resume");Ft(U.message),Vt(U.message),ze(()=>k.current?.(U)),mn(w,U,{code:U.code,declineCode:U.declineCode}),bt("error"),await go(1500)}finally{Da(),Rl(),bt(null),Vt(null),sn(!1)}})())},[mn,ze,d,kr,Q,o]);let Ne=(0,I.useRef)(null),kt=(0,I.useMemo)(()=>Xt?bo(Xt):"",[Xt]),xt=(0,I.useRef)(Xt);xt.current=Xt,(0,I.useEffect)(()=>{Bt(e??"")},[e]),(0,I.useEffect)(()=>{Mn.current=!1,Ft(Te),Vt(null),Dt(!1),bt(null)},[kt,Te,e]);async function Bn(N,M,te){let ce=ea(Q,o,Nt),Ye=new Ir.PaymentAPI(Q,{telemetry:!1}),pe=!1;try{let U=N.idempotencyKey!==void 0?(0,Se.resolveIdempotencyKey)(N.idempotencyKey):void 0,w=ls(M,te),P=cs(M,te);w?.canonicalIdentity===te&&P&&P.canonicalIdentity===void 0&&(La(M,te,P.idempotencyKey),P={...P,canonicalIdentity:te});let Y=U??(P?.canonicalIdentity===te?P.idempotencyKey:void 0),pt,vt=!1;ce.log({name:w?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let m=w?.sid??null,y=null,x,Me,J=!1;if(m)try{y=await Ye.getUnifiedCheckoutSession(m,w?.nonce),w&&w.canonicalIdentity===void 0&&(Tl(y.data.session,N)?(Na(M,te,m,w.nonce??y.data.session?.clientSecret),P&&P.canonicalIdentity===void 0&&(La(M,te,P.idempotencyKey),Y??(Y=P.idempotencyKey))):(Oa(M,te),P=null,Y=U,m=null,y=null));let q=y?.data.session?.status;if(m&&y&&q==="complete"){if(wa(m))return{sid:m,result:y};Oa(M,te),m=null,y=null,vt=!0}}catch{ce.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),w?.canonicalIdentity===void 0?(Oa(M,te),Y=U):qa(M,te),m=null}if(!m){!U&&(vt||!Y)&&(Y=(0,Se.resolveIdempotencyKey)(),pt=Y),Y&&La(M,te,Y);let q=ce.now(),Xe=0;ce.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let nt={...N,idempotencyKey:Y,avsCheck:!!ne,avsConfig:typeof ne=="object"?ne:void 0,checkoutType:"embedded_checkout",checkoutLayout:Z?"custom_layout":de==="buttons"?"buttons_layout":"default_layout"};Object.defineProperty(nt,Ir.SESSION_CREATE_TELEMETRY,{configurable:!1,enumerable:!1,value:{onAttempt:z=>{Xe=Math.max(Xe,z)}}});let fe=()=>{ce.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:"2xx"}),ce.performance({stage:"session_create",durationMs:ce.now()-q,durationMode:"machine",requestCategory:"session_create",attempt:Xe,statusClass:"2xx"})},Pe=z=>{let ge=(0,Se.classifyTelemetryFailure)(z,"CHECKOUT_SESSION_CREATE_FAILED","unknown");ce.performance({stage:"session_create",durationMs:ce.now()-q,durationMode:"machine",requestCategory:"session_create",attempt:Xe,statusClass:ge.statusClass}),z instanceof Se.FloPayError&&z.type==="validation_error"?ce.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown"}):ge.statusClass==="4xx"?ce.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create",statusClass:"4xx"}):(ce.error({...ge,stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create"}),G({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_create"}))};try{if((0,Se.isDetachedSessionEligible)(nt)){let z=await Ye.createDetachedSession(nt);z.claimed.catch(()=>{}),y=z.shell,m=z.sessionId,Me=z.claim,J=!nt.account.email?.trim(),x=z.claimed.then(ge=>{let lt=ge.data.session?.id??z.sessionId;return lt&&Na(M,te,lt,ge.data.session?.clientSecret??z.nonce),fe(),ge},ge=>{throw qa(M,te),Pe(ge),ge}).finally(()=>ho(ce)),x.catch(()=>{}),pe=!0,ce.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),ce.performance({stage:"session_shell",durationMs:ce.now()-q,durationMode:"machine",requestCategory:"session_create",attempt:Xe,statusClass:"2xx",paymentMethodCategory:"card"})}else y=await Ye.createAndFetchSession(nt),fe()}catch(z){throw Pe(z),z}m=y.data.session?.id??m??"",m&&!x&&Na(M,te,m,y.data.session?.clientSecret)}return{sid:m??"",result:y,sdkGeneratedIdempotencyKey:pt,...x?{claimed:x}:{},...Me?{claim:Me}:{},...J?{claimRequiresIdentity:!0}:{}}}finally{pe||ho(ce)}}let fn=(0,I.useCallback)(async(N,M)=>{let te=xt.current;if(!te)throw new Se.FloPayError("createSession is required to bootstrap checkout.","validation_error");let ce=ba(te,N),Ye=bo(ce),pe=xl(ce),U=ta.get(Ye);if(!U){let Y={canonicalIdentity:Ye,promise:Bn(ce,pe,Ye),consumers:0,settled:!1};U=Y,ta.set(Ye,Y);let pt=()=>{Y.settled=!0,as(Ye,Y)};Y.promise.then(pt,pt)}U.consumers+=1;let w=!1,P=()=>{w||(w=!0,U.consumers-=1,as(Ye,U))};M?.(P);try{let Y=await U.promise;Ne.current=Ye,N&&(_t(Ut),at(nt=>Si(nt,N)));let{sid:pt,result:vt,claimed:m,claim:y,claimRequiresIdentity:x}=Y;if(Cn.current=y,zt(x===!0),ae(vt),vt.data.session&&rt(vt.data.session),pt&&Bt(pt),m){le.current+=1;let nt=le.current;jn(!0),m.then(fe=>{le.current===nt&&(ae(fe),fe.data.session&&rt(fe.data.session),jn(!1),zt(!1))},fe=>{le.current===nt&&(jn(!1),zt(!1),xn(fe instanceof Se.FloPayError?fe:new Se.FloPayError(fe instanceof Error?fe.message:"Failed to create session","api_error")))})}else le.current+=1,jn(!1),zt(!1);let{publishableKey:Me,paypalPublishableKey:J}=Ko(vt),{flopay:q,paypalFlopay:Xe}=await Yo({publishableKey:Me,paypalPublishableKey:J,billingApiUrl:Q,locale:d,telemetry:o});return Le.current=q,xe(q),A.current=Xe,ee(Xe),wt(!1),Y}catch(Y){throw Ne.current===Ye&&(Ne.current=null),Y}finally{M||P()}},[Ut,d,Q,o,Nt]),Fn=(0,I.useRef)(yn);Fn.current=yn;let Dn=(0,I.useRef)(fn);Dn.current=fn;let qt=(0,I.useCallback)(async N=>{if(!_l(N)||Qt)return{sessionId:Mt,session:R};cn(!0);try{let M=await fn(N);return{sessionId:M.sid,session:M.result.data.session??null}}finally{cn(!1)}},[fn,Qt,Mt,R]),nn=(0,I.useCallback)(async N=>{let M=Cn.current;M&&await M(N)},[]);(0,I.useEffect)(()=>{let N=!1,M;if(xn(null),kt){let Ye=xt.current;return Qn(Sn),wt(!1),Ne.current===kt?()=>{N=!0}:(rt(wi(Ye,T)),(async()=>{let pe=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),U=Sn==="auto"&&!Mn.current&&!pe;U&&(Ft(null),Vt(null),bt("processing"));try{let w=await Dn.current(void 0,vt=>{M=vt}),P=w.result.data.session??null;Jt.current=Ko(w.result);let Y=Fa(w.result),pt=wa(w.sid||P?.id);if(!N&&U&&P&&!Y&&!pt){Mn.current=!0,await kl(kt,w.sdkGeneratedIdempotencyKey,()=>Fn.current(P,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:w.result.autoProcessingError,initialAutoProcessingPending:w.result.autoProcessingPending,autoProcessingAttempted:w.result.autoProcessingAttempted,sessionId:w.sid||P.id}));return}!N&&U&&((Y||pt)&&(Mn.current=!0),bt(null),Vt(null))}catch(w){if(N)return;let P=w instanceof Se.FloPayError||typeof w=="object"&&w!==null&&"code"in w?w.code:void 0;if(U&&P==="session_auto_completed"){Mn.current=!0,bt("success"),await go(1200),N||(ze(()=>{Hn.current?.({status:"succeeded"})}),bt(null),Vt(null));return}U&&(bt(null),Vt(null));let Y=w instanceof Se.FloPayError?w:new Se.FloPayError(w instanceof Error?w.message:"Failed to create session","api_error");xn(Y)}finally{M?.(),M=void 0}})(),()=>{N=!0,M?.()})}wt(!0);async function te(){let Ye=!1;try{let U=await new Ir.PaymentAPI(Q,{telemetry:!1}).getUnifiedCheckoutSession(se,t);if(N)return;ae(U);let w=U.data.session??null;if(rt(w),!w)throw new Se.FloPayError("No session data returned","api_error");let P=w.checkoutMode;if(P==="setup")throw new Se.FloPayError("This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.","validation_error",{code:"InvalidCardSetupSurface",param:"sessionId"});if(w.status==="authorized"){wt(!1),ze(()=>{Hn.current?.(Pr(w,se)),Ke.current?.(w.successUrl??"")});return}if(w.status==="complete"){wt(!1),ze(()=>{Ke.current?.(w.successUrl??"")});return}if(w.status==="expired")throw Fo(w);Ye=!0;let Y=T??P??"full";Qn(Y);let pt=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),vt=Fa(U);if(Y==="auto"&&!Mn.current&&!pt&&!vt){Mn.current=!0;let m=ce(U);try{if(await Fn.current(w,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>m,sessionId:se||w.id}),N)return;await m,N||wt(!1);return}catch{if(N)return;await m,N||wt(!1);return}}await ce(U),N||wt(!1)}catch(pe){if(N)return;Ye&&G({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"}),pe instanceof Se.FloPayError?!Ye&&!Il(pe)&&Ba(Q,o,Nt,"NETWORK_REQUEST_FAILED","session_read"):Ba(Q,o,Nt,"INTERNAL_SDK_ERROR","checkout_mount");let U=pe instanceof Se.FloPayError?pe:new Se.FloPayError(pe instanceof Error?pe.message:"Failed to initialize checkout","api_error");xn(U),wt(!1)}}async function ce(Ye){let{publishableKey:pe,paypalPublishableKey:U}=Ko(Ye);Jt.current={publishableKey:pe,paypalPublishableKey:U};let{flopay:w,paypalFlopay:P}=await Yo({publishableKey:pe,paypalPublishableKey:U,billingApiUrl:Q,locale:d,telemetry:o});Le.current=w,xe(w),A.current=P,ee(P)}return te(),()=>{N=!0}},[T,kt,Sn,Ve,ze,t]);let rn=(0,I.useCallback)(async()=>{if(!(Gt||!R)){sn(!0),Ft(null);try{await yn(R,{attempt3DS:!0,fallbackToFull:!0,sessionId:se||R.id})}finally{sn(!1)}}},[se,Gt,yn,R]),tr=Ua(ie),Rr=Fa(ie),Nn=(0,I.useMemo)(()=>{if(!(!ie||!R||!ie.data.stripe?.publishableKey))return{billingApiUrl:Q}},[ie,R,Q]),Yn=!!(n&&!Z&&de==="buttons"&&oe&&Sn==="full"),Zt=(0,I.useMemo)(()=>({session:R,loading:Wt,error:Ot,checkoutMode:Tn,inlineSessionDraft:Xt,applyInlineSessionPatch:Yn?qt:void 0,inlineSessionPatchProcessing:Qt,claimPending:dn,claimRequiresIdentity:Vn}),[R,Wt,Ot,Tn,Xt,Yn,qt,Qt,dn,Vn]),it=!!n&&de==="buttons"&&!Rr&&(!X||!Nn),Ht=Pn?(0,E.jsx)(Rn,{status:Pn,errorMessage:sr,authorized:lr}):null;if(Wt){if(c)return(0,E.jsxs)(E.Fragment,{children:[c,Ht]});if(de==="buttons"){let N=De?.buttonsLayout?.cardButton?.borderRadius??De?.appearance.variables?.borderRadius??8,M=te=>(0,E.jsx)("div",{style:{height:te,borderRadius:N,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return(0,E.jsxs)(E.Fragment,{children:[(0,E.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[C&&M(Hr),he&&(S||me)&&M(Hr),he&&M(Hr),(0,E.jsx)("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),Ht]})}return(0,E.jsxs)(E.Fragment,{children:[(0,E.jsxs)("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[(0,E.jsx)("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),(0,E.jsx)("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),Ht]})}return Ot?v?(0,E.jsx)(zn.Provider,{value:Zt,children:v(Ot)}):(0,E.jsx)(zn.Provider,{value:Zt,children:(0,E.jsx)("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:Ot.message})}):it?(0,E.jsxs)(E.Fragment,{children:[(0,E.jsx)(zn.Provider,{value:Zt,children:(0,E.jsx)(Ml,{onButtonClick:Re,showPayPal:C,showStripe:he,showApplePay:S,showGooglePay:me,theme:K,buttonsTheme:be,buttonsStyles:$e,cardButtonContent:we,cardBackButtonContent:gt,cardTitleContent:Fe})}),Ht]}):Rr&&R&&tr?(0,E.jsxs)(E.Fragment,{children:[(0,E.jsx)(zn.Provider,{value:Zt,children:(0,E.jsxs)("div",{className:re,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[ln&&(0,E.jsx)(zr,{icon:!1,children:ln}),An==="retrying"&&(0,E.jsx)("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),An==="exhausted"&&(0,E.jsxs)("div",{role:"alert",children:[(0,E.jsx)("div",{children:"PayPal is temporarily unavailable. Please try again."}),(0,E.jsx)("button",{type:"button",onClick:tt,children:"Retry PayPal"})]}),An!=="exhausted"&&(0,E.jsx)("div",{"aria-hidden":An==="retrying"?!0:void 0,style:An==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:(0,E.jsx)(Ni,{sessionId:se,nonce:R.clientSecret||void 0,billingApiUrl:Q,email:R.customer?.email,clientId:tr.clientId,environment:tr.environment,currency:(R.currency??"usd").toUpperCase(),isSubscription:R.mode==="subscription",providerObjectType:tr.providerObjectType,onComplete:g,onErrorChange:Ft,onDecline:D,onButtonClick:Re,onInitializationStateChange:pn,allowAutomaticRetry:yr===0,session:R,telemetry:o,telemetryContext:Nt,onInstrument:dt,debug:H},`${ve}:paypal-init-${yr}`)})]})}),Ht]}):!X||!Nn?(0,E.jsx)(E.Fragment,{children:Ht}):Tn==="confirm"?(0,E.jsxs)(E.Fragment,{children:[(0,E.jsx)(zn.Provider,{value:Zt,children:(0,E.jsx)(po,{flopay:X,paypalFlopay:L,options:Nn,onInstrument:dt,children:(0,E.jsxs)("div",{className:re,children:[ln&&(0,E.jsx)("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:ln}),Ae?Ae({onConfirm:rn,isProcessing:Gt}):(0,E.jsx)("button",{type:"button",onClick:rn,disabled:Gt,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:Gt?"not-allowed":"pointer",opacity:Gt?.6:1},children:Gt?"Processing...":j??"Confirm Purchase"})]})},ve)}),Ht]}):(0,E.jsxs)(E.Fragment,{children:[(0,E.jsx)(zn.Provider,{value:Zt,children:(0,E.jsx)(po,{flopay:X,paypalFlopay:L,options:Nn,onInstrument:dt,children:Z?(0,E.jsxs)(E.Fragment,{children:[ln&&(0,E.jsx)("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:ln}),(0,E.jsx)(Al,{sessionId:se,nonce:R?.clientSecret||void 0,billingApiUrl:Q,session:R,children:Z})]}):(0,E.jsx)(Zo,{sessionId:se,nonce:R?.clientSecret||void 0,email:R?.customer?.email||Xt?.account?.email,userId:R?.customer?.id||Xt?.account?.userId,firstName:R?.customer?.firstName||Xt?.account?.firstName,lastName:R?.customer?.lastName||Xt?.account?.lastName,totalAmount:R?Math.round((0,Se.buildCheckoutDisplayData)(R).total*100):0,currency:R?.currency?.toLowerCase()??"usd",onComplete:g,onError:h,onDecline:D,error:ln,onErrorChange:Ft,showPayPal:C,showStripe:he,enabledPaymentMethods:V??ie?.data.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:ie?.data.stripe?.enabledPaymentMethodCountries,showApplePay:S,showGooglePay:me,layout:de,theme:K,buttonsTheme:be,buttonsStyles:$e,appearance:Qe,cardButtonContent:we,cardBackButtonContent:gt,cardTitleContent:Fe,onButtonClick:Re,onBeforeButtonClick:oe,onBuyerIdentityReady:nn,enableAVS:ne,...O?{cardFieldOrder:O}:{},...ue?{cardPreFormSlot:ue}:{},avsLayout:We,country:R?.customer?.country,city:R?.customer?.city,state:R?.customer?.state,onCountryChange:B,onZipChange:p,avsCheck:!!ne,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:Z?"custom_layout":de==="buttons"?"buttons_layout":"default_layout",className:re,directPaypal:Ua(ie),isSubscription:R?.mode==="subscription",session:R,dataAttachmentPending:dn,dataAttachmentRequiresIdentity:Vn,debug:H})},ve)}),Ht]})}function Al({sessionId:e,nonce:t,billingApiUrl:n,session:r,children:o}){return(0,E.jsx)(E.Fragment,{children:I.default.Children.map(o,i=>{if(!I.default.isValidElement(i))return i;let d=i.props,c={};return d.sessionId||(c.sessionId=e),!d.nonce&&t&&(c.nonce=t),d.billingApiUrl||(c.billingApiUrl=n),r?.customer&&(d.email||(c.email=r.customer.email),d.userId||(c.userId=r.customer.id),d.firstName||(c.firstName=r.customer.firstName),d.lastName||(c.lastName=r.customer.lastName)),Object.keys(c).length===0?i:I.default.cloneElement(i,c)})})}function Ml({onButtonClick:e,showPayPal:t,showStripe:n=!0,showApplePay:r,showGooglePay:o,theme:i,buttonsTheme:d,buttonsStyles:c,cardButtonContent:v,cardBackButtonContent:g,cardTitleContent:h}){let[f,D]=(0,I.useState)(!1),B=(0,I.useMemo)(()=>(0,Se.resolveTheme)(i),[i]),p=(0,I.useMemo)(()=>{let S=B?.buttonsLayout??(0,Se.resolveButtonsLayoutTheme)(d);return c?{...S,...c,cardButton:{...S.cardButton,...c.cardButton},cardFormContainer:{...S.cardFormContainer,...c.cardFormContainer},backButton:{...S.backButton,...c.backButton},backButtonIcon:{...S.backButtonIcon,...c.backButtonIcon},submitButton:{...S.submitButton,...c.submitButton},title:{...S.title,...c.title}}:S},[B,d,c]),C=B?.buttonsLayout?.cardButton?.borderRadius??B?.appearance.variables?.borderRadius??8,he=S=>(0,E.jsx)("div",{style:{height:S,borderRadius:C,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),V=v===void 0?{boxSizing:"border-box",height:Hr,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(f){let S=p.cardInputBorder??"#e5e7eb",me=p.cardInputBackground??"white",H=Ar(g),de=Ar(h);return(0,E.jsxs)("div",{style:{backgroundColor:p.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",...p.cardFormContainer},children:[(0,E.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,E.jsxs)("button",{type:"button",onClick:()=>D(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:H?0:"0.5rem",background:"none",border:"none",color:"#4b5563",fontSize:"0.85rem",fontWeight:500,padding:0,flexShrink:0,opacity:1,cursor:"pointer",...p.backButton},children:[(0,E.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...p.backButtonIcon},children:(0,E.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,E.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,E.jsx)(Br,{content:g})]}),de?(0,E.jsx)("div",{style:{flex:1}}):(0,E.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...p.title},children:(0,E.jsx)(oo,{content:h})})]}),(0,E.jsx)("div",{style:{backgroundColor:me,border:`1px solid ${S}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:(0,E.jsx)("div",{style:{width:"60%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,E.jsxs)("div",{style:{display:"flex"},children:[(0,E.jsx)("div",{style:{flex:1,backgroundColor:me,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${S}`,borderLeft:`1px solid ${S}`,borderBottomLeftRadius:8,padding:12,height:45},children:(0,E.jsx)("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,E.jsx)("div",{style:{flex:1,backgroundColor:me,borderTop:"none",borderRight:`1px solid ${S}`,borderBottom:`1px solid ${S}`,borderLeft:`1px solid ${S}`,borderBottomRightRadius:8,padding:12,height:45},children:(0,E.jsx)("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),(0,E.jsx)("div",{style:{backgroundColor:me,border:`1px solid ${S}`,borderRadius:8,marginTop:8,padding:12,height:45},children:(0,E.jsx)("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,E.jsx)("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",...p.submitButton,opacity:.5}}),(0,E.jsx)("style",{children:`
40
+ `)}):null,vi=De==="apm-expanding"||De==="apm-form"||De==="apm-collapsing",Ao=De==="apm-expanding"?`flopay-card-enter ${$t}ms cubic-bezier(0, 0, 0.2, 1) both`:De==="apm-collapsing"?`flopay-card-exit ${$t}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0,Mo=xt?{...la,paymentMethodTypes:[xt]}:null;if(K==="buttons"){let l=De==="buttons"||De==="expanding"||De==="apm-expanding",F=De==="expanding"||De==="card"||De==="collapsing",$=Fe===void 0?{boxSizing:"border-box",height:Go,padding:"0 1rem"}:{padding:"0.9rem 1rem"},Ie=De==="expanding"||De==="apm-expanding"?`flopay-buttons-exit ${$t}ms cubic-bezier(0.4, 0, 0.2, 1) both`:De==="collapsing"||De==="apm-collapsing"?`flopay-buttons-enter ${$t}ms cubic-bezier(0, 0, 0.2, 1) both`:void 0,W=De==="expanding"?`flopay-card-enter ${$t}ms cubic-bezier(0, 0, 0.2, 1) both`:De==="collapsing"?`flopay-card-exit ${$t}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0;return(0,s.jsxs)("form",{onSubmit:ua,className:N,style:{position:"relative"},children:[(0,s.jsx)(_a,{}),Zt&&(0,s.jsx)(Rn,{status:Zt,errorMessage:U,authorized:An}),(0,s.jsxs)("div",{style:{display:"grid"},children:[(0,s.jsxs)("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!l&&!Ie?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!l&&!Ie?fl:{},...Ie?{animation:Ie,pointerEvents:"none"}:{}},children:[hi("flopay-direct-paypal-gate-debug"),bi("flopay-stripe-gate-debug"),Gr&&L&&(0,s.jsxs)(s.Fragment,{children:[te&&(0,s.jsx)("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."}),(0,s.jsx)(co,{sessionId:e,nonce:t,billingApiUrl:pe,email:x.email,billingName:Te||void 0,onBuyerIdentityReady:ue,clientId:L.clientId,environment:L.environment,currency:xe.toUpperCase(),isSubscription:ee,providerObjectType:L.providerObjectType,onTokenizedBody:wn,onComplete:i,onErrorChange:Ce,onDecline:c,onTechnicalFailure:_r,onButtonClick:ne,runBeforeButtonClick:On,isProcessing:m,onLoadStateChange:ca,onInitializationStateChange:da,session:A??null,existingOrderId:te?.orderId,debug:St},te?.orderId??"fresh")]}),Jr&&(0,s.jsx)(Et.Elements,{stripe:gn,options:Ka,children:(0,s.jsx)(Ji,{sessionId:e,nonce:t,email:x.email,billingName:Te||void 0,onBuyerIdentityReady:ue,billingApiUrl:pe,onTokenizedBody:wn,onErrorChange:Ce,isProcessing:m,onButtonClick:ne,onDecline:c,onTechnicalFailure:_r,runBeforeButtonClick:On,onLoadStateChange:Xa,placeholderBorderRadius:br})}),Xr?(0,s.jsx)(Et.Elements,{stripe:ke,options:Ha,children:(0,s.jsx)(Xi,{sessionId:e,nonce:t,email:x.email,billingName:Te||void 0,onBuyerIdentityReady:ue,billingApiUrl:pe,intentKind:X>0?"payment":"setup",expressMethods:Io,onTokenizedBody:wn,onErrorChange:Ce,onButtonClick:ne,onDecline:c,onTechnicalFailure:_r,runBeforeButtonClick:On,onLoadStateChange:Qa,placeholderBorderRadius:br})}):oi?(0,s.jsx)("div",{style:{height:Go,borderRadius:br,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,Zr&&(0,s.jsx)(Zi,{sessionId:e,nonce:t,email:x.email,billingName:[x.firstName,x.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:ue,billingApiUrl:pe,paymentElementMethods:Eo,stripeInstance:ke,paymentElementBaseOptions:la,onTokenizedBody:wn,onErrorChange:Ce,onButtonClick:ne,onDecline:c,runBeforeButtonClick:On,onLoadStateChange:ti,isProcessing:m,submitButtonColor:vr,submitButtonBorderRadius:Pt,submitButtonStyle:P.submitButton,onExpandApm:Dn,expandedApmMethod:xt,themeId:be,buttonAppearance:{backgroundColor:P.cardButton?.backgroundColor,borderColor:P.cardInputBorder,textColor:P.cardButton?.color,borderRadius:br}}),Oe&&(0,s.jsx)("button",{type:"button",onClick:async()=>{m||!(await On("card")).proceed||(ne?.("card"),tr())},disabled:m,style:{width:"100%",...$,...P.cardButton,...Ma({themeBundle:w,resolvedPrimaryColor:vr,resolvedBorderRadius:Pt,submitButtonStyle:P.submitButton,explicitPrimaryColor:on?.colorPrimary}),fontSize:P.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:m?"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:m?.6:1},onMouseEnter:Be=>{!m&&(w||on?.colorPrimary)&&(Be.currentTarget.style.backgroundColor=As)},onMouseLeave:Be=>{(w||on?.colorPrimary)&&(Be.currentTarget.style.backgroundColor=vr)},onMouseDown:Be=>{Be.currentTarget.style.transform="scale(0.985)"},onMouseUp:Be=>{Be.currentTarget.style.transform="scale(1)"},children:(0,s.jsx)(Mr,{content:Fe})}),U&&De==="buttons"&&(0,s.jsx)(zr,{margin:"0.25rem 0",styleOverride:P.errorBanner,children:U})]}),Oe&&F&&(0,s.jsx)("div",{style:{gridArea:"1 / 1",...W?{animation:W}:{},...De==="collapsing"?{pointerEvents:"none"}:{}},children:gi}),V&&vi&&xt&&Mo&&ke&&(0,s.jsx)("div",{style:{gridArea:"1 / 1",...Ao?{animation:Ao}:{},...De==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,s.jsxs)("div",{style:{backgroundColor:ya,borderRadius:ha,...to,padding:ga},children:[(0,s.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,s.jsxs)("button",{type:"button","data-testid":"flopay-apm-back-button",onClick:Yn,style:{display:"inline-flex",alignItems:"center",gap:fa?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:[(0,s.jsx)("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:(0,s.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,s.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,s.jsx)(Br,{content:Ee})]}),(0,s.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:P.titleFontSize??"1.05rem",color:eo,paddingRight:80,...P.title},children:`Pay with ${(0,u.getStripeMethodDisplayName)(xt)}`})]}),(0,s.jsx)(Et.Elements,{stripe:ke,options:Mo,children:(0,s.jsx)(Ta,{method:xt,sessionId:e,nonce:t,email:x.email,billingName:[x.firstName,x.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:ue,billingApiUrl:pe,onTokenizedBody:wn,onErrorChange:Ce,onDecline:c,onCancel:Yn,runBeforeButtonClick:On,onButtonClick:ne,isProcessing:m,submitButtonColor:vr,submitButtonBorderRadius:Pt,submitButtonStyle:P.submitButton,errorText:U})},xt)]})})]})]})}return vi&&xt&&Mo&&ke&&V?(0,s.jsxs)("form",{onSubmit:ua,className:N,style:{position:"relative"},children:[(0,s.jsx)(_a,{}),Zt&&(0,s.jsx)(Rn,{status:Zt,errorMessage:U,authorized:An}),(0,s.jsx)("div",{style:{...Ao?{animation:Ao}:{},...De==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,s.jsxs)("div",{style:{backgroundColor:ya,borderRadius:ha,...to,padding:ga},children:[(0,s.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,s.jsxs)("button",{type:"button","data-testid":"flopay-apm-back-button-default",onClick:Yn,style:{display:"inline-flex",alignItems:"center",gap:fa?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:[(0,s.jsx)("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:(0,s.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,s.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,s.jsx)(Br,{content:Ee})]}),(0,s.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:P.titleFontSize??"1.05rem",color:eo,paddingRight:80,...P.title},children:`Pay with ${(0,u.getStripeMethodDisplayName)(xt)}`})]}),(0,s.jsx)(Et.Elements,{stripe:ke,options:Mo,children:(0,s.jsx)(Ta,{method:xt,sessionId:e,nonce:t,email:x.email,billingName:[x.firstName,x.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:ue,billingApiUrl:pe,onTokenizedBody:wn,onErrorChange:Ce,onDecline:c,onCancel:Yn,runBeforeButtonClick:On,onButtonClick:ne,isProcessing:m,submitButtonColor:vr,submitButtonBorderRadius:Pt,submitButtonStyle:P.submitButton,errorText:U})},xt)]})})]}):(0,s.jsxs)("form",{onSubmit:ua,className:N,style:{position:"relative"},children:[(0,s.jsx)(_a,{}),Zt&&(0,s.jsx)(Rn,{status:Zt,errorMessage:U,authorized:An}),(0,s.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[hi("flopay-direct-paypal-gate-debug-default"),bi("flopay-stripe-gate-debug-default"),Gr&&L&&(0,s.jsxs)(s.Fragment,{children:[te&&(0,s.jsx)("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."}),(0,s.jsx)(co,{sessionId:e,nonce:t,billingApiUrl:pe,email:x.email,billingName:Te||void 0,onBuyerIdentityReady:ue,clientId:L.clientId,environment:L.environment,currency:xe.toUpperCase(),isSubscription:ee,providerObjectType:L.providerObjectType,onTokenizedBody:wn,onComplete:i,onErrorChange:Ce,onDecline:c,onTechnicalFailure:_r,onButtonClick:ne,runBeforeButtonClick:On,isProcessing:m,onLoadStateChange:ca,onInitializationStateChange:da,session:A??null,existingOrderId:te?.orderId,debug:St},te?.orderId??"fresh")]}),Jr&&(0,s.jsx)(Et.Elements,{stripe:gn,options:Ka,children:(0,s.jsx)(Ji,{sessionId:e,nonce:t,email:x.email,billingName:Te||void 0,onBuyerIdentityReady:ue,billingApiUrl:pe,onTokenizedBody:wn,onErrorChange:Ce,isProcessing:m,onButtonClick:ne,onDecline:c,onTechnicalFailure:_r,runBeforeButtonClick:On,onLoadStateChange:Xa,placeholderBorderRadius:br})}),Xr&&(0,s.jsx)(Et.Elements,{stripe:ke,options:Ha,children:(0,s.jsx)(Xi,{sessionId:e,nonce:t,email:x.email,billingName:Te||void 0,onBuyerIdentityReady:ue,billingApiUrl:pe,intentKind:X>0?"payment":"setup",expressMethods:Io,onTokenizedBody:wn,onErrorChange:Ce,onButtonClick:ne,onDecline:c,onTechnicalFailure:_r,runBeforeButtonClick:On,onLoadStateChange:Qa,placeholderBorderRadius:br})}),Zr&&(0,s.jsx)(Zi,{sessionId:e,nonce:t,email:x.email,billingName:[x.firstName,x.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:pe,paymentElementMethods:Eo,stripeInstance:ke,paymentElementBaseOptions:la,onTokenizedBody:wn,onErrorChange:Ce,onButtonClick:ne,onDecline:c,runBeforeButtonClick:On,onLoadStateChange:ti,isProcessing:m,submitButtonColor:vr,submitButtonBorderRadius:Pt,submitButtonStyle:P.submitButton,themeId:be,onExpandApm:Dn,expandedApmMethod:xt,buttonAppearance:{backgroundColor:P.cardButton?.backgroundColor,borderColor:P.cardInputBorder,textColor:P.cardButton?.color,borderRadius:br}})]}),Oe&&(ks||ws||Is)&&(0,s.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem",margin:"0.5rem 0 0.75rem",color:"#999",fontSize:"0.85rem"},children:[(0,s.jsx)("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}}),(0,s.jsx)("span",{children:"or pay with card"}),(0,s.jsx)("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}})]}),Oe&&gi]})}var R=require("react/jsx-runtime"),Hr=44,$a="flopay_checkout_saved_payment_resume",ta=new Map,Qo=new Map;function as(e,t){t.settled&&t.consumers===0&&ta.get(e)===t&&ta.delete(e)}function kl(e,t,n){let r=Qo.get(e);if(r&&(!r.sdkGeneratedIdempotencyKey||!t||r.sdkGeneratedIdempotencyKey===t))return r.attempt;let o=n(),i={attempt:o,sdkGeneratedIdempotencyKey:t};Qo.set(e,i);let d=()=>{Qo.get(e)===i&&Qo.delete(e)};return o.then(d,d),o}function go(e){return new Promise(t=>setTimeout(t,e))}function ea(e,t,n){let r=Uo({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:Se.SDK_VERSION,enabled:t!==!1});return r.beginCheckout(n),r}function ho(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function Ba(e,t,n,r,o){let i=ea(e,t,n);i.error({errorCode:r,stage:o,paymentMethodCategory:"unknown",...o==="session_read"?{requestCategory:"session_read"}:{}}),ho(i)}function Il(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 Ua(e){let t=e?.data.paypal?.publishableKey;if(t)return{clientId:t,environment:e?.data.paypal?.environment,providerObjectType:e?.data.paypal?.providerObjectType}}function Fa(e){return!e||e.data.stripe?.publishableKey?!1:!!Ua(e)?.clientId}function ir(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function El(){if(!ir())return null;try{let e=window.sessionStorage.getItem($a);return e?JSON.parse(e):null}catch{return null}}function is(e){if(ir())try{window.sessionStorage.setItem($a,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function Na(){if(ir())try{window.sessionStorage.removeItem($a)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}var ja=":idempotency-key";function ls(e,t){if(!ir())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 Da(e,t,n,r){if(ir())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 qa(e,t){if(ir())try{ls(e,t)&&window.sessionStorage.removeItem(e)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout session cache.",n)}}function cs(e,t){if(!ir())return null;try{let n=window.sessionStorage.getItem(e+ja);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 La(e,t,n){if(ir())try{window.sessionStorage.setItem(e+ja,JSON.stringify({canonicalIdentity:t,idempotencyKey:n}))}catch(r){console.warn("[FloPayCheckout] Failed to persist checkout idempotency key.",r)}}function Oa(e,t){if(qa(e,t),!!ir())try{cs(e,t)&&window.sessionStorage.removeItem(e+ja)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout idempotency key.",n)}}function Rl(){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 ss(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 _l(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 za(e,t){return`${e}:${t.totalAmount??""}:${t.overrideAmount??""}:${t.quantity??1}:${t.currency??""}`}function bo(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=>za(`${o.type??""}:${o.code??o.providerItemId??o.providerPlanId??""}`,o)).sort(),i:e?.items?.map(o=>za(o.code??o.providerItemId??"",o)).sort(),s:e?.subscriptions?.map(o=>za(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 xl(e,t=!1){let n=bo(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 Tl(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=(0,Se.resolveSessionCurrency)(t.currency,t.items,t.subscriptions,t.products);if(!o||e.currency.toUpperCase()!==o.toUpperCase())return!1;let i=(t.products??(0,Se.foldIntoProducts)(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(i.length!==d.length)return!1;for(let g=0;g<i.length;g+=1){let h=i[g],f=d[g];if(h.code!==f.code||h.type!==void 0&&h.type!==f.type||h.quantity!==f.quantity||h.totalAmount!==f.totalAmount||h.overrideAmount!==f.overrideAmount||h.currency!==f.currency)return!1}let c=[...t.couponCodes??[]].sort(),v=[...e.coupons??[]].sort();return c.length===v.length&&c.every((g,h)=>g===v[h])}function na({sessionId:e,nonce:t,createSession:n,billingApiUrl:r,telemetry:o,appearance:i,locale:d,loading:c,error:v,onComplete:g,onError:h,onInstrument:f,onDecline:N,onCountryChange:B,onZipChange:p,showPayPal:C=!0,showStripe:he=!0,enabledPaymentMethods:V,showApplePay:S=!0,showGooglePay:me=!0,debug:H=!1,layout:de,theme:K,buttonsTheme:be,buttonsStyles:$e,cardButtonContent:we,cardBackButtonContent:gt,cardTitleContent:Fe,showSecurityFooter:Ee,onButtonClick:Re,onBeforeButtonClick:oe,enableAVS:ne,cardFieldOrder:O,cardPreFormSlot:ue,avsLayout:We,className:re,initialErrorMessage:Ae=null,children:Z,checkoutMode:T,confirmLabel:j,renderConfirmButton:Me,onSessionCompleted:ye}){let Q=(0,Se.resolveBillingApiUrl)(r),Ne=(0,I.useMemo)(()=>(0,Se.resolveTheme)(K),[K]),Qe=i??Ne?.appearance,Ze=n?"embedded_checkout":"standard_checkout",_e=Z?"custom_layout":de==="buttons"?"buttons_layout":"default_layout",[ie,ae]=(0,I.useState)(null),[X,xe]=(0,I.useState)(null),Le=(0,I.useRef)(null),[L,ee]=(0,I.useState)(null),A=(0,I.useRef)(null),[E,rt]=(0,I.useState)(null),St=(0,I.useMemo)(()=>n?bo(n):"",[n]),ve=n?`create:${St}`:`session:${e??""}`,ct=E?.gateways?.stripe?"stripe":E?.gateways?.paypal?"paypal":void 0,st=(0,I.useRef)(new Set),ot=(0,I.useRef)(ve),Ge=(0,I.useRef)(ve);zo(()=>{Ge.current=ve,ot.current!==ve&&(ot.current=ve,st.current.clear())},[ve]);let b=(0,I.useCallback)(D=>{if(Ge.current===ve){if(Ca.has(D.name)){if(st.current.has(D.name))return;st.current.add(D.name)}ze(()=>f?.(D))}},[ve,f]),G=Or(b,ve),et=(0,I.useRef)(!1),dt=(0,I.useCallback)(D=>{if(et.current)return;let M=D.gateway||!ct?D:{...D,gateway:ct};b(M)},[b,ct]);(0,I.useEffect)(()=>{G({class:"lifecycle",name:"checkout.mount"})},[G]);let[Mt,Bt]=(0,I.useState)(e??""),se=e??Mt,Ve=n?"":se,[Gt,wt]=(0,I.useState)(!0),[zt,xn]=(0,I.useState)(null),[Tn,Qn]=(0,I.useState)("full"),[Jt,sn]=(0,I.useState)(!1),[ln,Ft]=(0,I.useState)(Ae),[Pn,bt]=(0,I.useState)(null),[sr,Ht]=(0,I.useState)(null),[lr,Nt]=(0,I.useState)(!1),[$n,at]=(0,I.useState)(void 0),[Rt,_t]=(0,I.useState)(""),[Qt,cn]=(0,I.useState)(!1),[dn,jn]=(0,I.useState)(!1),[Vn,Ut]=(0,I.useState)(!1),le=(0,I.useRef)(0),Cn=(0,I.useRef)(void 0),[An,er]=(0,I.useState)("loading"),[yr,Er]=(0,I.useState)(0),Mn=(0,I.useRef)(!1),un=(0,I.useRef)(!1),Oe=(0,I.useRef)(!1),Xt=(0,I.useRef)(null),Dt=(0,I.useMemo)(()=>({checkoutMode:T??Tn,layout:Z?"unknown":de==="buttons"?"buttons":"embedded"}),[T,Z,Tn,de]),Hn=(0,I.useRef)(g);Hn.current=g;let k=(0,I.useRef)(h);k.current=h;let ut=(0,I.useRef)(N);ut.current=N,(0,I.useEffect)(()=>{Vt(X)?.setCheckoutContext(Dt),L&&L!==X&&Vt(L)?.setCheckoutContext(Dt)},[X,L,Dt]);let Ke=(0,I.useRef)(ye);Ke.current=ye;let pn=(0,I.useCallback)(D=>{er(D),!(D!=="exhausted"||Oe.current)&&(Oe.current=!0,k.current?.(new Se.FloPayError("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),tt=(0,I.useCallback)(()=>{er("retrying"),Er(D=>D+1)},[]);(0,I.useEffect)(()=>{er("loading"),Er(0),Oe.current=!1},[se]),(0,I.useEffect)(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:Se.SDK_VERSION,checkout_type:Ze,checkout_layout:_e,billing_api_url:Q})},[_e,Ze,Q]);let qt=(0,I.useMemo)(()=>n?bo(n,!0):"",[n]),cr=(0,I.useMemo)(()=>Rt===qt?$n:void 0,[$n,Rt,qt]),Kn=(0,I.useMemo)(()=>n?ba(n,cr):void 0,[n,cr]),Sn=T??Kn?.checkoutMode??"full",Lt=(0,I.useMemo)(()=>Kn?{...Kn,checkoutMode:Sn}:void 0,[Kn,Sn]);(0,I.useEffect)(()=>{at(void 0),_t(qt),Cn.current=void 0,Ut(!1)},[qt]),(0,I.useEffect)(()=>{Ft(Ae)},[Ae]);let mn=(0,I.useCallback)((D,M,te)=>{ze(()=>{ut.current?.(jt(D,M,te))})},[ze]),yn=(0,I.useCallback)(async(D,M)=>{Ft(null),Ht(null),Nt(!1),bt("processing");let te=M?.sessionId??D.id,ce=D.gateways?.stripe?"stripe":D.gateways?.paypal?"paypal":void 0,Ye=Le.current??A.current,pe=Vt(Ye),U=Ye?null:ea(Q,o,Dt),w={log:J=>{pe?pe.log(J):U?.log(J)},error:J=>{pe?pe.error(J):U?.error(J)},terminal:J=>{pe?pe.terminal(J):U?.terminal(J)},performance:J=>{pe?pe.performance(J):U?.performance(J)},now:()=>pe?.now()??U?.now()??0,elapsed:J=>pe?.elapsed(J)??Math.max(0,(U?.now()??J)-J)},P=w.now(),Y=!!(M?.initialAutoProcessingError||M?.initialAutoProcessingPending),pt=!1,vt,m=()=>{pt||(pt=!0,Y=!0,vt=w.now(),w.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),w.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},y=!1,x=()=>{y||(y=!0,w.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),w.performance({stage:"processing",durationMs:w.elapsed(P),durationMode:"machine",paymentMethodCategory:"saved"}),vt!==void 0&&w.performance({stage:"recovery",durationMs:w.elapsed(vt),durationMode:"machine",paymentMethodCategory:"saved"}))};w.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),et.current=!0;try{w.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"})}finally{et.current=!1}G({class:"lifecycle",name:"payment.processing.started",provider:ce}),Y&&m();let Te;try{let J=zi(M?.initialAutoProcessingError),q;if(J)m(),J.type==="paypal_redirect_required"&&Xt.current?.publishableKey&&is({sessionId:te,publishableKey:Xt.current.publishableKey,paypalPublishableKey:Xt.current.paypalPublishableKey}),q=await Ho(J,{flopay:Le.current,paypalFlopay:A.current,attempt3DS:M?.attempt3DS,billingApiUrl:Q,sessionId:te,session:D,telemetry:!1}),J.type==="paypal_redirect_required"&&Na();else if(M?.initialAutoProcessingPending){let fe=(await new Ir.PaymentAPI(Q,{telemetry:!1}).waitForCheckoutSessionCompletion(M.initialAutoProcessingPending.sessionId,{initialDelayMs:M.initialAutoProcessingPending.retryAfterMs})).data.session;if(!Nr(fe))throw No(fe);q=Pr(fe,te)}else{if(M?.initialAutoProcessingError)throw pr(M.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:M.initialAutoProcessingError.checkoutMethod});if(M?.fromCreateSession)return M?.fallbackToFull&&(Qn("full"),ss("full")),!1;{let Xe=await $r({billingApiUrl:Q,sessionId:te,session:D,telemetry:!1});Xe.type==="success"?q=Xe.result:(m(),Xe.type==="paypal_redirect_required"&&Xt.current?.publishableKey&&is({sessionId:te,publishableKey:Xt.current.publishableKey,paypalPublishableKey:Xt.current.paypalPublishableKey}),q=await Ho(Xe,{flopay:Le.current,paypalFlopay:A.current,attempt3DS:M?.attempt3DS,billingApiUrl:Q,sessionId:te,session:D,telemetry:!1}),Xe.type==="paypal_redirect_required"&&Na())}}te&&Ur(te),x(),Y&&(w.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),w.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),w.terminal({outcome:q.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),Nt(q.status==="authorized"),bt("success"),await go(1200),Te=()=>Hn.current?.(q)}catch(J){let q=kr(J),Xe=q.checkoutMethod??yo;Ft(q.message),Ht(q.message),Nt(!1),M?.fallbackToFull&&(w.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),Qn("full"),ss("full")),x();let nt=q.statusCode!==void 0?(0,Se.telemetryStatusClass)(q.statusCode,"unknown"):void 0,fe=nt==="4xx"?{requestCategory:"process_payment",statusClass:nt}:{},Pe=nt===void 0||nt==="4xx";if(Pe&&(q.telemetryOutcome==="payment_declined"||!!(q.declineCode||q.code?.toLowerCase().includes("declin"))))w.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...fe});else if(Pe&&(q.telemetryOutcome==="validation_rejected"||q.type==="validation_error"))w.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...fe});else{let lt=(0,Se.classifyTelemetryFailure)(J,Y?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown"),Ot=q.telemetryRequestCategory??"process_payment";et.current=!0;try{w.error({...lt,...q.telemetryFailureCategory?{failureCategory:q.telemetryFailureCategory}:{},stage:Y?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:Ot})}finally{et.current=!1}G({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:Ot,provider:ce})}return ze(()=>k.current?.(q)),mn(Xe,q,{code:q.code,declineCode:q.declineCode}),bt("error"),await Promise.allSettled([go(1500),M?.ensureProvidersReady?M.ensureProvidersReady():Promise.resolve()]),Y&&(w.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),w.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{x(),U&&ho(U),bt(null),Ht(null)}return ze(Te),!0},[mn,G,ze,kr,Q,o,Dt]);(0,I.useEffect)(()=>{if(typeof window>"u"||un.current)return;let D=new URLSearchParams(window.location.search),M=D.get("payment_intent_client_secret");if(!M)return;let te=El();te&&(un.current=!0,(async()=>{let ce,Ye=0;Ft(null),Ht(null),bt("processing"),sn(!0);try{if(D.get("redirect_status")==="failed")throw Object.assign(new Se.FloPayError("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:pe,paypalFlopay:U}=await Yo({publishableKey:te.publishableKey,paypalPublishableKey:te.paypalPublishableKey,billingApiUrl:Q,locale:d,telemetry:o});ce=Vt(U??pe),Ye=ce?.now()??0,ce?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),ce?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let w=(U??pe)?.getRawProvider();if(!w)throw Object.assign(new Se.FloPayError("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:P,error:Y}=await w.retrievePaymentIntent(M);if(Y)throw Object.assign(new Se.FloPayError(Y.message??"Failed to retrieve PayPal payment status.","api_error",{code:Y.code}),{checkoutMethod:"paypal"});let pt=Ii(P?.status);if(!P||pt==="failed")throw Object.assign(new Se.FloPayError("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let vt=typeof P.payment_method=="string"?P.payment_method:P.payment_method?.id,m=pt;if(te.sessionId){let Te=(await new Ir.PaymentAPI(Q,{telemetry:!1}).getUnifiedCheckoutSession(te.sessionId)).data.session;if(Te&&Te.status!=="complete"){let J=await $r({billingApiUrl:Q,sessionId:te.sessionId,session:Te,telemetry:!1,tokenizedData:{id:vt??P.id,type:"card",threeDSecureActionResultTokenId:P.id,isPaypal:!0}});if(J.type!=="success")throw Object.assign(new Se.FloPayError("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});m=J.result.status}}te.sessionId&&Ur(te.sessionId),ce?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),ce?.performance({stage:"redirect_resume",durationMs:ce.elapsed(Ye),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),ce?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),bt("success"),await go(1200),ze(()=>Hn.current?.({status:m,paymentIntentId:P.id,paymentMethodId:vt,checkoutMethod:"paypal"}))}catch(pe){let U=kr(pe),w=U.checkoutMethod??"paypal",P=!!(U.declineCode||U.code?.toLowerCase().includes("declin"));if(ce)ce.performance({stage:"redirect_resume",durationMs:ce.elapsed(Ye),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),P?ce.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):ce.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(P){let Y=ea(Q,o,Dt);Y.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),ho(Y)}else Ba(Q,o,Dt,"REDIRECT_RESUME_FAILED","redirect_resume");Ft(U.message),Ht(U.message),ze(()=>k.current?.(U)),mn(w,U,{code:U.code,declineCode:U.declineCode}),bt("error"),await go(1500)}finally{Na(),Rl(),bt(null),Ht(null),sn(!1)}})())},[mn,ze,d,kr,Q,o]);let De=(0,I.useRef)(null),kt=(0,I.useMemo)(()=>Lt?bo(Lt):"",[Lt]),xt=(0,I.useRef)(Lt);xt.current=Lt,(0,I.useEffect)(()=>{Bt(e??"")},[e]),(0,I.useEffect)(()=>{Mn.current=!1,Ft(Ae),Ht(null),Nt(!1),bt(null)},[kt,Ae,e]);async function Bn(D,M,te){let ce=ea(Q,o,Dt),Ye=new Ir.PaymentAPI(Q,{telemetry:!1}),pe=!1;try{let U=D.idempotencyKey!==void 0?(0,Se.resolveIdempotencyKey)(D.idempotencyKey):void 0,w=ls(M,te),P=cs(M,te);w?.canonicalIdentity===te&&P&&P.canonicalIdentity===void 0&&(La(M,te,P.idempotencyKey),P={...P,canonicalIdentity:te});let Y=U??(P?.canonicalIdentity===te?P.idempotencyKey:void 0),pt,vt=!1;ce.log({name:w?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let m=w?.sid??null,y=null,x,Te,J=!1;if(m)try{y=await Ye.getUnifiedCheckoutSession(m,w?.nonce),w&&w.canonicalIdentity===void 0&&(Tl(y.data.session,D)?(Da(M,te,m,w.nonce??y.data.session?.clientSecret),P&&P.canonicalIdentity===void 0&&(La(M,te,P.idempotencyKey),Y??(Y=P.idempotencyKey))):(Oa(M,te),P=null,Y=U,m=null,y=null));let q=y?.data.session?.status;if(m&&y&&q==="complete"){if(wa(m))return{sid:m,result:y};Oa(M,te),m=null,y=null,vt=!0}}catch{ce.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),w?.canonicalIdentity===void 0?(Oa(M,te),Y=U):qa(M,te),m=null}if(!m){!U&&(vt||!Y)&&(Y=(0,Se.resolveIdempotencyKey)(),pt=Y),Y&&La(M,te,Y);let q=ce.now(),Xe=0;ce.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let nt={...D,idempotencyKey:Y,avsCheck:!!ne,avsConfig:typeof ne=="object"?ne:void 0,checkoutType:"embedded_checkout",checkoutLayout:Z?"custom_layout":de==="buttons"?"buttons_layout":"default_layout"};Object.defineProperty(nt,Ir.SESSION_CREATE_TELEMETRY,{configurable:!1,enumerable:!1,value:{onAttempt:z=>{Xe=Math.max(Xe,z)}}});let fe=()=>{ce.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:"2xx"}),ce.performance({stage:"session_create",durationMs:ce.now()-q,durationMode:"machine",requestCategory:"session_create",attempt:Xe,statusClass:"2xx"})},Pe=z=>{let ge=(0,Se.classifyTelemetryFailure)(z,"CHECKOUT_SESSION_CREATE_FAILED","unknown");ce.performance({stage:"session_create",durationMs:ce.now()-q,durationMode:"machine",requestCategory:"session_create",attempt:Xe,statusClass:ge.statusClass}),z instanceof Se.FloPayError&&z.type==="validation_error"?ce.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown"}):ge.statusClass==="4xx"?ce.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create",statusClass:"4xx"}):(ce.error({...ge,stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create"}),G({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_create"}))};try{if((0,Se.isDetachedSessionEligible)(nt)){let z=await Ye.createDetachedSession(nt);z.claimed.catch(()=>{}),y=z.shell,m=z.sessionId,Te=z.claim,J=!nt.account.email?.trim(),x=z.claimed.then(ge=>{let lt=ge.data.session?.id??z.sessionId;return lt&&Da(M,te,lt,ge.data.session?.clientSecret??z.nonce),fe(),ge},ge=>{throw qa(M,te),Pe(ge),ge}).finally(()=>ho(ce)),x.catch(()=>{}),pe=!0,ce.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),ce.performance({stage:"session_shell",durationMs:ce.now()-q,durationMode:"machine",requestCategory:"session_create",attempt:Xe,statusClass:"2xx",paymentMethodCategory:"card"})}else y=await Ye.createAndFetchSession(nt),fe()}catch(z){throw Pe(z),z}m=y.data.session?.id??m??"",m&&!x&&Da(M,te,m,y.data.session?.clientSecret)}return{sid:m??"",result:y,sdkGeneratedIdempotencyKey:pt,...x?{claimed:x}:{},...Te?{claim:Te}:{},...J?{claimRequiresIdentity:!0}:{}}}finally{pe||ho(ce)}}let fn=(0,I.useCallback)(async(D,M)=>{let te=xt.current;if(!te)throw new Se.FloPayError("createSession is required to bootstrap checkout.","validation_error");let ce=ba(te,D),Ye=bo(ce),pe=xl(ce),U=ta.get(Ye);if(!U){let Y={canonicalIdentity:Ye,promise:Bn(ce,pe,Ye),consumers:0,settled:!1};U=Y,ta.set(Ye,Y);let pt=()=>{Y.settled=!0,as(Ye,Y)};Y.promise.then(pt,pt)}U.consumers+=1;let w=!1,P=()=>{w||(w=!0,U.consumers-=1,as(Ye,U))};M?.(P);try{let Y=await U.promise;De.current=Ye,D&&(_t(qt),at(nt=>Si(nt,D)));let{sid:pt,result:vt,claimed:m,claim:y,claimRequiresIdentity:x}=Y;if(Cn.current=y,Ut(x===!0),ae(vt),vt.data.session&&rt(vt.data.session),pt&&Bt(pt),m){le.current+=1;let nt=le.current;jn(!0),m.then(fe=>{le.current===nt&&(ae(fe),fe.data.session&&rt(fe.data.session),jn(!1),Ut(!1))},fe=>{le.current===nt&&(jn(!1),Ut(!1),xn(fe instanceof Se.FloPayError?fe:new Se.FloPayError(fe instanceof Error?fe.message:"Failed to create session","api_error")))})}else le.current+=1,jn(!1),Ut(!1);let{publishableKey:Te,paypalPublishableKey:J}=Ko(vt),{flopay:q,paypalFlopay:Xe}=await Yo({publishableKey:Te,paypalPublishableKey:J,billingApiUrl:Q,locale:d,telemetry:o});return Le.current=q,xe(q),A.current=Xe,ee(Xe),wt(!1),Y}catch(Y){throw De.current===Ye&&(De.current=null),Y}finally{M||P()}},[qt,d,Q,o,Dt]),Fn=(0,I.useRef)(yn);Fn.current=yn;let Nn=(0,I.useRef)(fn);Nn.current=fn;let $t=(0,I.useCallback)(async D=>{if(!_l(D)||Qt)return{sessionId:Mt,session:E};cn(!0);try{let M=await fn(D);return{sessionId:M.sid,session:M.result.data.session??null}}finally{cn(!1)}},[fn,Qt,Mt,E]),en=(0,I.useCallback)(async D=>{let M=Cn.current;M&&await M(D)},[]);(0,I.useEffect)(()=>{let D=!1,M;if(xn(null),kt){let Ye=xt.current;return Qn(Sn),wt(!1),De.current===kt?()=>{D=!0}:(rt(wi(Ye,T)),(async()=>{let pe=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),U=Sn==="auto"&&!Mn.current&&!pe;U&&(Ft(null),Ht(null),bt("processing"));try{let w=await Nn.current(void 0,vt=>{M=vt}),P=w.result.data.session??null;Xt.current=Ko(w.result);let Y=Fa(w.result),pt=wa(w.sid||P?.id);if(!D&&U&&P&&!Y&&!pt){Mn.current=!0,await kl(kt,w.sdkGeneratedIdempotencyKey,()=>Fn.current(P,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:w.result.autoProcessingError,initialAutoProcessingPending:w.result.autoProcessingPending,autoProcessingAttempted:w.result.autoProcessingAttempted,sessionId:w.sid||P.id}));return}!D&&U&&((Y||pt)&&(Mn.current=!0),bt(null),Ht(null))}catch(w){if(D)return;let P=w instanceof Se.FloPayError||typeof w=="object"&&w!==null&&"code"in w?w.code:void 0;if(U&&P==="session_auto_completed"){Mn.current=!0,bt("success"),await go(1200),D||(ze(()=>{Hn.current?.({status:"succeeded"})}),bt(null),Ht(null));return}U&&(bt(null),Ht(null));let Y=w instanceof Se.FloPayError?w:new Se.FloPayError(w instanceof Error?w.message:"Failed to create session","api_error");xn(Y)}finally{M?.(),M=void 0}})(),()=>{D=!0,M?.()})}wt(!0);async function te(){let Ye=!1;try{let U=await new Ir.PaymentAPI(Q,{telemetry:!1}).getUnifiedCheckoutSession(se,t);if(D)return;ae(U);let w=U.data.session??null;if(rt(w),!w)throw new Se.FloPayError("No session data returned","api_error");let P=w.checkoutMode;if(P==="setup")throw new Se.FloPayError("This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.","validation_error",{code:"InvalidCardSetupSurface",param:"sessionId"});if(w.status==="authorized"){wt(!1),ze(()=>{Hn.current?.(Pr(w,se)),Ke.current?.(w.successUrl??"")});return}if(w.status==="complete"){wt(!1),ze(()=>{Ke.current?.(w.successUrl??"")});return}if(w.status==="expired")throw Fo(w);Ye=!0;let Y=T??P??"full";Qn(Y);let pt=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),vt=Fa(U);if(Y==="auto"&&!Mn.current&&!pt&&!vt){Mn.current=!0;let m=ce(U);try{if(await Fn.current(w,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>m,sessionId:se||w.id}),D)return;await m,D||wt(!1);return}catch{if(D)return;await m,D||wt(!1);return}}await ce(U),D||wt(!1)}catch(pe){if(D)return;Ye&&G({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"}),pe instanceof Se.FloPayError?!Ye&&!Il(pe)&&Ba(Q,o,Dt,"NETWORK_REQUEST_FAILED","session_read"):Ba(Q,o,Dt,"INTERNAL_SDK_ERROR","checkout_mount");let U=pe instanceof Se.FloPayError?pe:new Se.FloPayError(pe instanceof Error?pe.message:"Failed to initialize checkout","api_error");xn(U),wt(!1)}}async function ce(Ye){let{publishableKey:pe,paypalPublishableKey:U}=Ko(Ye);Xt.current={publishableKey:pe,paypalPublishableKey:U};let{flopay:w,paypalFlopay:P}=await Yo({publishableKey:pe,paypalPublishableKey:U,billingApiUrl:Q,locale:d,telemetry:o});Le.current=w,xe(w),A.current=P,ee(P)}return te(),()=>{D=!0}},[T,kt,Sn,Ve,ze,t]);let rn=(0,I.useCallback)(async()=>{if(!(Jt||!E)){sn(!0),Ft(null);try{await yn(E,{attempt3DS:!0,fallbackToFull:!0,sessionId:se||E.id})}finally{sn(!1)}}},[se,Jt,yn,E]),tr=Ua(ie),Rr=Fa(ie),Dn=(0,I.useMemo)(()=>{if(!(!ie||!E||!ie.data.stripe?.publishableKey))return{billingApiUrl:Q}},[ie,E,Q]),Yn=!!(n&&!Z&&de==="buttons"&&oe&&Sn==="full"),Zt=(0,I.useMemo)(()=>({session:E,loading:Gt,error:zt,checkoutMode:Tn,inlineSessionDraft:Lt,applyInlineSessionPatch:Yn?$t:void 0,inlineSessionPatchProcessing:Qt,claimPending:dn,claimRequiresIdentity:Vn}),[E,Gt,zt,Tn,Lt,Yn,$t,Qt,dn,Vn]),it=!!n&&de==="buttons"&&!Rr&&(!X||!Dn),Kt=Pn?(0,R.jsx)(Rn,{status:Pn,errorMessage:sr,authorized:lr}):null;if(Gt){if(c)return(0,R.jsxs)(R.Fragment,{children:[c,Kt]});if(de==="buttons"){let D=Ne?.buttonsLayout?.cardButton?.borderRadius??Ne?.appearance.variables?.borderRadius??8,M=te=>(0,R.jsx)("div",{style:{height:te,borderRadius:D,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return(0,R.jsxs)(R.Fragment,{children:[(0,R.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[C&&M(Hr),he&&(S||me)&&M(Hr),he&&M(Hr),(0,R.jsx)("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),Kt]})}return(0,R.jsxs)(R.Fragment,{children:[(0,R.jsxs)("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[(0,R.jsx)("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),(0,R.jsx)("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),Kt]})}return zt?v?(0,R.jsx)(zn.Provider,{value:Zt,children:v(zt)}):(0,R.jsx)(zn.Provider,{value:Zt,children:(0,R.jsx)("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:zt.message})}):it?(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(zn.Provider,{value:Zt,children:(0,R.jsx)(Ml,{onButtonClick:Re,showPayPal:C,showStripe:he,showApplePay:S,showGooglePay:me,theme:K,buttonsTheme:be,buttonsStyles:$e,cardButtonContent:we,cardBackButtonContent:gt,cardTitleContent:Fe})}),Kt]}):Rr&&E&&tr?(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(zn.Provider,{value:Zt,children:(0,R.jsxs)("div",{className:re,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[ln&&(0,R.jsx)(zr,{icon:!1,children:ln}),An==="retrying"&&(0,R.jsx)("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),An==="exhausted"&&(0,R.jsxs)("div",{role:"alert",children:[(0,R.jsx)("div",{children:"PayPal is temporarily unavailable. Please try again."}),(0,R.jsx)("button",{type:"button",onClick:tt,children:"Retry PayPal"})]}),An!=="exhausted"&&(0,R.jsx)("div",{"aria-hidden":An==="retrying"?!0:void 0,style:An==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:(0,R.jsx)(Di,{sessionId:se,nonce:E.clientSecret||void 0,billingApiUrl:Q,email:E.customer?.email||Lt?.account?.email,billingName:[E.customer?.firstName,E.customer?.lastName].filter(Boolean).join(" ")||[Lt?.account?.firstName,Lt?.account?.lastName].filter(Boolean).join(" ")||void 0,onBuyerIdentityReady:en,clientId:tr.clientId,environment:tr.environment,currency:(E.currency??"usd").toUpperCase(),isSubscription:E.mode==="subscription",providerObjectType:tr.providerObjectType,onComplete:g,onErrorChange:Ft,onDecline:N,onButtonClick:Re,onInitializationStateChange:pn,allowAutomaticRetry:yr===0,session:E,telemetry:o,telemetryContext:Dt,onInstrument:dt,debug:H},`${ve}:paypal-init-${yr}`)})]})}),Kt]}):!X||!Dn?(0,R.jsx)(R.Fragment,{children:Kt}):Tn==="confirm"?(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(zn.Provider,{value:Zt,children:(0,R.jsx)(po,{flopay:X,paypalFlopay:L,options:Dn,onInstrument:dt,children:(0,R.jsxs)("div",{className:re,children:[ln&&(0,R.jsx)("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:ln}),Me?Me({onConfirm:rn,isProcessing:Jt}):(0,R.jsx)("button",{type:"button",onClick:rn,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...":j??"Confirm Purchase"})]})},ve)}),Kt]}):(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(zn.Provider,{value:Zt,children:(0,R.jsx)(po,{flopay:X,paypalFlopay:L,options:Dn,onInstrument:dt,children:Z?(0,R.jsxs)(R.Fragment,{children:[ln&&(0,R.jsx)("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:ln}),(0,R.jsx)(Al,{sessionId:se,nonce:E?.clientSecret||void 0,billingApiUrl:Q,session:E,children:Z})]}):(0,R.jsx)(Zo,{sessionId:se,nonce:E?.clientSecret||void 0,email:E?.customer?.email||Lt?.account?.email,userId:E?.customer?.id||Lt?.account?.userId,firstName:E?.customer?.firstName||Lt?.account?.firstName,lastName:E?.customer?.lastName||Lt?.account?.lastName,totalAmount:E?Math.round((0,Se.buildCheckoutDisplayData)(E).total*100):0,currency:E?.currency?.toLowerCase()??"usd",onComplete:g,onError:h,onDecline:N,error:ln,onErrorChange:Ft,showPayPal:C,showStripe:he,enabledPaymentMethods:V??ie?.data.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:ie?.data.stripe?.enabledPaymentMethodCountries,showApplePay:S,showGooglePay:me,layout:de,theme:K,buttonsTheme:be,buttonsStyles:$e,appearance:Qe,cardButtonContent:we,cardBackButtonContent:gt,cardTitleContent:Fe,onButtonClick:Re,onBeforeButtonClick:oe,onBuyerIdentityReady:en,enableAVS:ne,...O?{cardFieldOrder:O}:{},...ue?{cardPreFormSlot:ue}:{},avsLayout:We,country:E?.customer?.country,city:E?.customer?.city,state:E?.customer?.state,onCountryChange:B,onZipChange:p,avsCheck:!!ne,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:Z?"custom_layout":de==="buttons"?"buttons_layout":"default_layout",className:re,directPaypal:Ua(ie),isSubscription:E?.mode==="subscription",session:E,dataAttachmentPending:dn,dataAttachmentRequiresIdentity:Vn,debug:H})},ve)}),Kt]})}function Al({sessionId:e,nonce:t,billingApiUrl:n,session:r,children:o}){return(0,R.jsx)(R.Fragment,{children:I.default.Children.map(o,i=>{if(!I.default.isValidElement(i))return i;let d=i.props,c={};return d.sessionId||(c.sessionId=e),!d.nonce&&t&&(c.nonce=t),d.billingApiUrl||(c.billingApiUrl=n),r?.customer&&(d.email||(c.email=r.customer.email),d.userId||(c.userId=r.customer.id),d.firstName||(c.firstName=r.customer.firstName),d.lastName||(c.lastName=r.customer.lastName)),Object.keys(c).length===0?i:I.default.cloneElement(i,c)})})}function Ml({onButtonClick:e,showPayPal:t,showStripe:n=!0,showApplePay:r,showGooglePay:o,theme:i,buttonsTheme:d,buttonsStyles:c,cardButtonContent:v,cardBackButtonContent:g,cardTitleContent:h}){let[f,N]=(0,I.useState)(!1),B=(0,I.useMemo)(()=>(0,Se.resolveTheme)(i),[i]),p=(0,I.useMemo)(()=>{let S=B?.buttonsLayout??(0,Se.resolveButtonsLayoutTheme)(d);return c?{...S,...c,cardButton:{...S.cardButton,...c.cardButton},cardFormContainer:{...S.cardFormContainer,...c.cardFormContainer},backButton:{...S.backButton,...c.backButton},backButtonIcon:{...S.backButtonIcon,...c.backButtonIcon},submitButton:{...S.submitButton,...c.submitButton},title:{...S.title,...c.title}}:S},[B,d,c]),C=B?.buttonsLayout?.cardButton?.borderRadius??B?.appearance.variables?.borderRadius??8,he=S=>(0,R.jsx)("div",{style:{height:S,borderRadius:C,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),V=v===void 0?{boxSizing:"border-box",height:Hr,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(f){let S=p.cardInputBorder??"#e5e7eb",me=p.cardInputBackground??"white",H=Ar(g),de=Ar(h);return(0,R.jsxs)("div",{style:{backgroundColor:p.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",...p.cardFormContainer},children:[(0,R.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,R.jsxs)("button",{type:"button",onClick:()=>N(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:H?0:"0.5rem",background:"none",border:"none",color:"#4b5563",fontSize:"0.85rem",fontWeight:500,padding:0,flexShrink:0,opacity:1,cursor:"pointer",...p.backButton},children:[(0,R.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...p.backButtonIcon},children:(0,R.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,R.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,R.jsx)(Br,{content:g})]}),de?(0,R.jsx)("div",{style:{flex:1}}):(0,R.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...p.title},children:(0,R.jsx)(oo,{content:h})})]}),(0,R.jsx)("div",{style:{backgroundColor:me,border:`1px solid ${S}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:(0,R.jsx)("div",{style:{width:"60%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,R.jsxs)("div",{style:{display:"flex"},children:[(0,R.jsx)("div",{style:{flex:1,backgroundColor:me,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${S}`,borderLeft:`1px solid ${S}`,borderBottomLeftRadius:8,padding:12,height:45},children:(0,R.jsx)("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,R.jsx)("div",{style:{flex:1,backgroundColor:me,borderTop:"none",borderRight:`1px solid ${S}`,borderBottom:`1px solid ${S}`,borderLeft:`1px solid ${S}`,borderBottomRightRadius:8,padding:12,height:45},children:(0,R.jsx)("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),(0,R.jsx)("div",{style:{backgroundColor:me,border:`1px solid ${S}`,borderRadius:8,marginTop:8,padding:12,height:45},children:(0,R.jsx)("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,R.jsx)("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",...p.submitButton,opacity:.5}}),(0,R.jsx)("style",{children:`
41
41
  @keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }
42
42
  @keyframes flopay-interim-expand {
43
43
  0% { opacity: 0; max-height: 0; transform: translateY(-12px); }
44
44
  40% { opacity: 1; }
45
45
  100% { opacity: 1; max-height: 600px; transform: translateY(0); }
46
46
  }
47
- `})]})}return(0,E.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&he(Hr),n&&(r||o)&&he(Hr),n&&(0,E.jsx)("button",{type:"button",onClick:()=>{e?.("card"),D(!0)},style:{width:"100%",...V,backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:"8px",fontSize:p.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,...p.cardButton},onMouseDown:S=>{S.currentTarget.style.transform="scale(0.985)"},onMouseUp:S=>{S.currentTarget.style.transform="scale(1)"},children:(0,E.jsx)(Mr,{content:v})}),(0,E.jsx)("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}var qn=require("react/jsx-runtime"),Bl=44;function ds(e){return new Promise(t=>setTimeout(t,e))}function Fl(e,t){return e instanceof bn.FloPayError?e:new bn.FloPayError(e instanceof Error?e.message:t,"api_error")}function Dl(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function Nl(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 us({sessionId:e,nonce:t,createSession:n,paymentMethodId:r,checkoutMethod:o,clientId:i,products:d,items:c,subscriptions:v,account:g,successUrl:h,cancelUrl:f,couponCodes:D,tagsData:B,utmMetadata:p,billingApiUrl:C,locale:he,theme:V,appearance:S,buttonsTheme:me,buttonsStyles:H,onSuccess:de,onError:K,onDecline:be,children:$e,disabled:we=!1,type:gt="button",style:Fe,...Ee}){let Re=(0,qe.useMemo)(()=>(0,bn.resolveBillingApiUrl)(C),[C]),oe=(0,qe.useMemo)(()=>Nl({createSession:n,clientId:i,products:d,items:c,subscriptions:v,account:g,successUrl:h,cancelUrl:f,couponCodes:D,tagsData:B,utmMetadata:p}),[g,f,i,D,n,d,c,v,h,B,p]),[ne,O]=(0,qe.useState)(!1),[ue,We]=(0,qe.useState)(null),[re,Te]=(0,qe.useState)(null),[Z,T]=(0,qe.useState)(!1),[j,Ae]=(0,qe.useState)(null),ye=(0,qe.useRef)(!0),Q=(0,qe.useRef)(null),De=(0,qe.useRef)(j),Qe=(0,qe.useRef)(de),Ze=(0,qe.useRef)(K),_e=(0,qe.useRef)(be);(0,qe.useEffect)(()=>{De.current=j},[j]),(0,qe.useEffect)(()=>{Qe.current=de},[de]),(0,qe.useEffect)(()=>{Ze.current=K},[K]),(0,qe.useEffect)(()=>{_e.current=be},[be]),(0,qe.useEffect)(()=>(ye.current=!0,()=>{ye.current=!1,Q.current?.abort()}),[]),(0,qe.useEffect)(()=>{if(typeof window>"u")return;let b=G=>{G.key==="Escape"&&Ae(null)};return window.addEventListener("keydown",b),()=>{window.removeEventListener("keydown",b)}},[]);let ie=(0,qe.useCallback)((b,G=yo)=>{_e.current?.($t(G,b,{code:b.code,declineCode:b.declineCode}))},[]),ae=(0,qe.useCallback)(async b=>{ye.current&&(Te(null),T(b.result.status==="authorized"),We("success"),await ds(1200),ye.current&&Qe.current?.(b))},[]),X=(0,qe.useCallback)(async(b,G)=>{ye.current&&(Ze.current?.(b),G?.emitDecline&&ie(b,G.method),Te(b.message),T(!1),We("error"),await ds(1500))},[ie]),xe=(0,qe.useCallback)(async(b,G,et)=>{let dt=b.data.session??null;if(!dt)throw new bn.FloPayError("No session data returned","api_error");let Mt=dt.clientSecret||t;if(Dr(dt)){await ae({result:Pr(dt,G),session:dt,sessionId:dt.id||G,autoCompleted:!1});return}if(dt.status==="expired")throw Fo(dt);try{if(b.autoProcessingPending){let Wt=(await new ra.PaymentAPI(Re).waitForCheckoutSessionCompletion(b.autoProcessingPending.sessionId,{initialDelayMs:b.autoProcessingPending.retryAfterMs})).data.session;if(!Dr(Wt))throw Do(Wt);await ae({result:Pr(Wt,G),session:Wt,sessionId:Wt.id||G,autoCompleted:!1});return}if(b.autoProcessingError){if(b.autoProcessingError.type==="3ds_required"&&b.autoProcessingError.nextActionRedirectUrl&&G&&Mt){let se=new AbortController;Q.current=se;let Ve;try{Ve=await Ui({billingApiUrl:Re,sessionId:G,nonce:Mt,nextActionRedirectUrl:b.autoProcessingError.nextActionRedirectUrl,signal:se.signal})}finally{Q.current===se&&(Q.current=null)}if(Ve.status==="declined")throw pr({type:Ve.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:Ve.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:b.autoProcessingError.checkoutMethod});let Ot=(await new ra.PaymentAPI(Re).waitForCheckoutSessionCompletion(G,{initialDelayMs:0,nonce:Mt})).data.session;if(!Dr(Ot))throw pr({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:b.autoProcessingError.checkoutMethod});await ae({result:Pr(Ot,G),session:Ot,sessionId:Ot.id||G,autoCompleted:!1});return}throw pr(b.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:b.autoProcessingError.checkoutMethod})}if(et?.fromCreateSession&&b.autoProcessingAttempted===!0)throw pr({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let Bt=await $r({billingApiUrl:Re,sessionId:G??dt.id,session:dt,nonce:Mt});if(Bt.type!=="success")throw pr({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await ae({result:Bt.result,session:dt,sessionId:dt.id||G,autoCompleted:!1})}catch(Bt){let se=kr(Bt),Ve=dt.id||G;await X(se,{emitDecline:!0,method:se.checkoutMethod??yo}),Dl(se,Ve)&&Ve&&ye.current&&Ae({sessionId:Ve,errorMessage:se.message,nonce:Mt||void 0})}},[t,Re,X,ae]),Le=(0,qe.useCallback)(async b=>{if(Ee.onClick?.(b),!(b.defaultPrevented||we||ne)){if(Ae(null),e&&oe){let G=new bn.FloPayError("Provide either sessionId or create-session props, not both.","validation_error");await X(G),ye.current&&(We(null),Te(null));return}if(!e&&!oe){let G=new bn.FloPayError("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await X(G),ye.current&&(We(null),Te(null));return}O(!0),Te(null),T(!1),We("processing");try{let G=new ra.PaymentAPI(Re);if(e){let et=await G.getUnifiedCheckoutSession(e,t);await xe(et,e);return}try{let et=await G.createAndFetchSession({...oe});await xe(et,et.data.session?.id??null,{fromCreateSession:!0})}catch(et){if(et instanceof bn.FloPayError&&et.code==="session_auto_completed"){await ae({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw et}}catch(G){await X(Fl(G,"Automatic payment failed. Please try again."))}finally{ye.current&&(We(null),Te(null),O(!1))}}},[Ee,oe,we,ne,t,xe,Re,e,X,ae]),L=(0,qe.useCallback)(b=>{let G=De.current;Ae(null),Qe.current?.({result:b,session:null,sessionId:G?.sessionId??null,autoCompleted:!1})},[]),ee=(0,qe.useCallback)(b=>{Ze.current?.(b)},[]),A=(0,qe.useCallback)(b=>{_e.current?.(b)},[]),R=(0,qe.useMemo)(()=>(0,bn.resolveTheme)(V),[V]),rt=(0,qe.useMemo)(()=>{let b=R?.buttonsLayout??(0,bn.resolveButtonsLayoutTheme)(me);return H?{...b,...H,cardButton:{...b.cardButton,...H.cardButton}}:b},[R,me,H]),St=(0,qe.useMemo)(()=>{let b=R?.appearance;return S?b?{...b,...S,variables:{...b.variables,...S.variables}}:S:b},[S,R]),ve=St?.variables,ct=ve?.colorPrimary??"#4A49FF",st=ve?.colorPrimaryHover??Vr(ct,.12),ot=ve?.borderRadius??"8px";return(0,qn.jsxs)(qn.Fragment,{children:[(0,qn.jsx)("button",{...Ee,type:gt,onClick:Le,disabled:we||ne,"aria-busy":ne,style:{width:"100%",...$e===void 0?{boxSizing:"border-box",height:Bl,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...rt.cardButton,...Ma({themeBundle:R,resolvedPrimaryColor:ct,resolvedBorderRadius:ot,submitButtonStyle:rt.submitButton,explicitPrimaryColor:ve?.colorPrimary}),fontSize:rt.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:we||ne?"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:we||ne?.6:1,...Fe},onMouseEnter:b=>{Ee.onMouseEnter?.(b),!b.defaultPrevented&&!we&&!ne&&(R||ve?.colorPrimary)&&(b.currentTarget.style.backgroundColor=st)},onMouseLeave:b=>{Ee.onMouseLeave?.(b),!b.defaultPrevented&&(R||ve?.colorPrimary)&&(b.currentTarget.style.backgroundColor=ct)},onMouseDown:b=>{Ee.onMouseDown?.(b),b.defaultPrevented||(b.currentTarget.style.transform="scale(0.985)")},onMouseUp:b=>{Ee.onMouseUp?.(b),b.defaultPrevented||(b.currentTarget.style.transform="scale(1)")},children:(0,qn.jsx)(Mr,{content:$e})}),ue&&(0,qn.jsx)(Rn,{status:ue,errorMessage:re,authorized:Z}),j&&(0,qn.jsx)("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:(0,qn.jsx)("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:(0,qn.jsx)(na,{sessionId:j.sessionId,nonce:j.nonce,checkoutMode:"full",billingApiUrl:Re,locale:he,theme:V,...St?{appearance:St}:{},buttonsTheme:me,buttonsStyles:H,initialErrorMessage:j.errorMessage,cardTitleContent:null,onComplete:L,onError:ee,onDecline:A})})})]})}var oa=require("@flopay/js/card-setup"),vn=require("@flopay/shared"),ft=require("react");var Zn=require("react/jsx-runtime"),vo=class extends vn.FloPayError{constructor(t,n,r){super(t,n,r),this.name="FloPayCardSetupError",this.retryable=r.retryable}};function ps(e,t={}){let n=e instanceof vn.FloPayError?e:void 0,r=n?.statusCode,o=t.retryable??(n?.type==="network_error"||n?.type==="rate_limit_error"||typeof r=="number"&&r>=500||n?.code==="vault_capture_timeout"||!n);return new vo(n?.message??(e instanceof Error?e.message:"Failed to load the secure card form."),n?.type??"api_error",{code:t.code??n?.code??"card_setup_load_failed",retryable:o,...n?.param?{param:n.param}:{},...r!==void 0?{statusCode:r}:{}})}function ms({sessionId:e,nonce:t,billingApiUrl:n,telemetry:r,theme:o="modern-light",containerStyle:i,loading:d=null,onReady:c,onComplete:v,onDecline:g,onCancel:h,onValidation:f,onError:D}){let[B,p]=(0,ft.useState)(null),[C,he]=(0,ft.useState)(null),[V,S]=(0,ft.useState)(null),[me,H]=(0,ft.useState)(null),[de,K]=(0,ft.useState)(null),be=(0,ft.useRef)(!1),$e=(0,ft.useRef)(!1),we=(0,ft.useMemo)(()=>{if(typeof o=="object")return o;let re=(0,vn.resolveTheme)(o);if(re)return Wo({appearance:re.appearance,buttonsStyles:re.buttonsLayout,layout:"default"})},[o]),gt=(0,ft.useRef)(c),Fe=(0,ft.useRef)(D),Ee=(0,ft.useRef)(v),Re=(0,ft.useRef)(g),oe=(0,ft.useRef)(h),ne=(0,ft.useRef)(f),O=(0,ft.useRef)(!1),ue=(0,ft.useRef)(!1),We=(0,ft.useRef)(0);return gt.current=c,Fe.current=D,Ee.current=v,Re.current=g,oe.current=h,ne.current=f,(0,ft.useEffect)(()=>{let re=We.current+1;return We.current=re,()=>{queueMicrotask(()=>{We.current===re&&(O.current||ue.current||(ue.current=!0,ze(()=>{oe.current?.({status:"cancelled",sessionId:e})})))})}},[e]),(0,ft.useEffect)(()=>{let re=!0,Te=new oa.PaymentAPI((0,vn.resolveBillingApiUrl)(n),{telemetry:r});return p(null),he(null),S(null),O.current=!1,ue.current=!1,(async()=>{try{if(!e.trim())throw new vn.FloPayError("FloPayCardSetup requires a sessionId.","validation_error",{code:"MissingCheckoutSessionId",param:"sessionId"});if(!t.trim())throw new vn.FloPayError("FloPayCardSetup requires a session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let Z=await Te.getUnifiedCheckoutSession(e,t);if(!re)return;let T=Z.data.session;if(!T||!(0,vn.isCardSetupCheckoutSession)(T))throw new vn.FloPayError("FloPayCardSetup only accepts a zero-amount, productless setup session.","validation_error",{code:"InvalidCardSetupSession",param:"sessionId"});let j=T.vault;if(j?.html?.trim()||(j=await Te.getVaultCapture(e,t)),!j.html?.trim())throw new vn.FloPayError("FloPay: this setup session has no vault card capability. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});if(!re)return;he(j),p(new oa.PciVaultCardCapture({sessionId:e,operation:"card_setup",telemetry:r}))}catch(Z){if(!re)return;let T=ps(Z);O.current=!0,S(T),ze(()=>Fe.current?.(T))}})(),()=>{re=!1,Te.destroy()}},[n,t,e,r]),(0,ft.useEffect)(()=>{if(!B)return;let re=!1;$e.current=!1,be.current=!1;let Te=B.on("submitting",()=>{be.current=!0,K(null),H("processing")}),Z=B.on("complete",j=>{O.current=!0,be.current=!1,H("success"),(async()=>(await new Promise(Ae=>setTimeout(Ae,1200)),!$e.current&&($e.current=!0,ze(()=>{Ee.current?.({status:"succeeded",sessionId:e,...j.paymentMethod?{paymentMethod:j.paymentMethod}:{}})}),re||H(null))))()}),T=B.on("decline",j=>{O.current=!0,be.current=!1,K(j.message??null),H("error"),ze(()=>{Re.current?.({status:"declined",sessionId:e,...j.declineReason?{reason:j.declineReason}:{},...j.message?{message:j.message}:{}})}),(async()=>(await new Promise(Ae=>setTimeout(Ae,1500)),re||H(null)))()});return()=>{re=!0,Te(),Z(),T()}},[B,e]),V?(0,Zn.jsx)("div",{role:"alert",children:V.message}):!B||!C?.html?(0,Zn.jsx)(Zn.Fragment,{children:d}):(0,Zn.jsxs)(Zn.Fragment,{children:[me&&(0,Zn.jsx)(Rn,{status:me,errorMessage:de,processingLabel:"SAVING CARD...",successLabel:"CARD SAVED",errorLabel:"CARD NOT SAVED",successNote:null}),(0,Zn.jsx)(jr,{capture:B,html:C.html,messageToken:C.messageToken,expectedOrigin:C.expectedOrigin,theme:we,containerStyle:i,onReady:()=>{ze(()=>gt.current?.())},onValidation:re=>{ze(()=>ne.current?.(re))},onError:re=>{if(!re)return;be.current&&(be.current=!1,K(re),H("error"),setTimeout(()=>H(null),1500));let Te=ps(new Error(re),{code:"card_setup_widget_failed",retryable:!0});ze(()=>Fe.current?.(Te))}})]})}0&&(module.exports={DirectPayPalButton,FloPayAutomaticPaymentButton,FloPayCardSetup,FloPayCardSetupError,FloPayCheckout,FloPayProvider,SplitCardForm,VaultCardFields,dropThirdPartyOnlyError,useCheckout,useFloPay,usePayPalFloPay});
47
+ `})]})}return(0,R.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&he(Hr),n&&(r||o)&&he(Hr),n&&(0,R.jsx)("button",{type:"button",onClick:()=>{e?.("card"),N(!0)},style:{width:"100%",...V,backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:"8px",fontSize:p.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,...p.cardButton},onMouseDown:S=>{S.currentTarget.style.transform="scale(0.985)"},onMouseUp:S=>{S.currentTarget.style.transform="scale(1)"},children:(0,R.jsx)(Mr,{content:v})}),(0,R.jsx)("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}var qn=require("react/jsx-runtime"),Bl=44;function ds(e){return new Promise(t=>setTimeout(t,e))}function Fl(e,t){return e instanceof bn.FloPayError?e:new bn.FloPayError(e instanceof Error?e.message:t,"api_error")}function Nl(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function Dl(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 us({sessionId:e,nonce:t,createSession:n,paymentMethodId:r,checkoutMethod:o,clientId:i,products:d,items:c,subscriptions:v,account:g,successUrl:h,cancelUrl:f,couponCodes:N,tagsData:B,utmMetadata:p,billingApiUrl:C,locale:he,theme:V,appearance:S,buttonsTheme:me,buttonsStyles:H,onSuccess:de,onError:K,onDecline:be,children:$e,disabled:we=!1,type:gt="button",style:Fe,...Ee}){let Re=(0,qe.useMemo)(()=>(0,bn.resolveBillingApiUrl)(C),[C]),oe=(0,qe.useMemo)(()=>Dl({createSession:n,clientId:i,products:d,items:c,subscriptions:v,account:g,successUrl:h,cancelUrl:f,couponCodes:N,tagsData:B,utmMetadata:p}),[g,f,i,N,n,d,c,v,h,B,p]),[ne,O]=(0,qe.useState)(!1),[ue,We]=(0,qe.useState)(null),[re,Ae]=(0,qe.useState)(null),[Z,T]=(0,qe.useState)(!1),[j,Me]=(0,qe.useState)(null),ye=(0,qe.useRef)(!0),Q=(0,qe.useRef)(null),Ne=(0,qe.useRef)(j),Qe=(0,qe.useRef)(de),Ze=(0,qe.useRef)(K),_e=(0,qe.useRef)(be);(0,qe.useEffect)(()=>{Ne.current=j},[j]),(0,qe.useEffect)(()=>{Qe.current=de},[de]),(0,qe.useEffect)(()=>{Ze.current=K},[K]),(0,qe.useEffect)(()=>{_e.current=be},[be]),(0,qe.useEffect)(()=>(ye.current=!0,()=>{ye.current=!1,Q.current?.abort()}),[]),(0,qe.useEffect)(()=>{if(typeof window>"u")return;let b=G=>{G.key==="Escape"&&Me(null)};return window.addEventListener("keydown",b),()=>{window.removeEventListener("keydown",b)}},[]);let ie=(0,qe.useCallback)((b,G=yo)=>{_e.current?.(jt(G,b,{code:b.code,declineCode:b.declineCode}))},[]),ae=(0,qe.useCallback)(async b=>{ye.current&&(Ae(null),T(b.result.status==="authorized"),We("success"),await ds(1200),ye.current&&Qe.current?.(b))},[]),X=(0,qe.useCallback)(async(b,G)=>{ye.current&&(Ze.current?.(b),G?.emitDecline&&ie(b,G.method),Ae(b.message),T(!1),We("error"),await ds(1500))},[ie]),xe=(0,qe.useCallback)(async(b,G,et)=>{let dt=b.data.session??null;if(!dt)throw new bn.FloPayError("No session data returned","api_error");let Mt=dt.clientSecret||t;if(Nr(dt)){await ae({result:Pr(dt,G),session:dt,sessionId:dt.id||G,autoCompleted:!1});return}if(dt.status==="expired")throw Fo(dt);try{if(b.autoProcessingPending){let Gt=(await new ra.PaymentAPI(Re).waitForCheckoutSessionCompletion(b.autoProcessingPending.sessionId,{initialDelayMs:b.autoProcessingPending.retryAfterMs})).data.session;if(!Nr(Gt))throw No(Gt);await ae({result:Pr(Gt,G),session:Gt,sessionId:Gt.id||G,autoCompleted:!1});return}if(b.autoProcessingError){if(b.autoProcessingError.type==="3ds_required"&&b.autoProcessingError.nextActionRedirectUrl&&G&&Mt){let se=new AbortController;Q.current=se;let Ve;try{Ve=await Ui({billingApiUrl:Re,sessionId:G,nonce:Mt,nextActionRedirectUrl:b.autoProcessingError.nextActionRedirectUrl,signal:se.signal})}finally{Q.current===se&&(Q.current=null)}if(Ve.status==="declined")throw pr({type:Ve.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:Ve.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:b.autoProcessingError.checkoutMethod});let zt=(await new ra.PaymentAPI(Re).waitForCheckoutSessionCompletion(G,{initialDelayMs:0,nonce:Mt})).data.session;if(!Nr(zt))throw pr({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:b.autoProcessingError.checkoutMethod});await ae({result:Pr(zt,G),session:zt,sessionId:zt.id||G,autoCompleted:!1});return}throw pr(b.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:b.autoProcessingError.checkoutMethod})}if(et?.fromCreateSession&&b.autoProcessingAttempted===!0)throw pr({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let Bt=await $r({billingApiUrl:Re,sessionId:G??dt.id,session:dt,nonce:Mt});if(Bt.type!=="success")throw pr({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await ae({result:Bt.result,session:dt,sessionId:dt.id||G,autoCompleted:!1})}catch(Bt){let se=kr(Bt),Ve=dt.id||G;await X(se,{emitDecline:!0,method:se.checkoutMethod??yo}),Nl(se,Ve)&&Ve&&ye.current&&Me({sessionId:Ve,errorMessage:se.message,nonce:Mt||void 0})}},[t,Re,X,ae]),Le=(0,qe.useCallback)(async b=>{if(Ee.onClick?.(b),!(b.defaultPrevented||we||ne)){if(Me(null),e&&oe){let G=new bn.FloPayError("Provide either sessionId or create-session props, not both.","validation_error");await X(G),ye.current&&(We(null),Ae(null));return}if(!e&&!oe){let G=new bn.FloPayError("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await X(G),ye.current&&(We(null),Ae(null));return}O(!0),Ae(null),T(!1),We("processing");try{let G=new ra.PaymentAPI(Re);if(e){let et=await G.getUnifiedCheckoutSession(e,t);await xe(et,e);return}try{let et=await G.createAndFetchSession({...oe});await xe(et,et.data.session?.id??null,{fromCreateSession:!0})}catch(et){if(et instanceof bn.FloPayError&&et.code==="session_auto_completed"){await ae({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw et}}catch(G){await X(Fl(G,"Automatic payment failed. Please try again."))}finally{ye.current&&(We(null),Ae(null),O(!1))}}},[Ee,oe,we,ne,t,xe,Re,e,X,ae]),L=(0,qe.useCallback)(b=>{let G=Ne.current;Me(null),Qe.current?.({result:b,session:null,sessionId:G?.sessionId??null,autoCompleted:!1})},[]),ee=(0,qe.useCallback)(b=>{Ze.current?.(b)},[]),A=(0,qe.useCallback)(b=>{_e.current?.(b)},[]),E=(0,qe.useMemo)(()=>(0,bn.resolveTheme)(V),[V]),rt=(0,qe.useMemo)(()=>{let b=E?.buttonsLayout??(0,bn.resolveButtonsLayoutTheme)(me);return H?{...b,...H,cardButton:{...b.cardButton,...H.cardButton}}:b},[E,me,H]),St=(0,qe.useMemo)(()=>{let b=E?.appearance;return S?b?{...b,...S,variables:{...b.variables,...S.variables}}:S:b},[S,E]),ve=St?.variables,ct=ve?.colorPrimary??"#4A49FF",st=ve?.colorPrimaryHover??Vr(ct,.12),ot=ve?.borderRadius??"8px";return(0,qn.jsxs)(qn.Fragment,{children:[(0,qn.jsx)("button",{...Ee,type:gt,onClick:Le,disabled:we||ne,"aria-busy":ne,style:{width:"100%",...$e===void 0?{boxSizing:"border-box",height:Bl,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...rt.cardButton,...Ma({themeBundle:E,resolvedPrimaryColor:ct,resolvedBorderRadius:ot,submitButtonStyle:rt.submitButton,explicitPrimaryColor:ve?.colorPrimary}),fontSize:rt.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:we||ne?"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:we||ne?.6:1,...Fe},onMouseEnter:b=>{Ee.onMouseEnter?.(b),!b.defaultPrevented&&!we&&!ne&&(E||ve?.colorPrimary)&&(b.currentTarget.style.backgroundColor=st)},onMouseLeave:b=>{Ee.onMouseLeave?.(b),!b.defaultPrevented&&(E||ve?.colorPrimary)&&(b.currentTarget.style.backgroundColor=ct)},onMouseDown:b=>{Ee.onMouseDown?.(b),b.defaultPrevented||(b.currentTarget.style.transform="scale(0.985)")},onMouseUp:b=>{Ee.onMouseUp?.(b),b.defaultPrevented||(b.currentTarget.style.transform="scale(1)")},children:(0,qn.jsx)(Mr,{content:$e})}),ue&&(0,qn.jsx)(Rn,{status:ue,errorMessage:re,authorized:Z}),j&&(0,qn.jsx)("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:b=>{b.target===b.currentTarget&&Me(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:(0,qn.jsx)("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:(0,qn.jsx)(na,{sessionId:j.sessionId,nonce:j.nonce,checkoutMode:"full",billingApiUrl:Re,locale:he,theme:V,...St?{appearance:St}:{},buttonsTheme:me,buttonsStyles:H,initialErrorMessage:j.errorMessage,cardTitleContent:null,onComplete:L,onError:ee,onDecline:A})})})]})}var oa=require("@flopay/js/card-setup"),vn=require("@flopay/shared"),ft=require("react");var Zn=require("react/jsx-runtime"),vo=class extends vn.FloPayError{constructor(t,n,r){super(t,n,r),this.name="FloPayCardSetupError",this.retryable=r.retryable}};function ps(e,t={}){let n=e instanceof vn.FloPayError?e:void 0,r=n?.statusCode,o=t.retryable??(n?.type==="network_error"||n?.type==="rate_limit_error"||typeof r=="number"&&r>=500||n?.code==="vault_capture_timeout"||!n);return new vo(n?.message??(e instanceof Error?e.message:"Failed to load the secure card form."),n?.type??"api_error",{code:t.code??n?.code??"card_setup_load_failed",retryable:o,...n?.param?{param:n.param}:{},...r!==void 0?{statusCode:r}:{}})}function ms({sessionId:e,nonce:t,billingApiUrl:n,telemetry:r,theme:o="modern-light",containerStyle:i,loading:d=null,onReady:c,onComplete:v,onDecline:g,onCancel:h,onValidation:f,onError:N}){let[B,p]=(0,ft.useState)(null),[C,he]=(0,ft.useState)(null),[V,S]=(0,ft.useState)(null),[me,H]=(0,ft.useState)(null),[de,K]=(0,ft.useState)(null),be=(0,ft.useRef)(!1),$e=(0,ft.useRef)(!1),we=(0,ft.useMemo)(()=>{if(typeof o=="object")return o;let re=(0,vn.resolveTheme)(o);if(re)return Wo({appearance:re.appearance,buttonsStyles:re.buttonsLayout,layout:"default"})},[o]),gt=(0,ft.useRef)(c),Fe=(0,ft.useRef)(N),Ee=(0,ft.useRef)(v),Re=(0,ft.useRef)(g),oe=(0,ft.useRef)(h),ne=(0,ft.useRef)(f),O=(0,ft.useRef)(!1),ue=(0,ft.useRef)(!1),We=(0,ft.useRef)(0);return gt.current=c,Fe.current=N,Ee.current=v,Re.current=g,oe.current=h,ne.current=f,(0,ft.useEffect)(()=>{let re=We.current+1;return We.current=re,()=>{queueMicrotask(()=>{We.current===re&&(O.current||ue.current||(ue.current=!0,ze(()=>{oe.current?.({status:"cancelled",sessionId:e})})))})}},[e]),(0,ft.useEffect)(()=>{let re=!0,Ae=new oa.PaymentAPI((0,vn.resolveBillingApiUrl)(n),{telemetry:r});return p(null),he(null),S(null),O.current=!1,ue.current=!1,(async()=>{try{if(!e.trim())throw new vn.FloPayError("FloPayCardSetup requires a sessionId.","validation_error",{code:"MissingCheckoutSessionId",param:"sessionId"});if(!t.trim())throw new vn.FloPayError("FloPayCardSetup requires a session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let Z=await Ae.getUnifiedCheckoutSession(e,t);if(!re)return;let T=Z.data.session;if(!T||!(0,vn.isCardSetupCheckoutSession)(T))throw new vn.FloPayError("FloPayCardSetup only accepts a zero-amount, productless setup session.","validation_error",{code:"InvalidCardSetupSession",param:"sessionId"});let j=T.vault;if(j?.html?.trim()||(j=await Ae.getVaultCapture(e,t)),!j.html?.trim())throw new vn.FloPayError("FloPay: this setup session has no vault card capability. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});if(!re)return;he(j),p(new oa.PciVaultCardCapture({sessionId:e,operation:"card_setup",telemetry:r}))}catch(Z){if(!re)return;let T=ps(Z);O.current=!0,S(T),ze(()=>Fe.current?.(T))}})(),()=>{re=!1,Ae.destroy()}},[n,t,e,r]),(0,ft.useEffect)(()=>{if(!B)return;let re=!1;$e.current=!1,be.current=!1;let Ae=B.on("submitting",()=>{be.current=!0,K(null),H("processing")}),Z=B.on("complete",j=>{O.current=!0,be.current=!1,H("success"),(async()=>(await new Promise(Me=>setTimeout(Me,1200)),!$e.current&&($e.current=!0,ze(()=>{Ee.current?.({status:"succeeded",sessionId:e,...j.paymentMethod?{paymentMethod:j.paymentMethod}:{}})}),re||H(null))))()}),T=B.on("decline",j=>{O.current=!0,be.current=!1,K(j.message??null),H("error"),ze(()=>{Re.current?.({status:"declined",sessionId:e,...j.declineReason?{reason:j.declineReason}:{},...j.message?{message:j.message}:{}})}),(async()=>(await new Promise(Me=>setTimeout(Me,1500)),re||H(null)))()});return()=>{re=!0,Ae(),Z(),T()}},[B,e]),V?(0,Zn.jsx)("div",{role:"alert",children:V.message}):!B||!C?.html?(0,Zn.jsx)(Zn.Fragment,{children:d}):(0,Zn.jsxs)(Zn.Fragment,{children:[me&&(0,Zn.jsx)(Rn,{status:me,errorMessage:de,processingLabel:"SAVING CARD...",successLabel:"CARD SAVED",errorLabel:"CARD NOT SAVED",successNote:null}),(0,Zn.jsx)(jr,{capture:B,html:C.html,messageToken:C.messageToken,expectedOrigin:C.expectedOrigin,theme:we,containerStyle:i,onReady:()=>{ze(()=>gt.current?.())},onValidation:re=>{ze(()=>ne.current?.(re))},onError:re=>{if(!re)return;be.current&&(be.current=!1,K(re),H("error"),setTimeout(()=>H(null),1500));let Ae=ps(new Error(re),{code:"card_setup_widget_failed",retryable:!0});ze(()=>Fe.current?.(Ae))}})]})}0&&(module.exports={DirectPayPalButton,FloPayAutomaticPaymentButton,FloPayCardSetup,FloPayCardSetupError,FloPayCheckout,FloPayProvider,SplitCardForm,VaultCardFields,dropThirdPartyOnlyError,useCheckout,useFloPay,usePayPalFloPay});