@flopay/react 1.8.8 → 1.8.9

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 js=Object.create;var Lo=Object.defineProperty;var Vs=Object.getOwnPropertyDescriptor;var Ks=Object.getOwnPropertyNames;var Hs=Object.getPrototypeOf,Ys=Object.prototype.hasOwnProperty;var Ws=(e,t)=>{for(var n in t)Lo(e,n,{get:t[n],enumerable:!0})},xi=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Ks(t))!Ys.call(e,o)&&o!==n&&Lo(e,o,{get:()=>t[o],enumerable:!(r=Vs(t,o))||r.enumerable});return e};var Ti=(e,t,n)=>(n=e!=null?js(Hs(e)):{},xi(t||!e||!e.__esModule?Lo(n,"default",{value:e,enumerable:!0}):n,e)),Gs=e=>xi(Lo({},"__esModule",{value:!0}),e);var Hl={};Ws(Hl,{DirectPayPalButton:()=>mo,FloPayAutomaticPaymentButton:()=>Ps,FloPayCardSetup:()=>Ss,FloPayCardSetupError:()=>So,FloPayCheckout:()=>aa,FloPayProvider:()=>fo,SplitCardForm:()=>ta,VaultCardFields:()=>Yr,dropThirdPartyOnlyError:()=>ws.dropThirdPartyOnlyError,useCheckout:()=>Oi,useFloPay:()=>or,usePayPalFloPay:()=>Uo});module.exports=Gs(Hl);var ws=require("@flopay/shared");var ia=require("@flopay/js"),ln=require("@flopay/shared"),Oe=require("react");var vt=require("react/jsx-runtime");function Js(){return(0,vt.jsxs)(vt.Fragment,{children:[(0,vt.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,vt.jsx)("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),(0,vt.jsx)("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",(0,vt.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,vt.jsx)("path",{d:"M9 18l6-6-6-6"})})]})}function Xs(){return(0,vt.jsx)(vt.Fragment,{children:"Go back"})}function Zs(){return(0,vt.jsx)(vt.Fragment,{children:"Secure card checkout"})}function Fr(e){return e!==void 0&&(e===""||e===null||e===!1)}function Dr({content:e}){return(0,vt.jsx)(vt.Fragment,{children:e===void 0?(0,vt.jsx)(Js,{}):e})}function Lr({content:e}){return(0,vt.jsx)(vt.Fragment,{children:e===void 0?(0,vt.jsx)(Xs,{}):e})}function lo({content:e}){return(0,vt.jsx)(vt.Fragment,{children:e===void 0?(0,vt.jsx)(Zs,{}):e})}var tr=require("@flopay/shared");function Nr(e,t,n,r={}){let o;return(i={})=>{if(o)return o;let u={...r,...i,email:i.email?.trim()||r.email?.trim()};if(!(0,tr.isValidEmail)(u.email))return Promise.reject(new tr.FloPayError("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}));let c={};for(let[P,g]of Object.entries(u)){if(typeof g!="string")continue;let b=g.trim();b&&(c[P]=b)}return o=e.claimCheckoutSession(t,n,{accountData:c}),o.catch(()=>{}),o}}function Ai(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 Ia(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 Bi(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,u)=>i+(u.overrideAmount??u.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,u)=>({uuid:`synthetic-${i.type??"item"}-${u}`,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 Sr(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 Ra(e,t){return t?{...e,...t}:e}function Ft(e,t,n){let r=typeof t=="string"?t:t.message,o=typeof t=="string"?n?.code:n?.code??t.code,i=typeof t=="string"?n?.declineCode:n?.declineCode??t.declineCode;return{method:e,message:r,...o?{code:o}:{},...i?{declineCode:i}:{}}}var Qs=[{match:/^paypal authorization required\.?$/i,replacement:"For your additional security, please re-authenticate this payment via PayPal."}];function fr(e){if(typeof e!="string")return e??void 0;let t=e.trim();if(!t)return e;for(let{match:n,replacement:r}of Qs)if(n.test(t))return r;return e}function wr(e,t){return e.status!=="authorized"?{status:"succeeded"}:{status:"authorized",paymentId:e.paymentId,sessionId:e.id||t||void 0,authorizationExpiresAt:e.authorizationExpiresAt}}function Or(e){return e?.status==="authorized"||e?.status==="complete"}function Mi(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function No(e){let t=Mi(e);return new tr.FloPayError(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function Oo(e){let t=Mi(e);return new tr.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 zo(e,t){return e==="processing"||(0,tr.isMoneySettledOutcome)(e,t)}function Fi(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}function Di(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?{mode:"setup"}:{mode:"payment",amount:e}}function co(e){let t=[e?.id,e?.originalPaymentMethodId];for(let n of t)if(typeof n=="string"&&n.startsWith("pm_"))return n}var Er=require("@flopay/js"),Pe=require("@flopay/shared"),R=Ti(require("react"),1);var Ea=require("react"),kn=(0,Ea.createContext)({flopay:null,paypalFlopay:null,billingApiUrl:""}),Ln=(0,Ea.createContext)({session:null,loading:!1,error:null});var Vo=require("@flopay/js"),It=require("@flopay/shared"),ji=require("@paypal/paypal-js"),D=require("react");var Li=require("@flopay/shared"),Nn=require("react"),nr=require("react/jsx-runtime");function nn(e){let{firstName:t,lastName:n,...r}=e,o=t?.trim(),i=n?.trim();return{...r,...o?{firstName:o}:{},...i?{lastName:i}:{}}}function zr(){let[e,t]=(0,Nn.useState)(null),n=(0,Nn.useRef)(null),r=(0,Nn.useRef)(0),o=(0,Nn.useCallback)((u,c)=>(n.current?.(null),r.current+=1,t({id:r.current,methodLabel:u,identity:c}),new Promise(P=>{n.current=P})),[]),i=(0,Nn.useCallback)(u=>{let c=n.current;n.current=null,t(null),c?.(u)},[]);return(0,Nn.useEffect)(()=>()=>{n.current?.(null),n.current=null},[]),{request:e,collect:o,finish:i}}function Ur({identity:e,methodLabel:t,onComplete:n,onCancel:r,submitting:o=!1,testId:i="flopay-buyer-identity-pane"}){let[u,c]=(0,Nn.useState)(e.email?.trim()??""),P=(0,Li.isValidEmail)(u.trim());return(0,nr.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,nr.jsxs)("div",{style:{fontWeight:700},children:["Continue with ",t]}),(0,nr.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",(0,nr.jsx)("input",{type:"email",autoComplete:"email","data-testid":"flopay-email",required:!0,value:u,onChange:g=>c(g.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]}),(0,nr.jsxs)("div",{style:{display:"flex",gap:"0.5rem"},children:[r&&(0,nr.jsx)("button",{type:"button",onClick:r,style:{flex:1,minHeight:42},children:"Cancel"}),(0,nr.jsxs)("button",{type:"button",disabled:!P||o,onClick:()=>{n(nn({...e,email:u.trim()}))},style:{flex:2,minHeight:42},children:["Continue with ",t]})]})]})}function el(e){if(e instanceof Error)return e.message;if(typeof e=="object"&&e!==null){let t=e.message;return typeof t=="string"?t:void 0}return typeof e=="string"?e:void 0}function kr(e){if(typeof e!="string")return;let t=e.trim();return/^[a-z0-9_.-]{1,64}$/i.test(t)?t:void 0}function rr(e){if(typeof e!="object"||e===null)return;let t=e;return kr(t.code)??kr(t.type)??kr(t.name)}function qr(e){if(!(typeof e!="object"||e===null))return kr(e.decline_code)}function uo(e){return typeof e!="object"||e===null?!1:kr(e.type)?.toLowerCase()==="card_error"||qr(e)!==void 0}function gr(e){let t=el(e)?.toLowerCase()??"",r=`${rr(e)?.toLowerCase()??""} ${t}`;return r.includes("popup")&&r.includes("block")}var Ni=require("@flopay/shared"),po=require("react");function or(){return(0,po.useContext)(kn).flopay}function Uo(){return(0,po.useContext)(kn).paypalFlopay??null}function Oi(){return(0,po.useContext)(Ln)}function zi(){return(0,po.useContext)(kn).billingApiUrl||(0,Ni.resolveBillingApiUrl)()}var Ui=require("@flopay/shared"),Ir=require("react");function Ke(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 qo=require("react"),$o=typeof window>"u"?qo.useEffect:qo.useLayoutEffect;var tl={"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 nl(e){return e==="stripe"||e==="paypal"?e:void 0}function rl(e){let t=nl(e.provider),n={schemaVersion:Ui.FLO_INSTRUMENT_SCHEMA_VERSION,...t?{gateway:t}:{}};if(e.class==="lifecycle"){let r=tl[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 _a=new Set(["checkout_mount","sdk_loaded","form_rendered","card_expanded"]);function $r(e,t){let n=(0,Ir.useRef)(e);n.current=e;let r=(0,Ir.useRef)(new Set),o=(0,Ir.useRef)(t),i=(0,Ir.useRef)(t);return $o(()=>{i.current=t,o.current!==t&&(o.current=t,r.current.clear())},[t]),(0,Ir.useCallback)(u=>{if(i.current!==t)return;let c=rl(u);if(c){if(_a.has(c.name)){if(r.current.has(c.name))return;r.current.add(c.name)}Ke(()=>n.current?.(c))}},[t])}var ol=Symbol.for("@flopay/js.telemetry.bridge.v1"),al=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function il(){return{error:()=>{},log:()=>{},performance:()=>{},terminal:()=>{},now:()=>globalThis.performance?.now()??0,elapsed:e=>Math.max(0,(globalThis.performance?.now()??e)-e),setCheckoutContext:()=>{},beginCheckout:()=>globalThis.performance?.now()??0,disable:()=>{},subscribe:()=>()=>{},flush:async()=>{},destroy:()=>{}}}function sl(e){let t=il(),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 jo(e){let t=globalThis[al];return sl(t?.(e)??{})}function Dt(e){if(e)return e[ol]}var In=require("react/jsx-runtime"),Ko=45,ll=1e3,cl=11e3,dl=["https://www.paypal.com","https://www.sandbox.paypal.com"],qi="We couldn't open PayPal. Try again or choose another payment method.",ul={width:"100%",minHeight:Ko,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 $i(e){return e.includes("No ack for postMessage init()")&&dl.some(t=>e.includes(t))&&e.includes("10000ms")}function pl(e){return e?`${qi} Allow pop-ups for this site, then try again.`:qi}function ml(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 Vi({sessionId:e,nonce:t,billingApiUrl:n,email:r,billingName:o,onBuyerIdentityReady:i,clientId:u,environment:c,currency:P,isSubscription:g,providerObjectType:b,onTokenizedBody:v,onComplete:N,onErrorChange:B,onDecline:f,onTechnicalFailure:C,isProcessing:ge=!1,onLoadStateChange:$,onInitializationStateChange:S,allowAutomaticRetry:ye=!0,onButtonClick:j,runBeforeButtonClick:pe,session:J,existingOrderId:he,telemetry:ze,telemetryContext:we,onInstrument:yt,debug:Me=!1}){let Ie=or(),Re=$r(yt,e),re=(0,D.useMemo)(()=>{if(Ie)return null;let h=jo({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:It.SDK_VERSION,enabled:ze!==!1});return h.setCheckoutContext(we??{}),h.beginCheckout(we??{}),h},[n,Ie,ze,we?.checkoutMode,we?.layout]),oe=(0,D.useMemo)(()=>Dt(Ie),[Ie]);(0,D.useEffect)(()=>()=>{re&&re.flush().catch(()=>{}).finally(()=>re.destroy())},[re]);let O=(0,D.useMemo)(()=>({error:h=>{oe?oe.error(h):re?.error(h),Re({class:"technical_error",errorCode:h.requestCategory==="intent_create"?"PAYMENT_PROCESSING_FAILED":h.errorCode,requestCategory:h.requestCategory,provider:h.provider})},log:h=>{oe?oe.log(h):re?.log(h),Re({class:"lifecycle",name:h.name,provider:h.provider})},performance:h=>{oe?oe.performance(h):re?.performance(h)},terminal:h=>{oe?oe.terminal(h):re?.terminal(h)},startTiming:()=>oe?.now()??re?.now()??0,elapsed:h=>oe?.elapsed(h)??Math.max(0,(re?.now()??h)-h)}),[Re,oe,re]),Ee=(0,D.useRef)(null),_e=(0,D.useRef)(0),X=(0,D.useRef)(null),ke=(0,D.useRef)(!1),[Ce,x]=(0,D.useState)(!1),[q,xe]=(0,D.useState)(!1),[fe,te]=(0,D.useState)(0),Fe=(0,D.useRef)(0),[Qe,ot]=(0,D.useState)(!1),Le=(0,D.useRef)(!1),ae=(0,D.useRef)(!1),[Z,H]=(0,D.useState)(!1),[Te,He]=(0,D.useState)(!1),{request:M,collect:ie,finish:L}=zr(),E=(0,D.useRef)({sessionId:e,required:!(0,It.isValidEmail)(r?.trim()||J?.customer?.email?.trim())});E.current.sessionId!==e&&(E.current={sessionId:e,required:!(0,It.isValidEmail)(r?.trim()||J?.customer?.email?.trim())});let et=E.current.required,ft=(0,D.useMemo)(()=>n.replace(/\/+$/,""),[n]),ce=b??(g?"subscription":"order"),tt=b==="order"||b==="setup_token",Ge=(0,D.useMemo)(()=>JSON.stringify([ft,u,P,c??"",ce,tt,e,he??""]),[ft,u,P,c,he,ce,tt,e]),gt=(0,D.useRef)(Ge),St=gt.current!==Ge,[w,se]=(0,D.useState)([]),de=h=>{Me&&se(ht=>[...ht,`${new Date().toISOString().slice(11,23)} ${h}`])},at=(0,D.useRef)(v),Tt=(0,D.useRef)(N),Pt=(0,D.useRef)(B),Je=(0,D.useRef)(f),Ye=(0,D.useRef)(C),jt=(0,D.useRef)(j),Lt=(0,D.useRef)($),At=(0,D.useRef)(S),dn=(0,D.useRef)(i),_n=(0,D.useRef)(pe),zn=(0,D.useRef)(J),Jt=(0,D.useRef)(r),xn=(0,D.useRef)(o),Ht=(0,D.useRef)(t),nt=(0,D.useRef)(null),un=(0,D.useRef)(0),je=(0,D.useRef)(null),Un=(0,D.useRef)(null),it=(0,D.useRef)(new Map),cr=(0,D.useRef)(new Map),Nt=(0,D.useRef)(!1);(0,D.useEffect)(()=>(Nt.current=!0,()=>{Nt.current=!1}),[]),(0,D.useEffect)(()=>{at.current=v},[v]),(0,D.useEffect)(()=>{dn.current=i},[i]),(0,D.useEffect)(()=>{Tt.current=N},[N]),(0,D.useEffect)(()=>{Pt.current=B},[B]),(0,D.useEffect)(()=>{Je.current=f},[f]),(0,D.useEffect)(()=>{Ye.current=C},[C]),(0,D.useEffect)(()=>{jt.current=j},[j]),(0,D.useEffect)(()=>{Lt.current=$},[$]),(0,D.useEffect)(()=>{At.current=S},[S]),(0,D.useEffect)(()=>{_n.current=pe},[pe]),(0,D.useEffect)(()=>{zn.current=J},[J]),(0,D.useEffect)(()=>{Jt.current=r},[r]),(0,D.useEffect)(()=>{xn.current=o},[o]),(0,D.useEffect)(()=>{Ht.current=t},[t]),(0,D.useEffect)(()=>{Fe.current=fe},[fe]),(0,D.useEffect)(()=>{Qe&&X.current?.focus()},[Qe,fe]);let Vt=(0,D.useCallback)(()=>{window.setTimeout(()=>{X.current?.focus()},0)},[]),pn=(0,D.useCallback)(()=>{x(!1),te(h=>h+1)},[]),rn=(0,D.useCallback)(()=>{ot(!1),(Ee.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??Ee.current)?.focus?.()},[]);(0,D.useEffect)(()=>{!Ce||!ke.current||(ke.current=!1,rn())},[rn,Ce,fe]);let mn=(0,D.useCallback)((h,ht)=>{let Kt=Ye.current;if(Kt){Kt("paypal",h,ht);return}Pt.current?.(pl(ht?.popupBlocked??gr(h)))},[]),Bt=()=>{je.current?.timer&&(clearTimeout(je.current.timer),je.current.timer=null)},dr=()=>{Bt();let h=un.current+1;return un.current=h,Un.current=null,je.current={generation:h,timer:null,yieldedControl:!1},ot(!1),h},Ot=h=>h!==void 0&&je.current?.generation!==h?!1:(Bt(),je.current=null,Un.current=null,!0),ue=h=>{let ht=h?.generation??je.current?.generation??un.current;(!h?.generation||je.current?.generation===ht)&&(Bt(),je.current=null),Un.current=ht,h?.showRetry&&ot(!0),h?.remount&&pn(),h?.focus!==!1&&Vt()},ur=h=>je.current?.generation===h&&Un.current!==h,yn=h=>{typeof document<"u"&&document.visibilityState!=="visible"||(Bt(),h.timer=setTimeout(()=>{je.current?.generation===h.generation&&(je.current=null,Un.current=h.generation,mn(new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}),ot(!0),pn(),Vt())},600))},Xt=()=>{let h=je.current;h?.yieldedControl&&yn(h)},qn=()=>{let h=je.current;h&&(h.yieldedControl=!0,Bt())},fn=h=>{let ht=nt.current;return ht&&cr.current.set(h,ht),h};(0,D.useEffect)(()=>{let h=()=>{document.visibilityState==="visible"?Xt():qn()};return document.addEventListener("visibilitychange",h),window.addEventListener("focus",Xt),window.addEventListener("blur",qn),()=>{document.removeEventListener("visibilitychange",h),window.removeEventListener("focus",Xt),window.removeEventListener("blur",qn),Bt()}},[]),(0,D.useEffect)(()=>{gt.current!==Ge&&(gt.current=Ge,Le.current=!1,ae.current=!1,x(!1),xe(!1),H(!1),At.current?.("loading"))},[Ge]),(0,D.useEffect)(()=>{Ke(()=>Lt.current?.(Ce&&!Z))},[Ce,Z]);let Wn=(0,It.normalizeGatewayEnvironment)(c);(0,D.useEffect)(()=>{let h=u?`${u.slice(0,6)}\u2026(len ${u.length})`:"(empty)",ht=typeof navigator<"u"?navigator.userAgent:"(no navigator)";if(de(`mount clientId=${h} env=${c??"(unset)"}\u2192${Wn??"live"} ccy=${P} sub=${g}`),de(`ua=${ht.slice(0,80)}${ht.length>80?"\u2026":""}`),!u){de("FAIL: clientId empty \u2014 gateway misconfigured"),H(!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(!Ee.current){de("FAIL: containerRef not attached");return}_e.current=O.startTiming(),O.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let Kt=!1,Gn=!1,Ue=()=>Kt||Gn,wt,ct=!1,Yt=()=>{wt=(0,It.generateIdempotencyKey)(),wt||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),ct=!0},Jn=null,pr=!1,Xn=null,br=!1,hn=()=>{!Xn||br||(br=!0,Xn.close().catch(()=>{}))},Zn=null,$n=()=>{Zn!==null&&(O.log({name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal"}),O.performance({stage:"overlay_return",durationMs:O.elapsed(Zn),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal"}),Zn=null)},Zt=!1,bt=Ee.current,Tn=null,on=null,Qt=[],en=y=>{if(!y||typeof y.getBoundingClientRect!="function")return"(no rect)";let d=y.getBoundingClientRect();return`${Math.round(d.width)}\xD7${Math.round(d.height)}`},st=y=>{if(!y)return"(empty)";try{let d=new URL(y,typeof window<"u"?window.location.href:"https://localhost"),m=d.pathname.toLowerCase();return m.includes("checkcaptcha")||m.includes("captcha")?`CAPTCHA(${d.host}${m})`:m.includes("risk")||m.includes("challenge")?`RISK(${d.host}${m})`:m.includes("smart/buttons")?`smart-buttons(${d.host})`:`${d.host}${m}`.slice(0,100)}catch{return y.slice(0,80)}},Qn=y=>{let d=y.getAttribute("src"),m=y.getAttribute("srcdoc"),T=y.getAttribute("name"),A=y.getAttribute("sandbox"),me=[];return d&&me.push(`src=${st(d)}`),m&&me.push(`srcdoc[${m.length}ch]`),!d&&!m&&me.push("src=(empty) srcdoc=(empty)"),T&&me.push(`name=${T.slice(0,40)}`),A!==null&&me.push(`sandbox="${A.slice(0,40)}"`),me.join(" ")},An=y=>{if(!(y instanceof HTMLIFrameElement))return"";try{let d=y.contentDocument;if(!d)return"cd=null";let m=d.body?.children.length??0,T=d.body?.innerHTML.length??0,A=d.head?.innerHTML.length??0;return`cd=same-origin readyState=${d.readyState} body[${m}children,${T}ch] head[${A}ch]`}catch(d){return`cd=cross-origin(${d.message.slice(0,30)})`}},bn=[],Bn=y=>{if(Ue())return;let d=y.message??String(y.error??"(no message)");d&&(d.toLowerCase().includes("paypal")||d.toLowerCase().includes("zoid")||d.toLowerCase().includes("postrobot")||d.toLowerCase().includes("storage"))&&(de(`window:error ${d.slice(0,140)}`),bn.push(d))},qe=y=>{if(Ue())return;let d=y.reason instanceof Error?y.reason.message:String(y.reason??"(no reason)");d&&(d.toLowerCase().includes("paypal")||d.toLowerCase().includes("zoid")||d.toLowerCase().includes("postrobot")||d.toLowerCase().includes("storage"))&&(de(`window:rejection ${d.slice(0,140)}`),bn.push(d))};Me&&typeof window<"u"&&(window.addEventListener("error",Bn),window.addEventListener("unhandledrejection",qe));let Mt={value:0};if(Me&&typeof PerformanceObserver<"u")try{on=new PerformanceObserver(y=>{if(!Ue())for(let d of y.getEntries()){if(!d.name.toLowerCase().includes("paypal"))continue;Mt.value+=1;let m=Math.round(d.duration);de(`net ${m}ms ${d.name.slice(0,90)}`)}}),on.observe({type:"resource",buffered:!0})}catch{}let Et=()=>{for(Tn?.disconnect(),Tn=null,on?.disconnect(),on=null;Qt.length;)clearTimeout(Qt.pop());Me&&typeof window<"u"&&(window.removeEventListener("error",Bn),window.removeEventListener("unhandledrejection",qe))},Mn=y=>{if(!y)return!1;let d=y.toLowerCase();return d.includes("zoid destroyed")||d.includes("destroyed all components")||d.includes("window closed")||d.includes("detected container element removed")},mr=y=>{if(Ue()||Mn(y))return;let d=fr(y)??y;Ke(()=>Pt.current?.(d))},er=y=>{Kt||(H(!0),y.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:",y))},an=(y,d=!1)=>{if(Kt)return;let m=Le.current||!ye;if(pr)return;pr=!0,Gn=!0,Et(),hn();let T=d||$i(y);if(T&&ye&&!Le.current){Le.current=!0,x(!1),He(!1),xe(!0),At.current?.("retrying"),Jn=setTimeout(()=>{Kt||te(A=>A+1)},ll);return}if(T||m){if(x(!1),He(!1),xe(!1),H(!0),At.current?.("exhausted"),!ae.current){ae.current=!0;let A=$i(y)?"paypal_init_timeout":d?"paypal_render_timeout":"paypal_init_failure";console.error("[FloPay] Direct PayPal initialization failed:",A)}return}er(y)};H(!1);let zt=async(y,d=nt.current)=>{if(Ue())return;let m=d?.sessionId??e;if(at.current){await at.current(y,{sessionId:m,accountPatch:d?.accountPatch,nonce:d?.nonce});return}let T=O.startTiming();O.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let A=()=>{O.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),O.performance({stage:"processing",durationMs:O.elapsed(T),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})};try{let me=zn.current,Xe=d?.accountPatch?.email??Jt.current,Q=d?.accountPatch?.userId??me?.customer?.id??me?.accountData?.userId??"",ne=d?.accountPatch?.firstName??me?.customer?.firstName??me?.accountData?.firstName,Se=d?.accountPatch?.lastName??me?.customer?.lastName??me?.accountData?.lastName,k=await new Vo.PaymentAPI(ft,{telemetry:!1}).processPayment(Q,{sessionId:m,nonce:d?.nonce??Ht.current,tokenizedData:y,accountData:{userId:Q,email:Xe??me?.customer?.email??"",...ne?{firstName:ne}:{},...Se?{lastName:Se}:{},country:d?.accountPatch?.country??me?.customer?.country??me?.accountData?.country??void 0,zip:d?.accountPatch?.zip??me?.customer?.zip??me?.accountData?.zip??void 0}});if(k.ok){if(Gn||Kt&&Nt.current)return;A(),O.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),Ke(()=>Tt.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(Ue())return;let W=await k.json().catch(()=>null),F=W?.message??"PayPal payment failed.",ee=fr(F)??F;A(),k.status===400&&(typeof W?.declineCode=="string"||!Array.isArray(W?.fields))?O.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):k.status===400||k.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:k.status>=500?"5xx":k.status>=400?"4xx":k.status>=300?"3xx":"unknown",failureCategory:k.status>=500?"server_error":void 0}),mr(ee),Ke(()=>Je.current?.(Ft("paypal",ee,{code:W?.code,declineCode:W?.declineCode})));return}catch(me){if(Ue())return;A(),O.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let Xe=me instanceof Error?me.message:"PayPal payment failed.",Q=fr(Xe)??Xe;mr(Q),Ke(()=>Je.current?.(Ft("paypal",Q)));return}},vn=()=>new It.FloPayError("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),_t=y=>Ue()?Promise.reject(vn()):Promise.resolve(y),U=async y=>{if(Ue())throw vn();ct||Yt();let d=nt.current,m=d?.sessionId??e,T=d?.nonce??Ht.current;O.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let A;try{A=await new Vo.PaymentAPI(ft,{telemetry:!1}).createSessionIntent(m,T??"",tt?{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:It.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE,paymentMethodId:null,intentKind:ce==="setup_token"?"setup":"payment"}:{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"},{idempotencyKey:wt})}catch(me){throw O.error({...(0,It.classifyTelemetryFailure)(me,"PAYMENT_PROCESSING_FAILED","unknown"),stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"}),me}if(Ue())throw vn();if(A.provider!=="paypal"||A.providerObjectType!==ce)throw new Error(y);return O.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),A.providerObjectId},V=(y,d)=>{let m=d?.nonce??Ht.current;if(!m)return;let T=d?.sessionId??e,A=qr(y)??rr(y)??"provider_declined";new Vo.PaymentAPI(ft,{telemetry:!1}).reportSessionIntentDecline(T,m,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:A}).catch(()=>{})},Y=fe;de("loadScript:scheduled (deferred 1 tick)");let le=null,Ae=setTimeout(()=>{if(Kt){de("loadScript:skipped (cancelled before defer ran)");return}de("loadScript:start");let y=Wn==="live"?"production":Wn;le=(0,ji.loadScript)({clientId:u,currency:P,...ce==="subscription"?{intent:"subscription",vault:!0}:ce==="order"?{intent:"capture"}:{},...y?{environment:y}:{},...y==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}}),le.then(d=>{if(de(`loadScript:resolved inactive=${Ue()} ns=${!!d} buttons=${!!d?.Buttons}`),Ue())return;if(!d?.Buttons){de("FAIL: namespace missing Buttons factory"),an("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(_e.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),O.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let m=async(ne,Se)=>{if(Ue()||Fe.current!==Y)return;let z=ne.vaultSetupToken??ne.subscriptionID??ne.orderID??"",k=z?cr.current.get(z):it.current.get(Y);if(!(!k||!ur(k.generation))&&Ot(k.generation)){cr.current.delete(z),it.current.delete(k.surfaceKey),$n();try{if(He(!0),Ke(()=>Pt.current?.(null)),!z)throw new It.FloPayError("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});let W=zn.current,F=Sr(xn.current??[W?.customer?.firstName,W?.customer?.lastName].filter(Boolean).join(" ")),ee=nn({email:k.accountPatch?.email?.trim()||Jt.current?.trim()||W?.customer?.email?.trim(),firstName:k.accountPatch?.firstName?.trim()||F.firstName,lastName:k.accountPatch?.lastName?.trim()||F.lastName});if(!(0,It.isValidEmail)(ee.email)||!(ee.firstName||ee.lastName))try{let Ve=ml(await Se?.order?.get?.());ee=nn({email:Ve.email||ee.email,firstName:Ve.firstName||ee.firstName,lastName:Ve.lastName||ee.lastName})}catch{}if((dn.current||et)&&!(0,It.isValidEmail)(ee.email)){let Ve=await ie("PayPal",ee);if(!Ve)return;ee=Ve}(0,It.isValidEmail)(ee.email)&&(k.accountPatch=nn({...k.accountPatch,...ee}),await dn.current?.(ee)),await zt(ce==="setup_token"?{id:z,type:"paypal_setup_token",isPaypal:!0,gateway:"paypal",paymentMethodType:It.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE}:tt?{id:z,isPaypal:!0,gateway:"paypal",paymentMethodType:It.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE}:{id:z,isPaypal:!0},k)}catch(W){mr(W instanceof Error?W.message:"PayPal capture failed.")}finally{Ue()||He(!1)}}},T=d.Buttons({style:{layout:"horizontal",height:Ko,tagline:!1},onClick:async(ne,Se)=>{if(Ue()){await Se.reject();return}Yt();let z=_n.current,k={};if(z)try{let ee=await z("paypal");if(Ue()){await Se.reject();return}if(!ee.proceed){nt.current=null,it.current.delete(Y),await Se.reject();return}k={sessionId:ee.sessionId,accountPatch:ee.accountPatch,nonce:ee.nonce}}catch(ee){de(`onClick:runBeforeButtonClick rejected msg=${(ee instanceof Error?ee.message:String(ee)).slice(0,120)}`),nt.current=null,it.current.delete(Y),await Se.reject();return}Ke(()=>jt.current?.("paypal"));let F={generation:dr(),surfaceKey:Y,...k};nt.current=F,it.current.set(Y,F),await Se.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"}),Zn=O.startTiming()},createOrder:ce==="order"?he?()=>_t(he).then(fn):()=>U("Failed to create PayPal order.").then(fn):void 0,createSubscription:ce==="subscription"?he?()=>_t(he).then(fn):()=>U("Failed to create PayPal subscription.").then(fn):void 0,createVaultSetupToken:ce==="setup_token"?()=>U("Failed to create PayPal setup token.").then(fn):void 0,onApprove:m,onCancel:()=>{if(Ue())return;let ne=it.current.get(Y)??nt.current;ne&&it.current.delete(ne.surfaceKey),nt.current=null,$n(),O.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),ke.current=!0,ue({generation:ne?.generation,remount:!0,focus:!1})},onError:ne=>{if(Ue()||Fe.current!==Y)return;let Se=ne instanceof Error?ne.message:"PayPal failed to render.";if(de(`onError rendered=${Zt} msg=${Se.slice(0,120)}`),Zt){let z=it.current.get(Y)??nt.current;if(z&&!ur(z.generation)||!z&&Un.current===un.current)return;if(Mn(Se)){Ot(z?.generation);return}if($n(),uo(ne)){O.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),V(ne,z),Ke(()=>Je.current?.(Ft("paypal",Se))),z&&it.current.delete(z.surfaceKey),nt.current=null,Ot(z?.generation);return}let k=Se.toLowerCase();O.error({errorCode:k.includes("popup")&&k.includes("block")?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),z&&it.current.delete(z.surfaceKey),nt.current=null,ue({generation:z?.generation,remount:!0,showRetry:!0,focus:!0}),mn(ne,{code:"paypal_runtime_failed"});return}an(Se)}}),A=T.isEligible();if(de(`isEligible=${A}`),O.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!A){x(!1),an("PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}Xn=T,Me&&de(`container:dims ${en(bt)} visibility=${typeof document<"u"?document.visibilityState:"(no document)"}`),Me&&typeof MutationObserver<"u"&&(Tn=new MutationObserver(ne=>{if(!Ue()){for(let Se of ne)if(Se.type==="childList")Se.addedNodes.forEach(z=>{if(!(z instanceof Element))return;let k=z.tagName.toLowerCase(),W=(z.getAttribute("title")??"").slice(0,40),F=k==="iframe"?` ${Qn(z)}`:"";de(`child+ ${k}${W?` title="${W}"`:""}${F} dims=${en(z)}`)});else if(Se.type==="attributes"&&Se.target instanceof Element){let z=Se.target;if(z.tagName.toLowerCase()!=="iframe")continue;let k=Se.attributeName;(k==="src"||k==="srcdoc")&&de(`attr~ iframe ${k}=${k==="srcdoc"?`[${(z.getAttribute("srcdoc")??"").length}ch]`:st(z.getAttribute("src"))} dims=${en(z)}`)}}}),Tn.observe(bt,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let Xe=ne=>{if(Ue()||Zt)return;let Se=bt.querySelectorAll("iframe"),z=typeof document<"u"&&"hasStorageAccess"in document;de(`watchdog:${ne} container=${en(bt)} children=${bt.childElementCount} iframes=${Se.length} visibility=${typeof document<"u"?document.visibilityState:"(no document)"} cookies=${typeof navigator<"u"?navigator.cookieEnabled:"?"} hasStorageAccessApi=${z} paypalNetRequests=${Mt.value}`),Se.forEach((k,W)=>{let F=(k.getAttribute("title")??"").slice(0,40);de(` iframe[${W}] ${en(k)}${F?` title="${F}"`:""} ${Qn(k)}`);let ee=An(k);ee&&de(` ${ee}`)}),bn.length===0&&de(" (no PayPal/zoid window errors captured)")};Me&&(Qt.push(setTimeout(()=>Xe("3s"),3e3)),Qt.push(setTimeout(()=>Xe("8s"),8e3)),Qt.push(setTimeout(()=>Xe("15s"),15e3))),de("render:start");let Q=O.startTiming();Qt.push(setTimeout(()=>{Ue()||Zt||(de("watchdog:11s retryable render timeout"),an("PayPal Buttons render did not settle within 11000ms.",!0))},cl)),T.render(bt).then(()=>{if(de(`render:resolved inactive=${Ue()}`),Et(),Ue()){hn();return}Zt=!0,x(!0),xe(!1),At.current?.("ready"),O.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),O.performance({stage:"checkout_render",durationMs:O.elapsed(Q),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}).catch(ne=>{let Se=ne instanceof Error?ne.message:"PayPal failed to render.";de(`render:rejected msg=${Se.slice(0,120)}`),Et(),an(Se)})}).catch(d=>{let m=d instanceof Error?d.message:"PayPal SDK failed to load.";de(`loadScript:rejected msg=${m.slice(0,120)}`),an(m)})},0);return()=>{Kt=!0,clearTimeout(Ae),Jn&&clearTimeout(Jn),Et(),hn()}},[ye,ft,u,P,c,ce,tt,e,he,fe,O,ie,et]);let gn=Me?(0,In.jsxs)("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:Z?"#fef2f2":"#f3f4f6",border:`1px solid ${Z?"#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=${Ce} failed=${Z})`,w.length===0?`
1
+ "use strict";var js=Object.create;var Uo=Object.defineProperty;var Vs=Object.getOwnPropertyDescriptor;var Ks=Object.getOwnPropertyNames;var Hs=Object.getPrototypeOf,Ys=Object.prototype.hasOwnProperty;var Ws=(e,t)=>{for(var n in t)Uo(e,n,{get:t[n],enumerable:!0})},Ti=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Ks(t))!Ys.call(e,o)&&o!==n&&Uo(e,o,{get:()=>t[o],enumerable:!(r=Vs(t,o))||r.enumerable});return e};var Mi=(e,t,n)=>(n=e!=null?js(Hs(e)):{},Ti(t||!e||!e.__esModule?Uo(n,"default",{value:e,enumerable:!0}):n,e)),Gs=e=>Ti(Uo({},"__esModule",{value:!0}),e);var Yl={};Ws(Yl,{DirectPayPalButton:()=>go,FloPayAutomaticPaymentButton:()=>Cs,FloPayCardSetup:()=>ws,FloPayCardSetupError:()=>Ro,FloPayCheckout:()=>la,FloPayProvider:()=>bo,SplitCardForm:()=>oa,VaultCardFields:()=>Gr,dropThirdPartyOnlyError:()=>ks.dropThirdPartyOnlyError,useCheckout:()=>zi,useFloPay:()=>ir,usePayPalFloPay:()=>Vo});module.exports=Gs(Yl);var ks=require("@flopay/shared");var ca=require("@flopay/js"),vn=require("@flopay/shared"),Ke=require("react");var St=require("react/jsx-runtime");function Js(){return(0,St.jsxs)(St.Fragment,{children:[(0,St.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,St.jsx)("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),(0,St.jsx)("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",(0,St.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,St.jsx)("path",{d:"M9 18l6-6-6-6"})})]})}function Xs(){return(0,St.jsx)(St.Fragment,{children:"Go back"})}function Zs(){return(0,St.jsx)(St.Fragment,{children:"Secure card checkout"})}function Lr(e){return e!==void 0&&(e===""||e===null||e===!1)}function Nr({content:e}){return(0,St.jsx)(St.Fragment,{children:e===void 0?(0,St.jsx)(Js,{}):e})}function Or({content:e}){return(0,St.jsx)(St.Fragment,{children:e===void 0?(0,St.jsx)(Xs,{}):e})}function uo({content:e}){return(0,St.jsx)(St.Fragment,{children:e===void 0?(0,St.jsx)(Zs,{}):e})}var rr=require("@flopay/shared");function zr(e,t,n,r={}){let o;return(i={})=>{if(o)return o;let d={...r,...i,email:i.email?.trim()||r.email?.trim()};if(!(0,rr.isValidEmail)(d.email))return Promise.reject(new rr.FloPayError("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}));let c={};for(let[v,y]of Object.entries(d)){if(typeof y!="string")continue;let g=y.trim();g&&(c[v]=g)}return o=e.claimCheckoutSession(t,n,{accountData:c}),o.catch(()=>{}),o}}function Ai(e,t){return t?e?{account:{...e.account??{},...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,..."checkoutMetadata"in t?{checkoutMetadata:t.checkoutMetadata}:"checkoutMetadata"in e?{checkoutMetadata:e.checkoutMetadata}:{},tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}:t:e}function Ra(e,t){return t?{...e,account:{...e.account,...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,..."checkoutMetadata"in t?{checkoutMetadata:t.checkoutMetadata}:{},tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}:e}function Bi(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 kr(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 Ea(e,t){return t?{...e,...t}:e}function Ut(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 Qs=[{match:/^paypal authorization required\.?$/i,replacement:"For your additional security, please re-authenticate this payment via PayPal."}];function hr(e){if(typeof e!="string")return e??void 0;let t=e.trim();if(!t)return e;for(let{match:n,replacement:r}of Qs)if(n.test(t))return r;return e}function Ir(e,t){return e.status!=="authorized"?{status:"succeeded"}:{status:"authorized",paymentId:e.paymentId,sessionId:e.id||t||void 0,authorizationExpiresAt:e.authorizationExpiresAt}}function Ur(e){return e?.status==="authorized"||e?.status==="complete"}function Fi(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function qo(e){let t=Fi(e);return new rr.FloPayError(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function $o(e){let t=Fi(e);return new rr.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 jo(e,t){return e==="processing"||(0,rr.isMoneySettledOutcome)(e,t)}function Di(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}function Li(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?{mode:"setup"}:{mode:"payment",amount:e}}function po(e){let t=[e?.id,e?.originalPaymentMethodId];for(let n of t)if(typeof n=="string"&&n.startsWith("pm_"))return n}var xr=require("@flopay/js"),Ce=require("@flopay/shared"),w=Mi(require("react"),1);var _a=require("react"),An=(0,_a.createContext)({flopay:null,paypalFlopay:null,billingApiUrl:""}),$n=(0,_a.createContext)({session:null,loading:!1,error:null});var Yo=require("@flopay/js"),xt=require("@flopay/shared"),Vi=require("@paypal/paypal-js"),E=require("react");var Ni=require("@flopay/shared"),jn=require("react"),or=require("react/jsx-runtime");function an(e){let{firstName:t,lastName:n,...r}=e,o=t?.trim(),i=n?.trim();return{...r,...o?{firstName:o}:{},...i?{lastName:i}:{}}}function qr(){let[e,t]=(0,jn.useState)(null),n=(0,jn.useRef)(null),r=(0,jn.useRef)(0),o=(0,jn.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,jn.useCallback)(d=>{let c=n.current;n.current=null,t(null),c?.(d)},[]);return(0,jn.useEffect)(()=>()=>{n.current?.(null),n.current=null},[]),{request:e,collect:o,finish:i}}function $r({identity:e,methodLabel:t,onComplete:n,onCancel:r,submitting:o=!1,testId:i="flopay-buyer-identity-pane"}){let[d,c]=(0,jn.useState)(e.email?.trim()??""),v=(0,Ni.isValidEmail)(d.trim());return(0,or.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,or.jsxs)("div",{style:{fontWeight:700},children:["Continue with ",t]}),(0,or.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",(0,or.jsx)("input",{type:"email",autoComplete:"email","data-testid":"flopay-email",required:!0,value:d,onChange:y=>c(y.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]}),(0,or.jsxs)("div",{style:{display:"flex",gap:"0.5rem"},children:[r&&(0,or.jsx)("button",{type:"button",onClick:r,style:{flex:1,minHeight:42},children:"Cancel"}),(0,or.jsxs)("button",{type:"button",disabled:!v||o,onClick:()=>{n(an({...e,email:d.trim()}))},style:{flex:2,minHeight:42},children:["Continue with ",t]})]})]})}function el(e){if(e instanceof Error)return e.message;if(typeof e=="object"&&e!==null){let t=e.message;return typeof t=="string"?t:void 0}return typeof e=="string"?e:void 0}function Rr(e){if(typeof e!="string")return;let t=e.trim();return/^[a-z0-9_.-]{1,64}$/i.test(t)?t:void 0}function ar(e){if(typeof e!="object"||e===null)return;let t=e;return Rr(t.code)??Rr(t.type)??Rr(t.name)}function jr(e){if(!(typeof e!="object"||e===null))return Rr(e.decline_code)}function mo(e){return typeof e!="object"||e===null?!1:Rr(e.type)?.toLowerCase()==="card_error"||jr(e)!==void 0}function br(e){let t=el(e)?.toLowerCase()??"",r=`${ar(e)?.toLowerCase()??""} ${t}`;return r.includes("popup")&&r.includes("block")}var Oi=require("@flopay/shared"),yo=require("react");function ir(){return(0,yo.useContext)(An).flopay}function Vo(){return(0,yo.useContext)(An).paypalFlopay??null}function zi(){return(0,yo.useContext)($n)}function Ui(){return(0,yo.useContext)(An).billingApiUrl||(0,Oi.resolveBillingApiUrl)()}var qi=require("@flopay/shared"),Er=require("react");function at(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 Ko=require("react"),fo=typeof window>"u"?Ko.useEffect:Ko.useLayoutEffect;var tl={"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 nl(e){return e==="stripe"||e==="paypal"?e:void 0}function rl(e){let t=nl(e.provider),n={schemaVersion:qi.FLO_INSTRUMENT_SCHEMA_VERSION,...t?{gateway:t}:{}};if(e.class==="lifecycle"){let r=tl[e.name];return r?{...n,name:r}:null}return e.class==="card_surface"?{...n,name:"card_expanded"}:e.errorCode==="CHECKOUT_SESSION_CREATE_FAILED"?{...n,name:"checkout_error",phase:"session_create"}:e.errorCode==="SDK_INITIALIZATION_FAILED"||e.errorCode==="PROVIDER_LOAD_FAILED"?{...n,name:"checkout_error",phase:"sdk_load"}:e.errorCode==="PAYMENT_PROCESSING_FAILED"?{...n,name:"checkout_error",phase:e.requestCategory==="intent_create"?"wallets":"process"}:null}var xa=new Set(["checkout_mount","sdk_loaded","form_rendered","card_expanded"]);function Vr(e,t){let n=(0,Er.useRef)(e);n.current=e;let r=(0,Er.useRef)(new Set),o=(0,Er.useRef)(t),i=(0,Er.useRef)(t);return fo(()=>{i.current=t,o.current!==t&&(o.current=t,r.current.clear())},[t]),(0,Er.useCallback)(d=>{if(i.current!==t)return;let c=rl(d);if(c){if(xa.has(c.name)){if(r.current.has(c.name))return;r.current.add(c.name)}at(()=>n.current?.(c))}},[t])}var ol=Symbol.for("@flopay/js.telemetry.bridge.v1"),al=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function il(){return{error:()=>{},log:()=>{},performance:()=>{},terminal:()=>{},now:()=>globalThis.performance?.now()??0,elapsed:e=>Math.max(0,(globalThis.performance?.now()??e)-e),setCheckoutContext:()=>{},beginCheckout:()=>globalThis.performance?.now()??0,disable:()=>{},subscribe:()=>()=>{},flush:async()=>{},destroy:()=>{}}}function sl(e){let t=il(),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 Ho(e){let t=globalThis[al];return sl(t?.(e)??{})}function qt(e){if(e)return e[ol]}var Bn=require("react/jsx-runtime"),Wo=45,ll=1e3,cl=11e3,dl=["https://www.paypal.com","https://www.sandbox.paypal.com"],$i="We couldn't open PayPal. Try again or choose another payment method.",ul={width:"100%",minHeight:Wo,margin:"0 0 0.5rem",padding:"0.75rem 0.875rem",border:"1px solid #2563eb",borderRadius:8,background:"#eff6ff",color:"#1d4ed8",fontSize:"0.95rem",fontWeight:700,cursor:"pointer"};function ji(e){return e.includes("No ack for postMessage init()")&&dl.some(t=>e.includes(t))&&e.includes("10000ms")}function pl(e){return e?`${$i} Allow pop-ups for this site, then try again.`:$i}function ml(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 Ki({sessionId:e,nonce:t,billingApiUrl:n,email:r,billingName:o,onBuyerIdentityReady:i,clientId:d,environment:c,currency:v,isSubscription:y,providerObjectType:g,onTokenizedBody:b,onComplete:B,onErrorChange:T,onDecline:p,onTechnicalFailure:P,isProcessing:he=!1,onLoadStateChange:q,onInitializationStateChange:S,allowAutomaticRetry:ue=!0,onButtonClick:$,runBeforeButtonClick:ce,session:W,existingOrderId:be,telemetry:He,telemetryContext:we,onInstrument:vt,debug:$e=!1}){let xe=ir(),Te=Vr(vt,e),ne=(0,E.useMemo)(()=>{if(xe)return null;let A=Ho({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:xt.SDK_VERSION,enabled:He!==!1});return A.setCheckoutContext(we??{}),A.beginCheckout(we??{}),A},[n,xe,He,we?.checkoutMode,we?.layout]),re=(0,E.useMemo)(()=>qt(xe),[xe]);(0,E.useEffect)(()=>()=>{ne&&ne.flush().catch(()=>{}).finally(()=>ne.destroy())},[ne]);let L=(0,E.useMemo)(()=>({error:A=>{re?re.error(A):ne?.error(A),Te({class:"technical_error",errorCode:A.requestCategory==="intent_create"?"PAYMENT_PROCESSING_FAILED":A.errorCode,requestCategory:A.requestCategory,provider:A.provider})},log:A=>{re?re.log(A):ne?.log(A),Te({class:"lifecycle",name:A.name,provider:A.provider})},performance:A=>{re?re.performance(A):ne?.performance(A)},terminal:A=>{re?re.terminal(A):ne?.terminal(A)},startTiming:()=>re?.now()??ne?.now()??0,elapsed:A=>re?.elapsed(A)??Math.max(0,(ne?.now()??A)-A)}),[Te,re,ne]),Me=(0,E.useRef)(null),Ae=(0,E.useRef)(0),X=(0,E.useRef)(null),Ie=(0,E.useRef)(!1),[Se,x]=(0,E.useState)(!1),[U,Be]=(0,E.useState)(!1),[me,ee]=(0,E.useState)(0),Le=(0,E.useRef)(0),[rt,pt]=(0,E.useState)(!1),qe=(0,E.useRef)(!1),te=(0,E.useRef)(!1),[G,H]=(0,E.useState)(!1),[Fe,Xe]=(0,E.useState)(!1),{request:M,collect:oe,finish:D}=qr(),I=(0,E.useRef)({sessionId:e,required:!(0,xt.isValidEmail)(r?.trim()||W?.customer?.email?.trim())});I.current.sessionId!==e&&(I.current={sessionId:e,required:!(0,xt.isValidEmail)(r?.trim()||W?.customer?.email?.trim())});let lt=I.current.required,Pt=(0,E.useMemo)(()=>n.replace(/\/+$/,""),[n]),ie=g??(y?"subscription":"order"),ct=g==="order"||g==="setup_token",et=(0,E.useMemo)(()=>JSON.stringify([Pt,d,v,c??"",ie,ct,e,be??""]),[Pt,d,v,c,be,ie,ct,e]),Ct=(0,E.useRef)(et),kt=Ct.current!==et,C=(0,E.useRef)($e),Z=(0,E.useRef)(null),[dt,yt]=(0,E.useState)([]),ye=(0,E.useCallback)(A=>{C.current&&yt(Dt=>[...Dt,`${new Date().toISOString().slice(11,23)} ${A}`])},[]);(0,E.useEffect)(()=>{C.current=$e,$e&&ye("debug:enabled"),Z.current?.setEnabled($e)},[ye,$e]);let It=(0,E.useRef)(b),it=(0,E.useRef)(B),Ye=(0,E.useRef)(T),Nt=(0,E.useRef)(p),$t=(0,E.useRef)(P),Yt=(0,E.useRef)($),Ln=(0,E.useRef)(q),tn=(0,E.useRef)(S),Kn=(0,E.useRef)(i),sn=(0,E.useRef)(ce),Cn=(0,E.useRef)(W),nn=(0,E.useRef)(r),Ot=(0,E.useRef)(o),Sn=(0,E.useRef)(t),tt=(0,E.useRef)(null),ur=(0,E.useRef)(0),ot=(0,E.useRef)(null),Nn=(0,E.useRef)(null),ft=(0,E.useRef)(new Map),jt=(0,E.useRef)(new Map),ln=(0,E.useRef)(!1);(0,E.useEffect)(()=>(ln.current=!0,()=>{ln.current=!1}),[]),(0,E.useEffect)(()=>{It.current=b},[b]),(0,E.useEffect)(()=>{Kn.current=i},[i]),(0,E.useEffect)(()=>{it.current=B},[B]),(0,E.useEffect)(()=>{Ye.current=T},[T]),(0,E.useEffect)(()=>{Nt.current=p},[p]),(0,E.useEffect)(()=>{$t.current=P},[P]),(0,E.useEffect)(()=>{Yt.current=$},[$]),(0,E.useEffect)(()=>{Ln.current=q},[q]),(0,E.useEffect)(()=>{tn.current=S},[S]),(0,E.useEffect)(()=>{sn.current=ce},[ce]),(0,E.useEffect)(()=>{Cn.current=W},[W]),(0,E.useEffect)(()=>{nn.current=r},[r]),(0,E.useEffect)(()=>{Ot.current=o},[o]),(0,E.useEffect)(()=>{Sn.current=t},[t]),(0,E.useEffect)(()=>{Le.current=me},[me]),(0,E.useEffect)(()=>{rt&&X.current?.focus()},[rt,me]);let wn=(0,E.useCallback)(()=>{window.setTimeout(()=>{X.current?.focus()},0)},[]),kn=(0,E.useCallback)(()=>{x(!1),ee(A=>A+1)},[]),Jt=(0,E.useCallback)(()=>{pt(!1),(Me.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??Me.current)?.focus?.()},[]);(0,E.useEffect)(()=>{!Se||!Ie.current||(Ie.current=!1,Jt())},[Jt,Se,me]);let Qn=(0,E.useCallback)((A,Dt)=>{let Rt=$t.current;if(Rt){Rt("paypal",A,Dt);return}Ye.current?.(pl(Dt?.popupBlocked??br(A)))},[]),Mt=()=>{ot.current?.timer&&(clearTimeout(ot.current.timer),ot.current.timer=null)},le=()=>{Mt();let A=ur.current+1;return ur.current=A,Nn.current=null,ot.current={generation:A,timer:null,yieldedControl:!1},pt(!1),A},er=A=>A!==void 0&&ot.current?.generation!==A?!1:(Mt(),ot.current=null,Nn.current=null,!0),cn=A=>{let Dt=A?.generation??ot.current?.generation??ur.current;(!A?.generation||ot.current?.generation===Dt)&&(Mt(),ot.current=null),Nn.current=Dt,A?.showRetry&&pt(!0),A?.remount&&kn(),A?.focus!==!1&&wn()},dn=A=>ot.current?.generation===A&&Nn.current!==A,pr=A=>{typeof document<"u"&&document.visibilityState!=="visible"||(Mt(),A.timer=setTimeout(()=>{ot.current?.generation===A.generation&&(ot.current=null,Nn.current=A.generation,Qn(new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}),pt(!0),kn(),wn())},600))},Hn=()=>{let A=ot.current;A?.yieldedControl&&pr(A)},tr=()=>{let A=ot.current;A&&(A.yieldedControl=!0,Mt())},Xt=A=>{let Dt=tt.current;return Dt&&jt.current.set(A,Dt),A};(0,E.useEffect)(()=>{let A=()=>{document.visibilityState==="visible"?Hn():tr()};return document.addEventListener("visibilitychange",A),window.addEventListener("focus",Hn),window.addEventListener("blur",tr),()=>{document.removeEventListener("visibilitychange",A),window.removeEventListener("focus",Hn),window.removeEventListener("blur",tr),Mt()}},[]),(0,E.useEffect)(()=>{Ct.current!==et&&(Ct.current=et,qe.current=!1,te.current=!1,x(!1),Be(!1),H(!1),tn.current?.("loading"))},[et]),(0,E.useEffect)(()=>{at(()=>Ln.current?.(Se&&!G))},[Se,G]);let Je=(0,xt.normalizeGatewayEnvironment)(c);(0,E.useEffect)(()=>{let A=d?`${d.slice(0,6)}\u2026(len ${d.length})`:"(empty)",Dt=typeof navigator<"u"?navigator.userAgent:"(no navigator)";if(ye(`mount clientId=${A} env=${c??"(unset)"}\u2192${Je??"live"} ccy=${v} sub=${y}`),ye(`ua=${Dt.slice(0,80)}${Dt.length>80?"\u2026":""}`),!d){ye("FAIL: clientId empty \u2014 gateway misconfigured"),H(!0),L.error({errorCode:"CONFIGURATION_INVALID",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),console.error("[FloPay] DirectPayPal: clientId empty \u2014 gateway misconfigured");return}if(!Me.current){ye("FAIL: containerRef not attached");return}Ae.current=L.startTiming(),L.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let Rt=!1,Et=!1,fe=()=>Rt||Et,Wt,mr=!1,yr=()=>{Wt=(0,xt.generateIdempotencyKey)(),Wt||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),mr=!0},nr=null,Pr=!1,Rn=null,Cr=!1,Yn=()=>{!Rn||Cr||(Cr=!0,Rn.close().catch(()=>{}))},un=null,At=()=>{un!==null&&(L.log({name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal"}),L.performance({stage:"overlay_return",durationMs:L.elapsed(un),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal"}),un=null)},rn=!1,Zt=Me.current,En=null,pn=null,st=[],mn=null,yn=!1,fn=!1,gn=null,Ne=R=>{if(!R||typeof R.getBoundingClientRect!="function")return"(no rect)";let f=R.getBoundingClientRect();return`${Math.round(f.width)}\xD7${Math.round(f.height)}`},Gt=R=>{if(!R)return"(empty)";try{let f=new URL(R,typeof window<"u"?window.location.href:"https://localhost"),m=f.pathname.toLowerCase();return m.includes("checkcaptcha")||m.includes("captcha")?`CAPTCHA(${f.host}${m})`:m.includes("risk")||m.includes("challenge")?`RISK(${f.host}${m})`:m.includes("smart/buttons")?`smart-buttons(${f.host})`:`${f.host}${m}`.slice(0,100)}catch{return R.slice(0,80)}},Bt=R=>{let f=R.getAttribute("src"),m=R.getAttribute("srcdoc"),J=R.getAttribute("name"),ke=R.getAttribute("sandbox"),ge=[];return f&&ge.push(`src=${Gt(f)}`),m&&ge.push(`srcdoc[${m.length}ch]`),!f&&!m&&ge.push("src=(empty) srcdoc=(empty)"),J&&ge.push(`name=${J.slice(0,40)}`),ke!==null&&ge.push(`sandbox="${ke.slice(0,40)}"`),ge.join(" ")},fr=R=>{if(!(R instanceof HTMLIFrameElement))return"";try{let f=R.contentDocument;if(!f)return"cd=null";let m=f.body?.children.length??0,J=f.body?.innerHTML.length??0,ke=f.head?.innerHTML.length??0;return`cd=same-origin readyState=${f.readyState} body[${m}children,${J}ch] head[${ke}ch]`}catch(f){return`cd=cross-origin(${f.message.slice(0,30)})`}},On=[],gr=R=>{if(fe())return;let f=R.message??String(R.error??"(no message)");f&&(f.toLowerCase().includes("paypal")||f.toLowerCase().includes("zoid")||f.toLowerCase().includes("postrobot")||f.toLowerCase().includes("storage"))&&(ye(`window:error ${f.slice(0,140)}`),On.push(f))},zn=R=>{if(fe())return;let f=R.reason instanceof Error?R.reason.message:String(R.reason??"(no reason)");f&&(f.toLowerCase().includes("paypal")||f.toLowerCase().includes("zoid")||f.toLowerCase().includes("postrobot")||f.toLowerCase().includes("storage"))&&(ye(`window:rejection ${f.slice(0,140)}`),On.push(f))},hn={value:0},zt=()=>{for(En?.disconnect(),En=null,pn?.disconnect(),pn=null;st.length;)clearTimeout(st.pop());fn=!1,yn&&typeof window<"u"&&(window.removeEventListener("error",gr),window.removeEventListener("unhandledrejection",zn)),yn=!1},Mr=()=>{if(!(yn||fe()||rn)){if(yn=!0,On.length=0,hn.value=0,typeof window<"u"&&(window.addEventListener("error",gr),window.addEventListener("unhandledrejection",zn)),typeof PerformanceObserver<"u")try{pn=new PerformanceObserver(R=>{if(!fe())for(let f of R.getEntries()){if(!f.name.toLowerCase().includes("paypal"))continue;hn.value+=1;let m=Math.round(f.duration);ye(`net ${m}ms ${f.name.slice(0,90)}`)}}),pn.observe({type:"resource",buffered:!0})}catch{}gn?.()}},_n=()=>{mn&&(clearTimeout(mn),mn=null)},O=()=>{zt(),_n()},z={setEnabled:R=>{R?Mr():zt()}};Z.current=z,C.current&&Mr();let Q=R=>{if(!R)return!1;let f=R.toLowerCase();return f.includes("zoid destroyed")||f.includes("destroyed all components")||f.includes("window closed")||f.includes("detected container element removed")},F=R=>{if(fe()||Q(R))return;let f=hr(R)??R;at(()=>Ye.current?.(f))},je=R=>{Rt||(H(!0),R.includes("paypal_ineligible")||L.error({errorCode:"PROVIDER_LOAD_FAILED",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime"}),console.error("[FloPay] DirectPayPal load/render failure:",R))},ae=(R,f=!1)=>{if(Rt)return;let m=qe.current||!ue;if(Pr)return;Pr=!0,Et=!0,O(),Yn();let J=f||ji(R);if(J&&ue&&!qe.current){qe.current=!0,x(!1),Xe(!1),Be(!0),tn.current?.("retrying"),nr=setTimeout(()=>{Rt||ee(ke=>ke+1)},ll);return}if(J||m){if(x(!1),Xe(!1),Be(!1),H(!0),tn.current?.("exhausted"),!te.current){te.current=!0;let ke=ji(R)?"paypal_init_timeout":f?"paypal_render_timeout":"paypal_init_failure";console.error("[FloPay] Direct PayPal initialization failed:",ke)}return}je(R)};H(!1);let N=async(R,f=tt.current)=>{if(fe())return;let m=f?.sessionId??e;if(It.current){await It.current(R,{sessionId:m,accountPatch:f?.accountPatch,nonce:f?.nonce});return}let J=L.startTiming();L.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let ke=()=>{L.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),L.performance({stage:"processing",durationMs:L.elapsed(J),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})};try{let ge=Cn.current,se=f?.accountPatch?.email??nn.current,Ee=f?.accountPatch?.userId??ge?.customer?.id??ge?.accountData?.userId??"",j=f?.accountPatch?.firstName??ge?.customer?.firstName??ge?.accountData?.firstName,V=f?.accountPatch?.lastName??ge?.customer?.lastName??ge?.accountData?.lastName,_e=await new Yo.PaymentAPI(Pt,{telemetry:!1}).processPayment(Ee,{sessionId:m,nonce:f?.nonce??Sn.current,tokenizedData:R,accountData:{userId:Ee,email:se??ge?.customer?.email??"",...j?{firstName:j}:{},...V?{lastName:V}:{},country:f?.accountPatch?.country??ge?.customer?.country??ge?.accountData?.country??void 0,zip:f?.accountPatch?.zip??ge?.customer?.zip??ge?.accountData?.zip??void 0}});if(_e.ok){if(Et||Rt&&ln.current)return;ke(),L.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),at(()=>it.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(fe())return;let mt=await _e.json().catch(()=>null),We=mt?.message??"PayPal payment failed.",Lt=hr(We)??We;ke(),_e.status===400&&(typeof mt?.declineCode=="string"||!Array.isArray(mt?.fields))?L.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):_e.status===400||_e.status===422?L.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx"}):L.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:_e.status>=500?"5xx":_e.status>=400?"4xx":_e.status>=300?"3xx":"unknown",failureCategory:_e.status>=500?"server_error":void 0}),F(Lt),at(()=>Nt.current?.(Ut("paypal",Lt,{code:mt?.code,declineCode:mt?.declineCode})));return}catch(ge){if(fe())return;ke(),L.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let se=ge instanceof Error?ge.message:"PayPal payment failed.",Ee=hr(se)??se;F(Ee),at(()=>Nt.current?.(Ut("paypal",Ee)));return}},h=()=>new xt.FloPayError("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),pe=R=>fe()?Promise.reject(h()):Promise.resolve(R),de=async R=>{if(fe())throw h();mr||yr();let f=tt.current,m=f?.sessionId??e,J=f?.nonce??Sn.current;L.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let ke;try{ke=await new Yo.PaymentAPI(Pt,{telemetry:!1}).createSessionIntent(m,J??"",ct?{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:xt.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE,paymentMethodId:null,intentKind:ie==="setup_token"?"setup":"payment"}:{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"},{idempotencyKey:Wt})}catch(ge){throw L.error({...(0,xt.classifyTelemetryFailure)(ge,"PAYMENT_PROCESSING_FAILED","unknown"),stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"}),ge}if(fe())throw h();if(ke.provider!=="paypal"||ke.providerObjectType!==ie)throw new Error(R);return L.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),ke.providerObjectId},Oe=(R,f)=>{let m=f?.nonce??Sn.current;if(!m)return;let J=f?.sessionId??e,ke=jr(R)??ar(R)??"provider_declined";new Yo.PaymentAPI(Pt,{telemetry:!1}).reportSessionIntentDecline(J,m,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:ke}).catch(()=>{})},Ze=me;ye("loadScript:scheduled (deferred 1 tick)");let ze=null,Re=setTimeout(()=>{if(Rt){ye("loadScript:skipped (cancelled before defer ran)");return}ye("loadScript:start");let R=Je==="live"?"production":Je;ze=(0,Vi.loadScript)({clientId:d,currency:v,...ie==="subscription"?{intent:"subscription",vault:!0}:ie==="order"?{intent:"capture"}:{},...R?{environment:R}:{},...R==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}}),ze.then(f=>{if(ye(`loadScript:resolved inactive=${fe()} ns=${!!f} buttons=${!!f?.Buttons}`),fe())return;if(!f?.Buttons){ye("FAIL: namespace missing Buttons factory"),ae("PayPal SDK did not expose the Buttons factory.");return}L.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),L.performance({stage:"provider_ready",durationMs:L.elapsed(Ae.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),L.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let m=async(Ee,j)=>{if(fe()||Le.current!==Ze)return;let V=Ee.vaultSetupToken??Ee.subscriptionID??Ee.orderID??"",ve=V?jt.current.get(V):ft.current.get(Ze);if(!(!ve||!dn(ve.generation))&&er(ve.generation)){jt.current.delete(V),ft.current.delete(ve.surfaceKey),At();try{if(Xe(!0),at(()=>Ye.current?.(null)),!V)throw new xt.FloPayError("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});let _e=Cn.current,mt=kr(Ot.current??[_e?.customer?.firstName,_e?.customer?.lastName].filter(Boolean).join(" ")),We=an({email:ve.accountPatch?.email?.trim()||nn.current?.trim()||_e?.customer?.email?.trim(),firstName:ve.accountPatch?.firstName?.trim()||mt.firstName,lastName:ve.accountPatch?.lastName?.trim()||mt.lastName});if(!(0,xt.isValidEmail)(We.email)||!(We.firstName||We.lastName))try{let Lt=ml(await j?.order?.get?.());We=an({email:Lt.email||We.email,firstName:Lt.firstName||We.firstName,lastName:Lt.lastName||We.lastName})}catch{}if((Kn.current||lt)&&!(0,xt.isValidEmail)(We.email)){let Lt=await oe("PayPal",We);if(!Lt)return;We=Lt}(0,xt.isValidEmail)(We.email)&&(ve.accountPatch=an({...ve.accountPatch,...We}),await Kn.current?.(We)),await N(ie==="setup_token"?{id:V,type:"paypal_setup_token",isPaypal:!0,gateway:"paypal",paymentMethodType:xt.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE}:ct?{id:V,isPaypal:!0,gateway:"paypal",paymentMethodType:xt.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE}:{id:V,isPaypal:!0},ve)}catch(_e){F(_e instanceof Error?_e.message:"PayPal capture failed.")}finally{fe()||Xe(!1)}}},J=f.Buttons({style:{layout:"horizontal",height:Wo,tagline:!1},onClick:async(Ee,j)=>{if(fe()){await j.reject();return}yr();let V=sn.current,ve={};if(V)try{let We=await V("paypal");if(fe()){await j.reject();return}if(!We.proceed){tt.current=null,ft.current.delete(Ze),await j.reject();return}ve={sessionId:We.sessionId,accountPatch:We.accountPatch,nonce:We.nonce}}catch(We){ye(`onClick:runBeforeButtonClick rejected msg=${(We instanceof Error?We.message:String(We)).slice(0,120)}`),tt.current=null,ft.current.delete(Ze),await j.reject();return}at(()=>Yt.current?.("paypal"));let mt={generation:le(),surfaceKey:Ze,...ve};tt.current=mt,ft.current.set(Ze,mt),await j.resolve(),L.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),L.log({name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),L.log({name:"provider.overlay.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),un=L.startTiming()},createOrder:ie==="order"?be?()=>pe(be).then(Xt):()=>de("Failed to create PayPal order.").then(Xt):void 0,createSubscription:ie==="subscription"?be?()=>pe(be).then(Xt):()=>de("Failed to create PayPal subscription.").then(Xt):void 0,createVaultSetupToken:ie==="setup_token"?()=>de("Failed to create PayPal setup token.").then(Xt):void 0,onApprove:m,onCancel:()=>{if(fe())return;let Ee=ft.current.get(Ze)??tt.current;Ee&&ft.current.delete(Ee.surfaceKey),tt.current=null,At(),L.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),Ie.current=!0,cn({generation:Ee?.generation,remount:!0,focus:!1})},onError:Ee=>{if(fe()||Le.current!==Ze)return;let j=Ee instanceof Error?Ee.message:"PayPal failed to render.";if(ye(`onError rendered=${rn} msg=${j.slice(0,120)}`),rn){let V=ft.current.get(Ze)??tt.current;if(V&&!dn(V.generation)||!V&&Nn.current===ur.current)return;if(Q(j)){er(V?.generation);return}if(At(),mo(Ee)){L.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),Oe(Ee,V),at(()=>Nt.current?.(Ut("paypal",j))),V&&ft.current.delete(V.surfaceKey),tt.current=null,er(V?.generation);return}let ve=j.toLowerCase();L.error({errorCode:ve.includes("popup")&&ve.includes("block")?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),V&&ft.current.delete(V.surfaceKey),tt.current=null,cn({generation:V?.generation,remount:!0,showRetry:!0,focus:!0}),Qn(Ee,{code:"paypal_runtime_failed"});return}ae(j)}}),ke=J.isEligible();if(ye(`isEligible=${ke}`),L.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!ke){x(!1),ae("PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}Rn=J,gn=()=>{if(!yn||fn||fe()||rn)return;fn=!0,ye(`container:dims ${Ne(Zt)} visibility=${typeof document<"u"?document.visibilityState:"(no document)"}`),typeof MutationObserver<"u"&&(En=new MutationObserver(j=>{if(!fe()){for(let V of j)if(V.type==="childList")V.addedNodes.forEach(ve=>{if(!(ve instanceof Element))return;let _e=ve.tagName.toLowerCase(),mt=(ve.getAttribute("title")??"").slice(0,40),We=_e==="iframe"?` ${Bt(ve)}`:"";ye(`child+ ${_e}${mt?` title="${mt}"`:""}${We} dims=${Ne(ve)}`)});else if(V.type==="attributes"&&V.target instanceof Element){let ve=V.target;if(ve.tagName.toLowerCase()!=="iframe")continue;let _e=V.attributeName;(_e==="src"||_e==="srcdoc")&&ye(`attr~ iframe ${_e}=${_e==="srcdoc"?`[${(ve.getAttribute("srcdoc")??"").length}ch]`:Gt(ve.getAttribute("src"))} dims=${Ne(ve)}`)}}}),En.observe(Zt,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let Ee=j=>{if(fe()||rn)return;let V=Zt.querySelectorAll("iframe"),ve=typeof document<"u"&&"hasStorageAccess"in document;ye(`watchdog:${j} container=${Ne(Zt)} children=${Zt.childElementCount} iframes=${V.length} visibility=${typeof document<"u"?document.visibilityState:"(no document)"} cookies=${typeof navigator<"u"?navigator.cookieEnabled:"?"} hasStorageAccessApi=${ve} paypalNetRequests=${hn.value}`),V.forEach((_e,mt)=>{let We=(_e.getAttribute("title")??"").slice(0,40);ye(` iframe[${mt}] ${Ne(_e)}${We?` title="${We}"`:""} ${Bt(_e)}`);let Lt=fr(_e);Lt&&ye(` ${Lt}`)}),On.length===0&&ye(" (no PayPal/zoid window errors captured)")};st.push(setTimeout(()=>Ee("3s"),3e3)),st.push(setTimeout(()=>Ee("8s"),8e3)),st.push(setTimeout(()=>Ee("15s"),15e3))},gn(),ye("render:start");let se=L.startTiming();mn=setTimeout(()=>{fe()||rn||(ye("watchdog:11s retryable render timeout"),ae("PayPal Buttons render did not settle within 11000ms.",!0))},cl),J.render(Zt).then(()=>{if(ye(`render:resolved inactive=${fe()}`),O(),fe()){Yn();return}rn=!0,x(!0),Be(!1),tn.current?.("ready"),L.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),L.performance({stage:"checkout_render",durationMs:L.elapsed(se),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}).catch(Ee=>{let j=Ee instanceof Error?Ee.message:"PayPal failed to render.";ye(`render:rejected msg=${j.slice(0,120)}`),O(),ae(j)})}).catch(f=>{let m=f instanceof Error?f.message:"PayPal SDK failed to load.";ye(`loadScript:rejected msg=${m.slice(0,120)}`),ae(m)})},0);return()=>{Rt=!0,clearTimeout(Re),nr&&clearTimeout(nr),O(),Z.current===z&&(Z.current=null),Yn()}},[ue,Pt,d,v,c,ie,ct,e,be,me,L,oe,lt,ye]);let In=$e?(0,Bn.jsxs)("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:G?"#fef2f2":"#f3f4f6",border:`1px solid ${G?"#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=${Se} failed=${G})`,dt.length===0?`
2
2
  (waiting for first lifecycle event\u2026)`:`
3
- ${w.join(`
4
- `)}`]}):null;return Z&&!St?Me?(0,In.jsx)("div",{children:gn}):null:(0,In.jsxs)("div",{children:[gn,M&&(0,In.jsx)(Ur,{identity:M.identity,methodLabel:M.methodLabel,testId:"flopay-direct-paypal-identity-pane",onComplete:L,onCancel:()=>L(null)}),(0,In.jsxs)("div",{"aria-hidden":q||M?!0:void 0,style:q||M?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:Ko},children:[!Ce&&!q&&(0,In.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,In.jsx)("div",{ref:Ee,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,role:"group","aria-label":"PayPal payment method",style:{minHeight:Ko,display:"flex",opacity:Ce?1:0},"aria-busy":Te||ge},fe)]},fe),Qe&&(0,In.jsx)("button",{ref:X,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:rn,style:ul,children:"Try PayPal again"})]})}function mo(e){return(0,In.jsx)(Vi,{...e})}function Ki(e){return(0,In.jsx)(Vi,{...e})}var yo=require("react/jsx-runtime");function jr({children:e,margin:t,icon:n=!0,styleOverride:r}){return(0,yo.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,yo.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:(0,yo.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 xt=require("react/jsx-runtime");function Rn({status:e,errorMessage:t,authorized:n=!1,processingLabel:r="PROCESSING...",successLabel:o,errorLabel:i="PAYMENT FAILED",successNote:u="You will be automatically redirected, do not close or navigate away from this window."}){return(0,xt.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,xt.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,xt.jsxs)("div",{style:{width:48,height:48,position:"relative"},children:[e==="processing"&&(0,xt.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,xt.jsx)("circle",{cx:"12",cy:"12",r:"10",stroke:"#e5e7eb",strokeWidth:"3"}),(0,xt.jsx)("path",{d:"M4 12a8 8 0 018-8v3a5 5 0 00-5 5H4z",fill:"#4A49FF"})]}),e==="success"&&(0,xt.jsx)("div",{style:{animation:"flopay-pop 0.4s cubic-bezier(0.34,1.56,0.64,1)"},children:(0,xt.jsxs)("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[(0,xt.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#22c55e"}),(0,xt.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,xt.jsx)("div",{style:{animation:"flopay-shake 0.4s ease"},children:(0,xt.jsxs)("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[(0,xt.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#ef4444"}),(0,xt.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,xt.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"&&u!==null&&(0,xt.jsx)("p",{style:{fontSize:13,color:"#6b7280",fontWeight:400,maxWidth:260,lineHeight:1.4,margin:0},children:u}),e==="error"&&t&&(0,xt.jsx)("p",{style:{fontSize:13,color:"#6b7280",fontWeight:400,maxWidth:260,lineHeight:1.4,margin:0},children:t}),(0,xt.jsx)("style",{children:`
3
+ ${dt.join(`
4
+ `)}`]}):null;return G&&!kt?$e?(0,Bn.jsx)("div",{children:In}):null:(0,Bn.jsxs)("div",{children:[In,M&&(0,Bn.jsx)($r,{identity:M.identity,methodLabel:M.methodLabel,testId:"flopay-direct-paypal-identity-pane",onComplete:D,onCancel:()=>D(null)}),(0,Bn.jsxs)("div",{"aria-hidden":U||M?!0:void 0,style:U||M?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:Wo},children:[!Se&&!U&&(0,Bn.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,Bn.jsx)("div",{ref:Me,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,role:"group","aria-label":"PayPal payment method",style:{minHeight:Wo,display:"flex",opacity:Se?1:0},"aria-busy":Fe||he},me)]},me),rt&&(0,Bn.jsx)("button",{ref:X,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:Jt,style:ul,children:"Try PayPal again"})]})}function go(e){return(0,Bn.jsx)(Ki,{...e})}function Hi(e){return(0,Bn.jsx)(Ki,{...e})}var ho=require("react/jsx-runtime");function Kr({children:e,margin:t,icon:n=!0,styleOverride:r}){return(0,ho.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,ho.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:(0,ho.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 Ft=require("react/jsx-runtime");function Fn({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,Ft.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,Ft.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,Ft.jsxs)("div",{style:{width:48,height:48,position:"relative"},children:[e==="processing"&&(0,Ft.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,Ft.jsx)("circle",{cx:"12",cy:"12",r:"10",stroke:"#e5e7eb",strokeWidth:"3"}),(0,Ft.jsx)("path",{d:"M4 12a8 8 0 018-8v3a5 5 0 00-5 5H4z",fill:"#4A49FF"})]}),e==="success"&&(0,Ft.jsx)("div",{style:{animation:"flopay-pop 0.4s cubic-bezier(0.34,1.56,0.64,1)"},children:(0,Ft.jsxs)("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[(0,Ft.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#22c55e"}),(0,Ft.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,Ft.jsx)("div",{style:{animation:"flopay-shake 0.4s ease"},children:(0,Ft.jsxs)("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[(0,Ft.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#ef4444"}),(0,Ft.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,Ft.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,Ft.jsx)("p",{style:{fontSize:13,color:"#6b7280",fontWeight:400,maxWidth:260,lineHeight:1.4,margin:0},children:d}),e==="error"&&t&&(0,Ft.jsx)("p",{style:{fontSize:13,color:"#6b7280",fontWeight:400,maxWidth:260,lineHeight:1.4,margin:0},children:t}),(0,Ft.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 Hi=require("@flopay/shared"),$t=require("react");var Yi=require("react/jsx-runtime");function fo({flopay:e,paypalFlopay:t,options:n,onInstrument:r,children:o}){let[i,u]=(0,$t.useState)(e instanceof Promise?null:e),[c,P]=(0,$t.useState)(t instanceof Promise||!t?null:t),g=(0,$t.useRef)(null),b=(0,$t.useRef)(null),v=$r(r);(0,$t.useEffect)(()=>{v({class:"lifecycle",name:"checkout.mount"})},[v]),(0,$t.useEffect)(()=>{i&&v({class:"lifecycle",name:"sdk.initialize.ready"})},[v,i]),(0,$t.useEffect)(()=>{if(i)return Dt(i)?.subscribe?.(v)},[v,i]),(0,$t.useEffect)(()=>{if(!(!c||c===i))return Dt(c)?.subscribe?.(v)},[v,i,c]),(0,$t.useEffect)(()=>{if(!i)return;let f=Dt(i);return g.current=f?.beginCheckout()??f?.now()??0,f?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{f?.log({name:"checkout.unmount",stage:"unmount"})}},[i]),(0,$t.useEffect)(()=>{let f=!1;return e instanceof Promise?e.then(C=>{f||u(C)},()=>{f||v({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"})}):u(e),()=>{f=!0}},[v,e]),(0,$t.useEffect)(()=>{let f=!1;if(!t){P(null);return}return t instanceof Promise?t.then(C=>{f||P(C)},()=>{f||v({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED",provider:"paypal"})}):P(t),()=>{f=!0}},[v,t]),(0,$t.useEffect)(()=>{if(!i||b.current===i)return;b.current=i;let f=Dt(i);f?.log({name:"checkout.rendered",stage:"checkout_render"}),v({class:"lifecycle",name:"checkout.rendered"}),f?.performance({stage:"checkout_render",durationMs:f.elapsed(g.current??0),durationMode:"machine"})},[v,i]);let N=(0,Hi.resolveBillingApiUrl)(n?.billingApiUrl),B=(0,$t.useMemo)(()=>({flopay:i,paypalFlopay:c,billingApiUrl:N,emitInstrument:v}),[i,c,N,v]);return(0,Yi.jsx)(kn.Provider,{value:B,children:o})}var Ho="flopay_recent_completion_";function Vr(e){if(!(!e||typeof window>"u"))try{let t={expiresAt:Date.now()+6e4};window.sessionStorage.setItem(Ho+e,JSON.stringify(t))}catch{}}function Ta(e){if(!e||typeof window>"u")return!1;try{let t=window.sessionStorage.getItem(Ho+e);if(!t)return!1;let n=JSON.parse(t);return typeof n?.expiresAt!="number"||n.expiresAt<=Date.now()?(window.sessionStorage.removeItem(Ho+e),!1):!0}catch{return!1}}var Kr=require("@flopay/js"),Ne=require("@flopay/shared");var ho="card";async function yl(e,t,n){if(n){if(typeof e.retrieveSetupIntent!="function")return null;let{setupIntent:i,error:u}=await e.retrieveSetupIntent(t);return{error:u,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 fl(e,t,n,r){if(r){if(typeof e.confirmCardSetup!="function")return null;let{setupIntent:u,error:c}=await e.confirmCardSetup(t,n);return{error:c,intent:u??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 Ba(e,t){return Object.assign(e,{checkoutMethod:t})}function ar(e,t){let n=e instanceof Ne.FloPayError?e:new Ne.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 go(e,t){try{return await e()}catch(n){throw ar(n,t)}}function Wi(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 gl(e){return e.status==="succeeded"||e.status==="declined"}async function Gi(e){if(typeof document>"u"||typeof window>"u")throw new Ne.FloPayError("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});if(e.signal?.aborted)throw new Ne.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 b=new AbortController,v=()=>b.abort();e.signal?.aborted?b.abort():e.signal?.addEventListener("abort",v);let N=window.setTimeout(()=>b.abort(),r);try{let B=await fetch(o,{method:"POST",headers:{"x-checkout-session-token":e.nonce,"content-type":"application/json"},body:"{}",signal:b.signal});if(!B.ok)return{status:"unknown"};let f=await B.json().catch(()=>null);return hl(f)}catch{return{status:"unknown"}}finally{window.clearTimeout(N),e.signal?.removeEventListener("abort",v)}},u=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 P=document.createElement("iframe");P.setAttribute("title","Card authentication"),P.setAttribute("allow","payment"),P.tabIndex=0,P.style.cssText=["width:min(100%,460px)","height:min(100%,640px)","border:0","border-radius:12px","background:#fff","box-shadow:0 12px 30px rgba(0,0,0,0.35)"].join(";"),P.src=e.nextActionRedirectUrl,c.appendChild(P),document.body.appendChild(c),P.focus();let g=null;try{g=new URL(e.billingApiUrl,window.location.href).origin}catch{g=null}try{let b=await new Promise((v,N)=>{let B=!1,f=0,C=0,ge=0,$=!1,S=()=>{window.clearTimeout(f),window.clearInterval(C),window.clearTimeout(ge),window.removeEventListener("message",J),P.removeEventListener("load",j),e.signal?.removeEventListener("abort",pe)},ye=async()=>{if(!(B||$)){$=!0;try{let he=await i();if(B||!gl(he))return;B=!0,S(),v(he)}finally{$=!1}}},j=()=>{window.clearTimeout(ge),ge=window.setTimeout(()=>{ye()},250)},pe=()=>{B||(B=!0,S(),N(new Ne.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"})))},J=he=>{if(he.source!==P.contentWindow||g&&he.origin!==g)return;let ze=he.data;!ze||typeof ze!="object"||ze.source!=="flopay-vault-3ds-return"||B||(B=!0,S(),v(null))};f=window.setTimeout(()=>{B||(B=!0,S(),N(new Ne.FloPayError("Card authentication timed out.","api_error",{code:"three_ds_timeout"})))},t),C=window.setInterval(()=>{ye()},n),P.addEventListener("load",j),window.addEventListener("message",J),e.signal?.addEventListener("abort",pe),e.signal?.aborted&&pe()});return b||await i()}finally{c.parentNode?.removeChild(c),u?.isConnected&&u.focus()}}function hl(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 hr(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=fr(o)??o;return Ba(new Ne.FloPayError(i,"api_error",{code:(0,Ne.normalizeCheckoutFailureOutcome)(e?.outcome)??(0,Ne.normalizeCheckoutFailureOutcome)(e?.type)??e?.gatewayErrorCode}),r)}function Aa(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function Yo(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}async function bl(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 Ji(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let o of n)if(typeof o=="string"&&o.length>0&&(!t?.requirePaymentIntentClientSecret||Yo(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||Yo(c)))return c;let u=o.gateways;if(u&&typeof u=="object"){let c=u.stripe;if(c&&typeof c=="object"){let P=c,g=[P.stripeClientSecret,P.clientSecret];for(let b of g)if(typeof b=="string"&&b.length>0&&(!t?.requirePaymentIntentClientSecret||Yo(b)))return b}}}}async function vl({billingApiUrl:e,sessionId:t,nonce:n,responseJson:r}){let o=Ji(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 Kr.PaymentAPI(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(Yo(c))return{type:"3ds_required",threeDSecureToken:c}}catch{}return null}async function Hr({billingApiUrl:e,sessionId:t,session:n,nonce:r,tokenizedData:o,returnUrl:i,telemetry:u}){let c=e.replace(/\/+$/,""),P=t??n.id,g=r??n.clientSecret,b=n.customer?.id??n.accountData?.userId??"",v=n.customer?.email??n.accountData?.email??"",N=n.customer?.firstName??n.accountData?.firstName??"",B=n.customer?.lastName??n.accountData?.lastName??"",f=n.customer?.country??n.accountData?.country??void 0,C=n.customer?.zip??n.accountData?.zip??void 0,ge=new Kr.PaymentAPI(c,u===!1?{telemetry:!1}:void 0),$=await bl(()=>ge.processPayment(b,{sessionId:P,nonce:g,tokenizedData:o,accountData:{userId:b,email:v,firstName:N,lastName:B,country:f,zip:C},returnUrl:i??Aa(n)}));if($.ok){let j=typeof $.json=="function"?await $.json().catch(()=>null):null;return(0,Ne.isAuthorizationOnlySession)(n)||j?.status==="authorized"?{type:"success",result:{status:"authorized",paymentId:typeof j?.paymentId=="string"?j.paymentId:n.paymentId,sessionId:typeof j?.sessionId=="string"?j.sessionId:P,authorizationExpiresAt:typeof j?.authorizationExpiresAt=="string"?j.authorizationExpiresAt:n.authorizationExpiresAt,paymentMethodId:co(o),checkoutMethod:o?o.isPaypal?"paypal":"card":void 0}}:{type:"success",result:{status:"succeeded",paymentIntentId:o?.threeDSecureActionResultTokenId,paymentMethodId:co(o),checkoutMethod:o?o.isPaypal?"paypal":"card":void 0}}}let S;try{S=await $.json()}catch{throw new Ne.FloPayError("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:$.status})}if(S?.type==="paypal_redirect_required"||S?.type==="3ds_required"){let j=Ji(S);if(!j)throw new Ne.FloPayError("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:$.status});return{type:S.type,threeDSecureToken:j,paymentMethodId:S.paymentMethodId}}if(S?.gatewayErrorCode==="authentication_required"){let j=await vl({billingApiUrl:c,sessionId:P,nonce:g,responseJson:S});if(j)return j;throw Ba(new Ne.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}let ye=new Ne.FloPayError(S?.message??"Payment failed. Please try again.","api_error",{code:S?.code??S?.gatewayErrorCode,declineCode:S?.declineCode??S?.gatewayDeclineReason,statusCode:$.status});throw Object.assign(ye,{telemetryOutcome:(0,Ne.classifyPaymentRejection)($.status,S)})}async function Wo(e,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:i,session:u,returnUrl:c,telemetry:P}){let g=t?.getRawProvider();if(!g)throw ar(new Ne.FloPayError("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!r||!e.threeDSecureToken)throw Ba(new Ne.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let b=(0,Ne.isSetupIntentClientSecret)(e.threeDSecureToken),v=null,N=e.paymentMethodId,B=await go(()=>yl(g,e.threeDSecureToken,b),"card");if(B){if(B.error)throw ar(new Ne.FloPayError(B.error.message??`Failed to retrieve 3DS ${b?"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 f=N?await go(()=>fl(g,e.threeDSecureToken,{payment_method:N,return_url:c??Aa(u)??window.location.href},b),"card"):null;if(f){if(f.error)throw ar(new Ne.FloPayError(f.error.message??"3DS authentication failed.","api_error",{code:f.error.code}),"card");v=f.intent}else{let C=await go(()=>g.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(C.error)throw ar(new Ne.FloPayError(C.error.message??"3DS authentication failed.","api_error",{code:C.error.code}),"card");v=(b?C.setupIntent:C.paymentIntent)??null}if(v&&(v.status==="requires_capture"||v.status==="succeeded"||v.status==="processing")){let C=await Hr({billingApiUrl:o,sessionId:i,session:u,telemetry:P,tokenizedData:{id:v.id,type:"card",threeDSecureActionResultTokenId:v.id},returnUrl:c});return C.type==="success"?{...C.result,paymentIntentId:C.result.paymentIntentId??v.id,paymentMethodId:C.result.paymentMethodId??N}:Wo(C,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:i,session:u,returnUrl:c,telemetry:P})}throw ar(new Ne.FloPayError("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let b=(n??t)?.getRawProvider();if(!b)throw ar(new Ne.FloPayError("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:N}=await go(()=>b.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(N)throw ar(new Ne.FloPayError(N.message??"PayPal authorization failed.","api_error",{code:N.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:v}=await go(()=>b.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:c??Aa(u)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(v)throw ar(new Ne.FloPayError(v.message??"PayPal authorization failed.","api_error",{code:v.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new Ne.FloPayError("Unsupported payment redirect state.","api_error")}function Rr(e){if(e instanceof Ne.FloPayError){let r=fr(e.message);return r&&r!==e.message?Object.assign(new Ne.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=fr(t)??t;return new Ne.FloPayError(n,"api_error")}function Go(e){let t=e.data.stripe?.publishableKey,n=!!e.data.paypal?.publishableKey;if(!t&&!n)throw new Ne.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 Jo({publishableKey:e,paypalPublishableKey:t,billingApiUrl:n,locale:r,telemetry:o}){if(!e)return{flopay:null,paypalFlopay:null};let i=!!t&&t!==e,[u,c]=await Promise.all([(0,Kr.loadFloPay)(e,{billingApiUrl:n,locale:r,telemetry:o}),i?(0,Kr.loadFloPay)(t,{billingApiUrl:n,locale:r,telemetry:o}).catch(P=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",P),null)):Promise.resolve(null)]);return{flopay:u,paypalFlopay:t?i?c:u:null}}var sr=require("@flopay/js"),p=require("@flopay/shared"),Rt=require("@stripe/react-stripe-js"),a=Ti(require("react"),1);function Xi(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 Zi={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 ir=require("react"),Qi=require("react/jsx-runtime");function Yr({capture:e,html:t,messageToken:n,expectedOrigin:r,theme:o,containerStyle:i,onReady:u,onError:c,onValidation:P}){let g=(0,ir.useRef)(null),b=(0,ir.useRef)(u),v=(0,ir.useRef)(c),N=(0,ir.useRef)(P);b.current=u,v.current=c,N.current=P;let B=(0,ir.useRef)(o);return B.current=o,(0,ir.useEffect)(()=>{let f=g.current;if(!f)return;let C=!0,ge=!1,$=()=>{!C||ge||(ge=!0,b.current?.())},S=e.on("ready",()=>{$()}),ye=e.on("error",J=>{v.current?.(J.message??"There was a problem loading the secure card form.")}),j=e.on("validation",J=>{N.current?.(J.message??null)}),pe={html:t,...n?{messageToken:n}:{},...r?{expectedOrigin:r}:{},...B.current?{theme:B.current}:{}};return e.mount(f,pe).then(()=>{$()}).catch(J=>{C&&v.current?.(J instanceof Error?J.message:"Failed to load the secure card form.")}),()=>{C=!1,S(),ye(),j(),e.unmount()}},[e,t,n,r]),(0,ir.useEffect)(()=>{o&&e.applyTheme?.(o)},[e,o]),(0,Qi.jsx)("div",{ref:g,"data-testid":"flopay-vault-card-fields",style:i})}function Wr(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),u=Math.round((r>>8&255)*o),c=Math.round((r&255)*o);return`#${(1<<24|i<<16|u<<8|c).toString(16).slice(1)}`}function Ma(e){if(typeof e=="number"||typeof e=="string")return e}function Xo({appearance:e,buttonsStyles:t,layout:n="default"}){let r=e?.variables,o=g=>typeof g=="string"&&g?g:void 0,i=t.submitButton,u=o(r?.colorPrimary)??o(i?.backgroundColor)??"#4A49FF",c=n==="buttons",P=t.nameInput;return{primaryColor:u,primaryHoverColor:o(r?.colorPrimaryHover)??Wr(u,.12),inputBackgroundColor:o(t.cardInputBackground)??o(r?.colorBackground)??"#ffffff",textColor:o(t.cardInputColor)??o(P?.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(P?.fontFamily)??o(r?.fontFamily)??"Poppins, sans-serif",fontSize:o(t.cardInputFontSize)??o(r?.fontSizeBase)??"16px",fontWeight:String(Ma(P?.fontWeight)??400),borderRadius:o(r?.borderRadius)??"8px"}}var l=require("react/jsx-runtime"),Kn="flopay_stripe_resume",es="flopay_wallet_resume";function ls(e){return e instanceof p.FloPayError&&(e.type==="validation_error"||e.statusCode===400||e.statusCode===422)}async function Qo(e,t,...n){let r=n[2].provider;t?.({class:"lifecycle",name:"payment.intent.started",provider:r});try{return await new sr.PaymentAPI(e).createSessionIntent(...n)}catch(o){throw ls(o)||t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"intent_create",provider:r}),o}}var bo="flopay_paypal_resume",Pl=250,ts="Just a moment \u2014 we are finalizing your order. Please press pay again.";function Oa(e,t,n){e?.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:"provider_runtime",stage:"provider_load",provider:t,paymentMethodCategory:n,requestCategory:"provider_sdk"})}async function ea({billingApiUrl:e,sessionId:t,nonce:n,request:r}){if(!(!t||!n))try{await new sr.PaymentAPI(e,{telemetry:!1}).reportSessionIntentDecline(t,n,r)}catch{}}function Cl(e){return e instanceof p.FloPayError&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function Fa(e){return e?.html?{html:e.html,...e.messageToken?{messageToken:e.messageToken}:{},...e.expectedOrigin?{expectedOrigin:e.expectedOrigin}:{}}:null}function Sl({event:e,fallbackEmail:t,fallbackName:n}){let r=e.billingDetails,o=Sr(r?.name),i=Sr(n);return nn({email:((0,p.isValidEmail)(t?.trim())?t?.trim():void 0)??r?.email?.trim(),firstName:i.firstName??o.firstName,lastName:i.lastName??o.lastName})}async function cs({event:e,prepared:t,email:n,billingName:r,methodLabel:o,collect:i}){let u=Sl({event:e,fallbackEmail:t?.accountPatch?.email??n,fallbackName:[t?.accountPatch?.firstName,t?.accountPatch?.lastName].filter(Boolean).join(" ")||r});return(0,p.isValidEmail)(u.email)?u:i(o,u)}var wl=`
9
+ `})]})})}var Yi=require("@flopay/shared"),Ht=require("react");var Wi=require("react/jsx-runtime");function bo({flopay:e,paypalFlopay:t,options:n,onInstrument:r,children:o}){let[i,d]=(0,Ht.useState)(e instanceof Promise?null:e),[c,v]=(0,Ht.useState)(t instanceof Promise||!t?null:t),y=(0,Ht.useRef)(null),g=(0,Ht.useRef)(null),b=Vr(r);(0,Ht.useEffect)(()=>{b({class:"lifecycle",name:"checkout.mount"})},[b]),(0,Ht.useEffect)(()=>{i&&b({class:"lifecycle",name:"sdk.initialize.ready"})},[b,i]),(0,Ht.useEffect)(()=>{if(i)return qt(i)?.subscribe?.(b)},[b,i]),(0,Ht.useEffect)(()=>{if(!(!c||c===i))return qt(c)?.subscribe?.(b)},[b,i,c]),(0,Ht.useEffect)(()=>{if(!i)return;let p=qt(i);return y.current=p?.beginCheckout()??p?.now()??0,p?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{p?.log({name:"checkout.unmount",stage:"unmount"})}},[i]),(0,Ht.useEffect)(()=>{let p=!1;return e instanceof Promise?e.then(P=>{p||d(P)},()=>{p||b({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"})}):d(e),()=>{p=!0}},[b,e]),(0,Ht.useEffect)(()=>{let p=!1;if(!t){v(null);return}return t instanceof Promise?t.then(P=>{p||v(P)},()=>{p||b({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED",provider:"paypal"})}):v(t),()=>{p=!0}},[b,t]),(0,Ht.useEffect)(()=>{if(!i||g.current===i)return;g.current=i;let p=qt(i);p?.log({name:"checkout.rendered",stage:"checkout_render"}),b({class:"lifecycle",name:"checkout.rendered"}),p?.performance({stage:"checkout_render",durationMs:p.elapsed(y.current??0),durationMode:"machine"})},[b,i]);let B=(0,Yi.resolveBillingApiUrl)(n?.billingApiUrl),T=(0,Ht.useMemo)(()=>({flopay:i,paypalFlopay:c,billingApiUrl:B,emitInstrument:b}),[i,c,B,b]);return(0,Wi.jsx)(An.Provider,{value:T,children:o})}var Go="flopay_recent_completion_";function Hr(e){if(!(!e||typeof window>"u"))try{let t={expiresAt:Date.now()+6e4};window.sessionStorage.setItem(Go+e,JSON.stringify(t))}catch{}}function Ma(e){if(!e||typeof window>"u")return!1;try{let t=window.sessionStorage.getItem(Go+e);if(!t)return!1;let n=JSON.parse(t);return typeof n?.expiresAt!="number"||n.expiresAt<=Date.now()?(window.sessionStorage.removeItem(Go+e),!1):!0}catch{return!1}}var Yr=require("@flopay/js"),Ve=require("@flopay/shared");var Po="card";async function yl(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 fl(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 Ba(e,t){return Object.assign(e,{checkoutMethod:t})}function sr(e,t){let n=e instanceof Ve.FloPayError?e:new Ve.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 vo(e,t){try{return await e()}catch(n){throw sr(n,t)}}function Gi(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 gl(e){return e.status==="succeeded"||e.status==="declined"}async function Ji(e){if(typeof document>"u"||typeof window>"u")throw new Ve.FloPayError("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});if(e.signal?.aborted)throw new Ve.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 g=new AbortController,b=()=>g.abort();e.signal?.aborted?g.abort():e.signal?.addEventListener("abort",b);let B=window.setTimeout(()=>g.abort(),r);try{let T=await fetch(o,{method:"POST",headers:{"x-checkout-session-token":e.nonce,"content-type":"application/json"},body:"{}",signal:g.signal});if(!T.ok)return{status:"unknown"};let p=await T.json().catch(()=>null);return hl(p)}catch{return{status:"unknown"}}finally{window.clearTimeout(B),e.signal?.removeEventListener("abort",b)}},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 y=null;try{y=new URL(e.billingApiUrl,window.location.href).origin}catch{y=null}try{let g=await new Promise((b,B)=>{let T=!1,p=0,P=0,he=0,q=!1,S=()=>{window.clearTimeout(p),window.clearInterval(P),window.clearTimeout(he),window.removeEventListener("message",W),v.removeEventListener("load",$),e.signal?.removeEventListener("abort",ce)},ue=async()=>{if(!(T||q)){q=!0;try{let be=await i();if(T||!gl(be))return;T=!0,S(),b(be)}finally{q=!1}}},$=()=>{window.clearTimeout(he),he=window.setTimeout(()=>{ue()},250)},ce=()=>{T||(T=!0,S(),B(new Ve.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"})))},W=be=>{if(be.source!==v.contentWindow||y&&be.origin!==y)return;let He=be.data;!He||typeof He!="object"||He.source!=="flopay-vault-3ds-return"||T||(T=!0,S(),b(null))};p=window.setTimeout(()=>{T||(T=!0,S(),B(new Ve.FloPayError("Card authentication timed out.","api_error",{code:"three_ds_timeout"})))},t),P=window.setInterval(()=>{ue()},n),v.addEventListener("load",$),window.addEventListener("message",W),e.signal?.addEventListener("abort",ce),e.signal?.aborted&&ce()});return g||await i()}finally{c.parentNode?.removeChild(c),d?.isConnected&&d.focus()}}function hl(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 vr(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=hr(o)??o;return Ba(new Ve.FloPayError(i,"api_error",{code:(0,Ve.normalizeCheckoutFailureOutcome)(e?.outcome)??(0,Ve.normalizeCheckoutFailureOutcome)(e?.type)??e?.gatewayErrorCode}),r)}function Aa(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function Jo(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}async function bl(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 Xi(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let o of n)if(typeof o=="string"&&o.length>0&&(!t?.requirePaymentIntentClientSecret||Jo(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||Jo(c)))return c;let d=o.gateways;if(d&&typeof d=="object"){let c=d.stripe;if(c&&typeof c=="object"){let v=c,y=[v.stripeClientSecret,v.clientSecret];for(let g of y)if(typeof g=="string"&&g.length>0&&(!t?.requirePaymentIntentClientSecret||Jo(g)))return g}}}}async function vl({billingApiUrl:e,sessionId:t,nonce:n,responseJson:r}){let o=Xi(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 Yr.PaymentAPI(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(Jo(c))return{type:"3ds_required",threeDSecureToken:c}}catch{}return null}async function Wr({billingApiUrl:e,sessionId:t,session:n,nonce:r,tokenizedData:o,returnUrl:i,telemetry:d}){let c=e.replace(/\/+$/,""),v=t??n.id,y=r??n.clientSecret,g=n.customer?.id??n.accountData?.userId??"",b=n.customer?.email??n.accountData?.email??"",B=n.customer?.firstName??n.accountData?.firstName??"",T=n.customer?.lastName??n.accountData?.lastName??"",p=n.customer?.country??n.accountData?.country??void 0,P=n.customer?.zip??n.accountData?.zip??void 0,he=new Yr.PaymentAPI(c,d===!1?{telemetry:!1}:void 0),q=await bl(()=>he.processPayment(g,{sessionId:v,nonce:y,tokenizedData:o,accountData:{userId:g,email:b,firstName:B,lastName:T,country:p,zip:P},returnUrl:i??Aa(n)}));if(q.ok){let $=typeof q.json=="function"?await q.json().catch(()=>null):null;return(0,Ve.isAuthorizationOnlySession)(n)||$?.status==="authorized"?{type:"success",result:{status:"authorized",paymentId:typeof $?.paymentId=="string"?$.paymentId:n.paymentId,sessionId:typeof $?.sessionId=="string"?$.sessionId:v,authorizationExpiresAt:typeof $?.authorizationExpiresAt=="string"?$.authorizationExpiresAt:n.authorizationExpiresAt,paymentMethodId:po(o),checkoutMethod:o?o.isPaypal?"paypal":"card":void 0}}:{type:"success",result:{status:"succeeded",paymentIntentId:o?.threeDSecureActionResultTokenId,paymentMethodId:po(o),checkoutMethod:o?o.isPaypal?"paypal":"card":void 0}}}let S;try{S=await q.json()}catch{throw new Ve.FloPayError("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:q.status})}if(S?.type==="paypal_redirect_required"||S?.type==="3ds_required"){let $=Xi(S);if(!$)throw new Ve.FloPayError("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:q.status});return{type:S.type,threeDSecureToken:$,paymentMethodId:S.paymentMethodId}}if(S?.gatewayErrorCode==="authentication_required"){let $=await vl({billingApiUrl:c,sessionId:v,nonce:y,responseJson:S});if($)return $;throw Ba(new Ve.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}let ue=new Ve.FloPayError(S?.message??"Payment failed. Please try again.","api_error",{code:S?.code??S?.gatewayErrorCode,declineCode:S?.declineCode??S?.gatewayDeclineReason,statusCode:q.status});throw Object.assign(ue,{telemetryOutcome:(0,Ve.classifyPaymentRejection)(q.status,S)})}async function Xo(e,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:i,session:d,returnUrl:c,telemetry:v}){let y=t?.getRawProvider();if(!y)throw sr(new Ve.FloPayError("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!r||!e.threeDSecureToken)throw Ba(new Ve.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let g=(0,Ve.isSetupIntentClientSecret)(e.threeDSecureToken),b=null,B=e.paymentMethodId,T=await vo(()=>yl(y,e.threeDSecureToken,g),"card");if(T){if(T.error)throw sr(new Ve.FloPayError(T.error.message??`Failed to retrieve 3DS ${g?"setup":"payment"} status.`,"api_error",{code:T.error.code}),"card");let P=T.intent;!B&&P?.payment_method&&(typeof P.payment_method=="string"?B=P.payment_method:"id"in P.payment_method&&(B=P.payment_method.id??void 0))}let p=B?await vo(()=>fl(y,e.threeDSecureToken,{payment_method:B,return_url:c??Aa(d)??window.location.href},g),"card"):null;if(p){if(p.error)throw sr(new Ve.FloPayError(p.error.message??"3DS authentication failed.","api_error",{code:p.error.code}),"card");b=p.intent}else{let P=await vo(()=>y.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(P.error)throw sr(new Ve.FloPayError(P.error.message??"3DS authentication failed.","api_error",{code:P.error.code}),"card");b=(g?P.setupIntent:P.paymentIntent)??null}if(b&&(b.status==="requires_capture"||b.status==="succeeded"||b.status==="processing")){let P=await Wr({billingApiUrl:o,sessionId:i,session:d,telemetry:v,tokenizedData:{id:b.id,type:"card",threeDSecureActionResultTokenId:b.id},returnUrl:c});return P.type==="success"?{...P.result,paymentIntentId:P.result.paymentIntentId??b.id,paymentMethodId:P.result.paymentMethodId??B}:Xo(P,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:i,session:d,returnUrl:c,telemetry:v})}throw sr(new Ve.FloPayError("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let g=(n??t)?.getRawProvider();if(!g)throw sr(new Ve.FloPayError("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:B}=await vo(()=>g.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(B)throw sr(new Ve.FloPayError(B.message??"PayPal authorization failed.","api_error",{code:B.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:b}=await vo(()=>g.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:c??Aa(d)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(b)throw sr(new Ve.FloPayError(b.message??"PayPal authorization failed.","api_error",{code:b.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new Ve.FloPayError("Unsupported payment redirect state.","api_error")}function Co(e){if(e instanceof Ve.FloPayError){let r=hr(e.message);return r&&r!==e.message?Object.assign(new Ve.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=hr(t)??t;return new Ve.FloPayError(n,"api_error")}function Zo(e){let t=e.data.stripe?.publishableKey,n=!!e.data.paypal?.publishableKey;if(!t&&!n)throw new Ve.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 Qo({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,Yr.loadFloPay)(e,{billingApiUrl:n,locale:r,telemetry:o}),i?(0,Yr.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 cr=require("@flopay/js"),u=require("@flopay/shared"),Tt=require("@stripe/react-stripe-js"),a=Mi(require("react"),1);function Zi(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 Qi={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 lr=require("react"),es=require("react/jsx-runtime");function Gr({capture:e,html:t,messageToken:n,expectedOrigin:r,theme:o,containerStyle:i,onReady:d,onError:c,onValidation:v}){let y=(0,lr.useRef)(null),g=(0,lr.useRef)(d),b=(0,lr.useRef)(c),B=(0,lr.useRef)(v);g.current=d,b.current=c,B.current=v;let T=(0,lr.useRef)(o);return T.current=o,(0,lr.useEffect)(()=>{let p=y.current;if(!p)return;let P=!0,he=!1,q=()=>{!P||he||(he=!0,g.current?.())},S=e.on("ready",()=>{q()}),ue=e.on("error",W=>{b.current?.(W.message??"There was a problem loading the secure card form.")}),$=e.on("validation",W=>{B.current?.(W.message??null)}),ce={html:t,...n?{messageToken:n}:{},...r?{expectedOrigin:r}:{},...T.current?{theme:T.current}:{}};return e.mount(p,ce).then(()=>{q()}).catch(W=>{P&&b.current?.(W instanceof Error?W.message:"Failed to load the secure card form.")}),()=>{P=!1,S(),ue(),$(),e.unmount()}},[e,t,n,r]),(0,lr.useEffect)(()=>{o&&e.applyTheme?.(o)},[e,o]),(0,es.jsx)("div",{ref:y,"data-testid":"flopay-vault-card-fields",style:i})}function Jr(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 Fa(e){if(typeof e=="number"||typeof e=="string")return e}function ea({appearance:e,buttonsStyles:t,layout:n="default"}){let r=e?.variables,o=y=>typeof y=="string"&&y?y: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)??Jr(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(Fa(v?.fontWeight)??400),borderRadius:o(r?.borderRadius)??"8px"}}var l=require("react/jsx-runtime"),Jn="flopay_stripe_resume",ts="flopay_wallet_resume";function cs(e){return e instanceof u.FloPayError&&(e.type==="validation_error"||e.statusCode===400||e.statusCode===422)}async function na(e,t,...n){let r=n[2].provider;t?.({class:"lifecycle",name:"payment.intent.started",provider:r});try{return await new cr.PaymentAPI(e).createSessionIntent(...n)}catch(o){throw cs(o)||t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"intent_create",provider:r}),o}}var So="flopay_paypal_resume",Pl=250,ns="Just a moment \u2014 we are finalizing your order. Please press pay again.";function za(e,t,n){e?.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:"provider_runtime",stage:"provider_load",provider:t,paymentMethodCategory:n,requestCategory:"provider_sdk"})}async function ra({billingApiUrl:e,sessionId:t,nonce:n,request:r}){if(!(!t||!n))try{await new cr.PaymentAPI(e,{telemetry:!1}).reportSessionIntentDecline(t,n,r)}catch{}}function Cl(e){return e instanceof u.FloPayError&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function Da(e){return e?.html?{html:e.html,...e.messageToken?{messageToken:e.messageToken}:{},...e.expectedOrigin?{expectedOrigin:e.expectedOrigin}:{}}:null}function Sl({event:e,fallbackEmail:t,fallbackName:n}){let r=e.billingDetails,o=kr(r?.name),i=kr(n);return an({email:((0,u.isValidEmail)(t?.trim())?t?.trim():void 0)??r?.email?.trim(),firstName:i.firstName??o.firstName,lastName:i.lastName??o.lastName})}async function ds({event:e,prepared:t,email:n,billingName:r,methodLabel:o,collect:i}){let d=Sl({event:e,fallbackEmail:t?.accountPatch?.email??n,fallbackName:[t?.accountPatch?.firstName,t?.accountPatch?.lastName].filter(Boolean).join(" ")||r});return(0,u.isValidEmail)(d.email)?d:i(o,d)}var wl=`
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 @@ ${w.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
- `,Zo=44;function za(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 kl={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"},ds={width:"100%",minHeight:Zo,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 Il(e){switch(e){case"paypal":return"PayPal";case"apple_pay":return"Apple Pay";case"google_pay":return"Google Pay";default:return"Card"}}function ns(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function La(e){return e==="paypal"?"PayPal":(0,p.getStripeMethodDisplayName)(e)}function Rl(e,t){let n=`We couldn't open ${La(e)}. Try again or choose another payment method.`;return t?`${n} Allow pop-ups for this site, then try again.`:n}function us(e){let t=(0,a.useRef)(0),n=(0,a.useRef)(null),r=(0,a.useRef)(null),o=(0,a.useCallback)((f=r.current)=>{let C=f;C?.timer&&(clearTimeout(C.timer),C.timer=null)},[]),i=(0,a.useCallback)((f,C)=>{typeof document<"u"&&document.visibilityState!=="visible"||(o(f),f.timer=setTimeout(()=>{f.timer=null,r.current?.generation===f.generation&&(r.current=null,n.current=f.generation,e(f.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}))},C))},[o,e]),u=(0,a.useCallback)(f=>{f.yieldedControl&&i(f,600)},[i]),c=(0,a.useCallback)(f=>{o();let C=t.current+1;t.current=C,n.current=null;let ge={generation:C,method:f,timer:null,yieldedControl:!1};return r.current=ge,C},[o]),P=(0,a.useCallback)(f=>{let C=r.current;return typeof f=="number"&&C?.generation!==f?!1:(o(C),r.current=null,(typeof f!="number"||n.current===f)&&(n.current=null),!0)},[o]),g=(0,a.useCallback)(f=>{let C=r.current,ge=f??C?.generation??t.current;(!f||C?.generation===f)&&(o(C),r.current=null),n.current=ge},[o]),b=(0,a.useCallback)(f=>n.current===(f??t.current),[]),v=(0,a.useCallback)(f=>r.current?.generation===f&&n.current!==f,[]),N=(0,a.useCallback)(()=>{let f=r.current;f&&u(f)},[u]),B=(0,a.useCallback)(()=>{let f=r.current;f&&(f.yieldedControl=!0,o(f))},[o]);return(0,a.useEffect)(()=>{let f=()=>{document.visibilityState==="visible"?N():B()},C=()=>{B()};return document.addEventListener("visibilitychange",f),window.addEventListener("blur",C),window.addEventListener("focus",N),()=>{document.removeEventListener("visibilitychange",f),window.removeEventListener("blur",C),window.removeEventListener("focus",N),o()}},[o,B,N]),{startAttempt:c,finishAttempt:P,invalidateAttempt:g,isAttemptInvalidated:b,isAttemptCurrent:v}}function El(e){let t=(0,p.getPostalCodeExample)(e);return`Enter a valid ${(0,p.getPostalCodeLabel)(e)}${t?` (e.g. ${t})`:""}`}function _l(e,t,n){let r=(0,p.isPostalCodeSupported)(e),o=t.trim(),i=n&&r,u=i&&!o,c=i&&!!o&&!(0,p.isValidPostalCode)(e,o);return{visible:n,supported:r,required:i,empty:u,malformed:c}}function xl(e,t){let n=e.trim(),r=t&&!n,o=t&&!!n&&!(0,p.isValidEmail)(n);return{required:t,empty:r,malformed:o,value:n}}function rs(e,t){return t instanceof p.FloPayError?t:new p.FloPayError(t instanceof Error?t.message:`${Il(e)} before-click hook failed.`,"validation_error")}function Da(){return(0,l.jsx)("style",{children:wl})}function Tl(e){return typeof e=="number"?`${e}px`:e}function ps(e,t){let n=e.availablePaymentMethods;return n&&t.some(r=>n[r])?"ready":"unavailable"}function ms({state:e,placeholderTestId:t,borderRadius:n=8,children:r}){return e==="unavailable"||e==="load_error"?null:(0,l.jsxs)("div",{style:{position:"relative",minHeight:44},children:[(0,l.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,l.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 os(e){return e!=="unavailable"&&e!=="load_error"}function ta(e){return(0,l.jsx)(Bl,{...e})}function as({sessionId:e,nonce:t,email:n,billingApiUrl:r,onTokenizedBody:o,onErrorChange:i,isProcessing:u=!1,onButtonClick:c,onDecline:P,onTechnicalFailure:g,runBeforeButtonClick:b,billingName:v,onBuyerIdentityReady:N,onLoadStateChange:B,placeholderBorderRadius:f}){let C=or(),{emitInstrument:ge}=(0,a.useContext)(kn),$=(0,Rt.useStripe)(),S=(0,Rt.useElements)(),[ye,j]=(0,a.useState)("loading");(0,a.useEffect)(()=>{B?.(ye)},[ye,B]);let[pe,J]=(0,a.useState)(!1),he=!(0,p.isValidEmail)(n?.trim())||!v?.trim(),{request:ze,collect:we,finish:yt}=zr(),Me=(0,a.useRef)(!1),Ie=(0,a.useRef)(null),Re=(0,a.useRef)(null),[re,oe]=(0,a.useState)(0),[O,Ee]=(0,a.useState)(!1),_e=(0,a.useRef)(!1),X=(0,a.useRef)(new Map),{startAttempt:ke,finishAttempt:Ce,invalidateAttempt:x,isAttemptInvalidated:q,isAttemptCurrent:xe}=us((ae,Z,H)=>{g?.(ae,Z,{...H,popupBlocked:H?.popupBlocked??gr(Z)}),Ee(!0),oe(Te=>Te+1)});(0,a.useEffect)(()=>{O&&Re.current?.focus()},[O,re]);let fe=(0,a.useCallback)(()=>{oe(ae=>ae+1)},[]),te=(0,a.useCallback)((ae,Z,H)=>{x(H),g?.("paypal",ae,{code:Z,popupBlocked:gr(ae)}),Ee(!0),fe()},[x,g,fe]),Fe=(0,a.useCallback)(()=>{window.setTimeout(()=>{(Ie.current?.querySelector("iframe")??Ie.current)?.focus()},0)},[]);(0,a.useEffect)(()=>{_e.current&&(_e.current=!1,Fe())},[Fe,re]);let Qe=(0,a.useCallback)(()=>{Ee(!1),i?.(null),Fe()},[Fe,i]);(0,a.useEffect)(()=>{if(!$||Me.current)return;let ae=new URLSearchParams(window.location.search),Z=ae.get("payment_intent"),H=ae.get("payment_intent_client_secret"),Te=ae.get("redirect_status");if(!Z||!H)return;Me.current=!0;let He;try{let ie=localStorage.getItem(bo);if(ie){let L=JSON.parse(ie);L.clientSecret===H&&(He={...L.accountPatch?{accountPatch:L.accountPatch}:{},...L.sessionId?{sessionId:L.sessionId}:{},...L.nonce?{nonce:L.nonce}:{}})}}catch{}try{localStorage.removeItem(bo)}catch{}let M=new URL(window.location.href);M.searchParams.delete("payment_intent"),M.searchParams.delete("payment_intent_client_secret"),M.searchParams.delete("redirect_status"),window.history.replaceState({},"",M.toString()),(async()=>{try{if(J(!0),Te==="failed"){let E="PayPal payment was declined. Please try again.";i?.(E),P?.(Ft("paypal",E));return}let{paymentIntent:ie,error:L}=await $.retrievePaymentIntent(H);if(L){i?.(L.message??"Failed to retrieve PayPal payment status.");return}if(ie&&(ie.status==="requires_capture"||ie.status==="succeeded")){let E=typeof ie.payment_method=="string"?ie.payment_method:ie.payment_method?.id;o({id:E??ie.id,type:"card",threeDSecureActionResultTokenId:ie.id,isPaypal:!0},He)}else{let E="PayPal payment was not completed. Please try again.";i?.(E),P?.(Ft("paypal",E))}}catch(ie){i?.(ie instanceof Error?ie.message:"Failed to complete PayPal payment.")}finally{J(!1)}})()},[$,o,i,P]);let ot=(0,a.useCallback)(async ae=>{if(u||pe){ae.reject();return}let Z=b?await b("paypal"):{proceed:!0};if(!Z.proceed){X.current.delete(re),ae.reject();return}let H=ke("paypal");X.current.set(re,{generation:H,accountPatch:Z.accountPatch,sessionId:Z.sessionId,nonce:Z.nonce}),Ee(!1),c?.("paypal"),ae.resolve()},[X,u,c,b,ke,pe,re]),Le=(0,a.useCallback)(async ae=>{if(!$||!S)return;let Z=X.current.get(re);if(Z&&!xe(Z.generation)){X.current.delete(re);return}if(!Z&&q()||Z&&!Ce(Z.generation))return;Z||Ce();let H=Z??null;if(X.current.delete(re),!H&&b){let E=await b("paypal");if(!E.proceed){ae.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}H={accountPatch:E.accountPatch,sessionId:E.sessionId,nonce:E.nonce}}let Te=H?.sessionId??e,He=H?.nonce??t,M=await cs({event:ae,prepared:H,email:n,billingName:v,methodLabel:"PayPal",collect:we});if(!M){ae.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let ie=M.email,L=nn({...H?.accountPatch,...M});try{if(J(!0),i?.(null),!Te||!(0,p.isValidEmail)(ie))throw new Error("Missing sessionId or email for PayPal payment");await N?.(M);let E=$.createPaymentMethod,{error:et,paymentMethod:ft}=await E({type:"paypal"});if(et){te(et,"stripe_paypal_create_payment_method_failed",Z?.generation),ae.paymentFailed({reason:"fail"});return}let ce=await Qo(r,ge,Te,He??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:ft?.id??null,intentKind:"payment"});if(ce.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let tt=ce.clientSecret,Ge={return_url:window.location.href};if(ft?.id&&(Ge.payment_method=ft.id),typeof window<"u")try{localStorage.setItem(bo,JSON.stringify({clientSecret:tt,sessionId:Te,nonce:He,accountPatch:L}))}catch{}let{error:gt,paymentIntent:St}=await $.confirmPayment({clientSecret:tt,confirmParams:Ge,redirect:"if_required"});if(gt){if(typeof window<"u")try{localStorage.removeItem(bo)}catch{}if(uo(gt)){let se=gt.message??"Your payment was declined.";i?.(se),P?.(Ft("paypal",se,{code:rr(gt),declineCode:qr(gt)})),await ea({billingApiUrl:r,sessionId:Te,nonce:He,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:rr(gt)??"provider_declined"}})}else te(gt,"stripe_paypal_confirm_failed",Z?.generation);return}if(typeof window<"u")try{localStorage.removeItem(bo)}catch{}let w=typeof St?.payment_method=="string"?St.payment_method:St?.payment_method?.id;o({id:w??St?.id,type:"card",threeDSecureActionResultTokenId:St?.id,isPaypal:!0},{accountPatch:L,sessionId:Te,nonce:He});return}catch(E){te(E,"stripe_paypal_failed",Z?.generation)}finally{J(!1)}},[$,S,e,t,n,v,we,N,r,ge,o,i,P,b,te,Ce,xe,q,re]);return(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(ms,{state:ye,placeholderTestId:"flopay-paypal-placeholder",borderRadius:f,children:(0,l.jsxs)("div",{ref:Ie,tabIndex:-1,"data-testid":"flopay-paypal-focus-target",role:"group","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[O&&(0,l.jsx)("button",{ref:Re,type:"button","data-testid":"flopay-paypal-retry-button",onClick:Qe,style:ds,children:"Try PayPal again"}),ze&&(0,l.jsx)(Ur,{identity:ze.identity,methodLabel:ze.methodLabel,onComplete:yt,onCancel:()=>yt(null)},ze.id),(0,l.jsx)("div",{style:{display:ze?"none":void 0},children:(0,l.jsx)(Rt.ExpressCheckoutElement,{onReady:ae=>j(ps(ae,["paypal"])),onLoadError:()=>{j("load_error"),Oa(Dt(C),"paypal","paypal")},onClick:ot,onConfirm:Le,onCancel:()=>{let ae=X.current.get(re);X.current.delete(re),Dt(C)?.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),x(ae?.generation),Ee(!1),_e.current=!0,fe()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:he,emailRequired:he,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},re)})]})}),pe&&(0,l.jsx)(Rn,{status:"processing"})]})}function is({sessionId:e,nonce:t,email:n,billingApiUrl:r,intentKind:o,expressMethods:i,onTokenizedBody:u,onErrorChange:c,onButtonClick:P,onDecline:g,onTechnicalFailure:b,runBeforeButtonClick:v,billingName:N,onBuyerIdentityReady:B,onLoadStateChange:f,placeholderBorderRadius:C}){let ge=or(),{emitInstrument:$}=(0,a.useContext)(kn),S=(0,Rt.useStripe)(),ye=(0,Rt.useElements)(),[j,pe]=(0,a.useState)("loading");(0,a.useEffect)(()=>{f?.(j)},[j,f]);let[J,he]=(0,a.useState)(!1),ze=!(0,p.isValidEmail)(n?.trim())||!N?.trim(),{request:we,collect:yt,finish:Me}=zr(),Ie=(0,a.useRef)(null),Re=(0,a.useRef)(null),[re,oe]=(0,a.useState)(0),[O,Ee]=(0,a.useState)(!1),[_e,X]=(0,a.useState)("google_pay"),ke=(0,a.useRef)(!1),Ce=(0,a.useRef)("google_pay"),x=(0,a.useRef)("google_pay"),q=(0,a.useRef)(new Map),{startAttempt:xe,finishAttempt:fe,invalidateAttempt:te,isAttemptInvalidated:Fe,isAttemptCurrent:Qe}=us((M,ie,L)=>{b?.(M,ie,{...L,popupBlocked:L?.popupBlocked??gr(ie)}),X(M),Ee(!0),oe(E=>E+1)});(0,a.useEffect)(()=>{O&&Re.current?.focus()},[O,re]);let ot=(0,a.useCallback)(()=>{oe(M=>M+1)},[]),Le=(0,a.useCallback)((M,ie,L,E)=>{te(E),b?.(M,ie,{code:L,popupBlocked:gr(ie)}),X(M),Ee(!0),ot()},[te,b,ot]),ae=(0,a.useCallback)(()=>{window.setTimeout(()=>{(Ie.current?.querySelector("iframe")??Ie.current)?.focus()},0)},[]);(0,a.useEffect)(()=>{ke.current&&(ke.current=!1,ae())},[ae,re]);let Z=(0,a.useCallback)(()=>{Ee(!1),c?.(null),ae()},[ae,c]),H=(0,a.useCallback)(async M=>{if(!S||!ye)return;let ie=q.current.get(re);if(ie&&!Qe(ie.generation)){q.current.delete(re);return}if(!ie&&Fe()||ie&&!fe(ie.generation))return;ie||fe();let L=M.expressPaymentType??ie?.method??Ce.current,E=ie??null;q.current.delete(re);let et=ns(L);if(!E&&v){let w=await v(et);if(!w.proceed){M.paymentFailed({reason:"fail",message:"Wallet checkout was cancelled."});return}E={accountPatch:w.accountPatch,sessionId:w.sessionId,nonce:w.nonce}}let ft=et,ce=E?.sessionId??e,tt=E?.nonce??t,Ge=await cs({event:M,prepared:E,email:n,billingName:N,methodLabel:La(L),collect:yt});if(!Ge){M.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let gt=Ge.email,St=nn({...E?.accountPatch,...Ge});try{if(he(!0),c?.(null),!(0,p.isValidEmail)(gt))throw new Error("Missing sessionId or email for wallet payment");await B?.(Ge);let{error:w}=await ye.submit();if(w){Le(L,w,"stripe_wallet_submit_failed",ie?.generation);return}let{error:se,paymentMethod:de}=await S.createPaymentMethod({elements:ye});if(se||!de){Le(L,se??new Error("Failed to create payment method."),"stripe_wallet_create_payment_method_failed",ie?.generation);return}if(!ce)throw new Error("Missing sessionId or email for wallet payment");let at=await Qo(r,$,ce,tt??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:L??et,paymentMethodId:de.id,intentKind:o});if(at.provider!=="stripe")throw new Error("Invalid provider returned for wallet intent");let Tt=at.clientSecret,{error:Pt,intentId:Je}=(0,p.isSetupIntentClientSecret)(Tt)?await S.confirmCardSetup(Tt,{payment_method:de.id}).then(Ye=>({error:Ye.error,intentId:Ye.setupIntent?.id})):await S.confirmCardPayment(Tt,{payment_method:de.id}).then(Ye=>({error:Ye.error,intentId:Ye.paymentIntent?.id}));if(Pt){if(uo(Pt)){let Ye=Pt.message??"Your payment was declined.";c?.(Ye),g?.(Ft(ft,Ye,{code:rr(Pt),declineCode:qr(Pt)})),await ea({billingApiUrl:r,sessionId:ce,nonce:tt,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:L??et,providerDeclineReason:rr(Pt)??"provider_declined"}})}else Le(L,Pt,"stripe_wallet_confirm_failed",ie?.generation);return}u({id:de.id,type:"card",threeDSecureActionResultTokenId:Je},{accountPatch:St,sessionId:ce,nonce:tt})}catch(w){Le(L,w,"stripe_wallet_failed",ie?.generation)}finally{he(!1)}},[S,ye,e,t,n,N,yt,B,r,$,o,u,c,g,v,Le,fe,Qe,Fe,re]),Te=(0,a.useMemo)(()=>{let M=["applePay","googlePay","paypal","link","amazonPay","klarna"],ie=new Set(["applePay","googlePay"]),L=new Set(i.map(p.stripeExpressMethodToOptionKey)),E={};for(let et of M)L.has(et)?E[et]=ie.has(et)?"always":"auto":E[et]="never";return E},[i]),He=(0,a.useMemo)(()=>i.map(p.stripeExpressMethodToOptionKey),[i]);return(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(ms,{state:j,placeholderTestId:"flopay-wallet-placeholder",borderRadius:C,children:(0,l.jsxs)("div",{ref:Ie,tabIndex:-1,"data-testid":"flopay-wallet-focus-target",role:"group","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[O&&(0,l.jsxs)("button",{ref:Re,type:"button","data-testid":"flopay-wallet-retry-button",onClick:Z,style:ds,children:["Try ",La(_e)," again"]}),we&&(0,l.jsx)(Ur,{identity:we.identity,methodLabel:we.methodLabel,onComplete:Me,onCancel:()=>Me(null)},we.id),(0,l.jsx)("div",{style:{display:we?"none":void 0},children:(0,l.jsx)(Rt.ExpressCheckoutElement,{onReady:M=>{pe(ps(M,He))},onLoadError:M=>{pe("load_error"),Oa(Dt(ge),"stripe","wallet")},onClick:async M=>{Ce.current=M.expressPaymentType,x.current=ns(M.expressPaymentType);let ie=v?await v(x.current):{proceed:!0};if(!ie.proceed){q.current.delete(re),M.reject();return}let L=xe(M.expressPaymentType);q.current.set(re,{generation:L,method:M.expressPaymentType,accountPatch:ie.accountPatch,sessionId:ie.sessionId,nonce:ie.nonce}),Ee(!1),P?.(x.current),M.resolve()},onConfirm:H,onCancel:()=>{let M=q.current.get(re);q.current.delete(re),Dt(ge)?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet"}),te(M?.generation),Ee(!1),ke.current=!0,ot()},options:{buttonType:{applePay:"plain",googlePay:"plain"},paymentMethods:Te,emailRequired:ze,billingAddressRequired:ze,layout:{maxColumns:1,overflow:"never"}}},re)})]})}),J&&(0,l.jsx)(Rn,{status:"processing"})]})}function Al({method:e,themeId:t,submitting:n=!1,disabled:r=!1,highlighted:o=!1,hasNextStep:i=!1,onClick:u,backgroundColor:c,borderColor:P,textColor:g,borderRadius:b,fontFamily:v}){let N=(0,p.resolveStripeMethodBrandVariant)(e,t),B=Zi[e],[f,C]=(0,a.useState)(!1),ge=N?.backgroundColor??c??"#ffffff",$=N?.borderColor??P??"#d1d5db",S=N?.textColor??g??"#262833";return(0,l.jsx)("button",{type:"button","data-testid":`flopay-stripe-method-button-${e}`,"data-method":e,onClick:()=>{!n&&!r&&u()},disabled:n||r,"aria-busy":n||void 0,style:{position:"relative",width:"100%",boxSizing:"border-box",height:Zo,padding:"0 1rem",backgroundColor:ge,color:S,border:`1px solid ${$}`,borderRadius:b??8,fontSize:"0.95rem",fontWeight:600,fontFamily:v,cursor:n||r?"not-allowed":"pointer",opacity:r&&!n?.55:1,animation:n?"flopay-pulse 1.5s ease-in-out infinite":void 0,display:"flex",alignItems:"center",justifyContent:"center",gap:8,transition:"transform 0.1s, opacity 140ms ease-out, border-color 140ms ease-out",boxShadow:o?"0 0 0 2px rgba(74, 73, 255, 0.15)":void 0},children:n?(0,l.jsx)("span",{style:{margin:"0 auto"},children:`Connecting to ${(0,p.getStripeMethodDisplayName)(e)}\u2026`}):(0,l.jsxs)(l.Fragment,{children:[(0,l.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:(0,p.hasVendoredStripeMethodLogo)(e)?8:0},children:[B&&!f?(0,l.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,l.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,l.jsx)("span",{children:(0,p.getStripeMethodDisplayName)(e)})]}),i&&(0,l.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,l.jsx)("path",{d:"M9 18l6-6-6-6"})})]})})}function Na({method:e,sessionId:t,nonce:n,email:r,billingName:o,onBuyerIdentityReady:i,billingApiUrl:u,onTokenizedBody:c,onErrorChange:P,onDecline:g,onCancel:b,runBeforeButtonClick:v,onButtonClick:N,isProcessing:B,submitButtonColor:f,submitButtonBorderRadius:C,submitButtonStyle:ge,errorText:$}){let S=or(),{emitInstrument:ye}=(0,a.useContext)(kn),j=(0,Rt.useStripe)(),pe=(0,Rt.useElements)(),[J,he]=(0,a.useState)(!1),ze=(0,a.useRef)(!1),[we,yt]=(0,a.useState)(!1),[Me,Ie]=(0,a.useState)("loading"),[Re,re]=(0,a.useState)(""),oe=!(0,p.isValidEmail)(r?.trim()),O=!oe||(0,p.isValidEmail)(Re.trim()),Ee=(0,a.useCallback)(async()=>{if(!j||!pe||B||ze.current||!we)return;ze.current=!0,he(!0);let _e=v?await v("card"):{proceed:!0};if(!_e.proceed){ze.current=!1,he(!1);return}N?.("card");let X=_e.sessionId??t,ke=_e.nonce??n,Ce=Sr(o?.trim()),x=nn({email:_e.accountPatch?.email?.trim()||r?.trim()||Re.trim(),firstName:_e.accountPatch?.firstName?.trim()||Ce.firstName,lastName:_e.accountPatch?.lastName?.trim()||Ce.lastName}),q=x.email,xe=nn({..._e.accountPatch,...x});try{if(P?.(null),!(0,p.isValidEmail)(q))throw new Error("A valid email address is required for payment.");await i?.(x);let fe=await pe.submit();if(fe.error){P?.(fe.error.message??"Payment failed.");return}let te=[x.firstName,x.lastName].filter(Boolean).join(" "),Fe=await j.createPaymentMethod({elements:pe,params:{billing_details:{email:q,...te?{name:te}:{}}}});if(Fe.error||!Fe.paymentMethod){P?.(Fe.error?.message??"Failed to create payment method.");return}let Qe=Fe.paymentMethod;if(!X||!q)throw new Error("Missing sessionId or email for payment.");let ot=Qe.type||e,Le=await Qo(u,ye,X,ke??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:ot,paymentMethodId:null,intentKind:"payment"});if(Le.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let ae=Le.clientSecret;if(typeof window<"u")try{localStorage.setItem(Kn,JSON.stringify({clientSecret:ae,sessionId:X,nonce:ke,accountPatch:xe,paymentMethodId:Qe.id,paymentMethodType:Qe.type??e,gateway:"stripe"}))}catch{}let{error:Z,paymentIntent:H}=await j.confirmPayment({clientSecret:ae,confirmParams:{return_url:window.location.href,payment_method:Qe.id},redirect:"if_required"});if(Z){if(typeof window<"u")try{localStorage.removeItem(Kn)}catch{}let M=Z.message??"Payment failed.";P?.(M),g?.(Ft("card",M,{code:Z.code})),await ea({billingApiUrl:u,sessionId:X,nonce:ke,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:Z.code??"provider_declined"}});return}let Te=H?.status;if(!zo(Te)){if(typeof window<"u")try{localStorage.removeItem(Kn)}catch{}let M=Te==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";P?.(M),g?.(Ft("card",M,{code:Te??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(Kn)}catch{}let He=typeof H?.payment_method=="string"?H.payment_method:H?.payment_method?.id;c({id:He??Qe.id,type:"card",threeDSecureActionResultTokenId:H?.id,gateway:"stripe",paymentMethodType:Qe.type??e},{accountPatch:xe,sessionId:X,nonce:ke})}catch(fe){P?.(fe instanceof Error?fe.message:"Payment failed. Please try again.")}finally{ze.current=!1,he(!1)}},[j,pe,B,we,v,N,t,n,r,o,Re,i,u,ye,e,c,P,g]);return(0,l.jsxs)("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[oe&&(0,l.jsx)("div",{"data-testid":"flopay-apm-identity-fields",style:{display:"flex",flexDirection:"column",gap:"0.75rem",marginBottom:"0.75rem"},children:oe&&(0,l.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",(0,l.jsx)("input",{type:"email",autoComplete:"email",required:!0,value:Re,onChange:_e=>re(_e.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]})}),(0,l.jsx)(Rt.PaymentElement,{onReady:()=>Ie("ready"),onLoadError:()=>{Ie("load_error"),Oa(Dt(S),"stripe","apm")},onChange:_e=>{yt(!!_e.complete)},options:{layout:{type:"accordion",defaultCollapsed:!1,radios:"never"},fields:{billingDetails:{email:"never"}},defaultValues:{billingDetails:{...o?.trim()?{name:o.trim()}:{},...(0,p.isValidEmail)(r?.trim())?{email:r?.trim()}:{}}}}}),(0,l.jsx)("button",{type:"button","data-testid":`flopay-stripe-method-pay-${e}`,onClick:()=>{Ee()},disabled:!we||!O||J||B||Me!=="ready",style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:f,color:"white",border:"none",borderRadius:C,fontSize:"1rem",fontWeight:600,cursor:!we||!O||J||B||Me!=="ready"?"not-allowed":"pointer",opacity:!we||!O||J||B||Me!=="ready"?.5:1,transition:"opacity 120ms ease-out",...ge??{}},children:J?"Processing\u2026":`Pay with ${(0,p.getStripeMethodDisplayName)(e)}`}),$&&(0,l.jsx)(jr,{margin:"0.75rem 0 0",children:$})]})}function ss({sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:i,paymentElementMethods:u,stripeInstance:c,paymentElementBaseOptions:P,onTokenizedBody:g,onErrorChange:b,onButtonClick:v,onDecline:N,runBeforeButtonClick:B,onLoadStateChange:f,isProcessing:C=!1,submitButtonColor:ge="#4A49FF",submitButtonBorderRadius:$=8,submitButtonStyle:S,buttonAppearance:ye,themeId:j,onExpandApm:pe,expandedApmMethod:J}){let{emitInstrument:he}=(0,a.useContext)(kn),[ze,we]=(0,a.useState)(null),[yt,Me]=(0,a.useState)(null),Ie=(0,a.useRef)(!1),{request:Re,collect:re,finish:oe}=zr();(0,a.useEffect)(()=>{u.length>0&&c?f?.("ready"):c||f?.("loading")},[u.length,c,f]);let O=(0,a.useCallback)(async x=>{if(!c||Ie.current||C)return;Ie.current=!0,Me(x);let q=B?await B("card"):{proceed:!0};if(!q.proceed){Ie.current=!1,Me(null);return}v?.("card");let xe=q.sessionId??e,fe=q.nonce??t,te=Sr([q.accountPatch?.firstName,q.accountPatch?.lastName].filter(Boolean).join(" ")||r),Fe=nn({email:q.accountPatch?.email?.trim()||n?.trim(),firstName:q.accountPatch?.firstName?.trim()||te.firstName,lastName:q.accountPatch?.lastName?.trim()||te.lastName});if(!(0,p.isValidEmail)(Fe.email)){Me(null);let Le=await re((0,p.getStripeMethodDisplayName)(x),Fe);if(!Le){Ie.current=!1;return}Fe=Le,Me(x)}let Qe=Fe.email,ot=nn({...q.accountPatch,...Fe});try{if(b?.(null),!xe||!(0,p.isValidEmail)(Qe))throw new Error("Missing sessionId or email for payment.");await o?.(Fe);let Le=await Qo(i,he,xe,fe??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:x,paymentMethodId:null,intentKind:"payment"});if(Le.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let ae=Le.clientSecret;if(typeof window<"u")try{localStorage.setItem(Kn,JSON.stringify({clientSecret:ae,sessionId:xe,nonce:fe,accountPatch:ot,paymentMethodType:x,gateway:"stripe"}))}catch{}let{error:Z,paymentIntent:H}=await c.confirmPayment({clientSecret:ae,confirmParams:{return_url:window.location.href,payment_method_data:{type:x,billing_details:{name:[Fe.firstName,Fe.lastName].filter(Boolean).join(" "),...Qe?{email:Qe}:{}}}},redirect:"if_required"});if(Z){if(typeof window<"u")try{localStorage.removeItem(Kn)}catch{}let M=Z.message??"Payment failed.";b?.(M),N?.(Ft("card",M,{code:Z.code})),await ea({billingApiUrl:i,sessionId:xe,nonce:fe,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:x,providerDeclineReason:Z.code??"provider_declined"}});return}let Te=H?.status;if(!zo(Te)){if(typeof window<"u")try{localStorage.removeItem(Kn)}catch{}let M=Te==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";b?.(M),N?.(Ft("card",M,{code:Te??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(Kn)}catch{}let He=typeof H?.payment_method=="string"?H.payment_method:H?.payment_method?.id;g({id:He??H?.id,type:"card",threeDSecureActionResultTokenId:H?.id,gateway:"stripe",paymentMethodType:x},{accountPatch:ot,sessionId:xe,nonce:fe})}catch(Le){b?.(Le instanceof Error?Le.message:"Payment failed. Please try again.")}finally{Ie.current=!1,Me(null)}},[c,C,B,v,e,t,n,re,i,he,r,o,g,b,N]),[Ee,_e]=(0,a.useState)(null),X=pe?J??null:Ee,ke=(0,a.useCallback)(x=>{Ie.current||C||X&&X!==x||((0,p.needsStripeMethodExplicitConfirm)(x)?pe?pe(x):_e(x):O(x))},[X,C,O,pe]),Ce=(0,a.useMemo)(()=>Ee?{...P,paymentMethodTypes:[Ee]}:null,[Ee,P]);return(0,l.jsx)("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:Re?(0,l.jsx)(Ur,{identity:Re.identity,methodLabel:Re.methodLabel,onComplete:oe,onCancel:()=>oe(null)},Re.id):u.map(x=>{let q=J===x,xe=yt===x,fe=yt!==null&&yt!==x||J!=null&&J!==x;return(0,l.jsxs)(a.default.Fragment,{children:[(0,l.jsx)(Al,{method:x,themeId:j,submitting:xe,disabled:fe,highlighted:q,hasNextStep:(0,p.needsStripeMethodExplicitConfirm)(x),onClick:()=>ke(x),backgroundColor:ye?.backgroundColor,borderColor:ye?.borderColor,textColor:ye?.textColor,borderRadius:ye?.borderRadius,fontFamily:ye?.fontFamily}),!pe&&Ee===x&&Ce&&c&&(0,l.jsx)(Rt.Elements,{stripe:c,options:Ce,children:(0,l.jsx)(Na,{method:x,sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:i,onTokenizedBody:g,onErrorChange:b,onDecline:N,onCancel:()=>_e(null),runBeforeButtonClick:B,onButtonClick:v,isProcessing:C,submitButtonColor:ge,submitButtonBorderRadius:$,submitButtonStyle:S})},x)]},x)})})}function Bl({sessionId:e,nonce:t,billingApiUrl:n,email:r,userId:o,onComplete:i,onError:u,onDecline:c,onTokenizedBody:P,firstName:g,lastName:b,chv:v,className:N,isProcessing:B,error:f,onErrorChange:C,showPayPal:ge=!0,showStripe:$=!0,enabledPaymentMethods:S,enabledPaymentMethodCountries:ye,showApplePay:j=!0,showGooglePay:pe=!0,layout:J="default",theme:he,buttonsTheme:ze,buttonsStyles:we,appearance:yt,cardButtonContent:Me,cardBackButtonContent:Ie,cardTitleContent:Re,showSecurityFooter:re,onButtonClick:oe,onBeforeButtonClick:O,onBuyerIdentityReady:Ee,enableAVS:_e,cardFieldOrder:X,cardPreFormSlot:ke,avsLayout:Ce="row",country:x,zip:q,addressLine1:xe,addressLine2:fe,city:te,state:Fe,onCountryChange:Qe,onZipChange:ot,avsCheck:Le,checkoutType:ae,checkoutLayout:Z,totalAmount:H=0,currency:Te="usd",initialCardOpen:He=!1,directPaypal:M,isSubscription:ie=!1,session:L,dataAttachmentPending:E=!1,dataAttachmentRequiresIdentity:et=!1,debug:ft=!1}){let ce=or(),tt=Uo(),Ge=(0,a.useContext)(Ln),{emitInstrument:gt}=(0,a.useContext)(kn),St=E||Ge.claimPending===!0,w=et||Ge.claimRequiresIdentity===!0,se=St&&!w,de=zi(),[at,Tt]=(0,a.useState)(!1),[Pt,Je]=(0,a.useState)(null),[Ye,jt]=(0,a.useState)(x??"US"),[Lt,At]=(0,a.useState)(q??""),[dn,_n]=(0,a.useState)(xe??""),[zn,Jt]=(0,a.useState)(fe??""),[xn,Ht]=(0,a.useState)(te??""),[nt,un]=(0,a.useState)(Fe??""),[je,Un]=(0,a.useState)(""),[it,cr]=(0,a.useState)({}),Nt=(0,a.useRef)(q??""),Vt=(0,a.useRef)(x??"US"),pn=(0,a.useRef)(xe??""),rn=(0,a.useRef)(fe??""),mn=(0,a.useRef)(te??""),Bt=(0,a.useRef)(Fe??""),dr=(0,a.useRef)(""),Ot=(0,a.useRef)({});(0,a.useEffect)(()=>{let s=(_,K,De,G,Be)=>{if(Ot.current[_])return;let $e=K?.trim();!$e||$e===De.current||(De.current=$e,G($e),Be?.($e))};s("country",x,Vt,jt,Qe),s("zip",q,Nt,At,ot),s("addressLine1",xe,pn,_n),s("addressLine2",fe,rn,Jt),s("city",te,mn,Ht),s("state",Fe,Bt,un)},[x,q,xe,fe,te,Fe,Qe,ot]);let ue=(0,a.useMemo)(()=>(0,p.resolveAVSConfig)(_e),[_e]),ur=ue!==null,yn=(0,a.useMemo)(()=>(0,p.isAuthorizationOnlySession)(L),[L]),Xt=!!L?.vault?.html,qn=!!L?.gateways?.pcivault,Wn=!!(L?.gateways?.stripe?.enabledPaymentMethods??S)?.includes("card"),gn=Xt||Wn||qn,h=!!($&&gn&&ce&&e),[ht,Kt]=(0,a.useState)(()=>J!=="buttons"||He?e??null:null),[Gn,Ue]=(0,a.useState)(0),wt=J!=="buttons"||He||!!e&&ht===e,ct=(0,a.useMemo)(()=>!ce||!h||!e||!wt?null:ce.cardCapture({sessionId:e,captureMethod:L?.captureMethod}),[ce,h,e,wt,L?.captureMethod]),Yt=(0,a.useMemo)(()=>{let s=Ye,_=ue?(0,p.isAVSFieldVisible)(ue.postal_code,s):!1;return _l(s,Lt,_)},[ue,Ye,Lt]),{avsInvalid:Jn,invalidAvsFields:pr}=(0,a.useMemo)(()=>{let s={line1:!1,city:!1,state:!1,zip:!1};if(!h||!ue)return{avsInvalid:!1,invalidAvsFields:s};let _=Ye,K=(Be,$e)=>(0,p.isAVSFieldVisible)(Be,_)&&!$e.trim(),De={line1:K(ue.address_line_1,dn),city:K(ue.city,xn),state:K(ue.state,nt),zip:Yt.empty||Yt.malformed};return{avsInvalid:De.line1||De.city||De.state||De.zip,invalidAvsFields:De}},[h,ue,Ye,dn,xn,nt,Yt]),[Xn,br]=(0,a.useState)(!1),[hn,Zn]=(0,a.useState)(!1),[$n,Zt]=(0,a.useState)(!1),[bt,Tn]=(0,a.useState)({line1:!1,city:!1,state:!1}),on=(0,a.useRef)(!1),Qt=(0,a.useRef)({email:!1,line1:!1,city:!1,state:!1,zip:!1}),en=(0,a.useRef)(!1),st=(0,a.useCallback)(s=>{Qt.current[s]=!0,en.current=!0},[]),Qn=(0,a.useCallback)(s=>!on.current&&Qt.current[s],[]),An=(0,a.useCallback)(s=>{Qn(s)&&Tn(_=>_[s]?_:{..._,[s]:!0})},[Qn]),[bn,Bn]=(0,a.useState)(()=>Fa(L?.vault)),[qe,Mt]=(0,a.useState)(He&&gn?"card":"buttons"),[Et,Mn]=(0,a.useState)(null),mr=qe==="expanding"||qe==="card",er=L?.gateways?.stripe?"stripe":void 0,an=(0,a.useCallback)(()=>{gt?.({class:"card_surface",provider:er})},[er,gt]),zt=280,vn=(0,a.useRef)(null),_t=(0,a.useCallback)(s=>{vn.current&&clearTimeout(vn.current),vn.current=setTimeout(()=>{vn.current=null,s()},zt)},[zt]);(0,a.useEffect)(()=>()=>{vn.current&&clearTimeout(vn.current)},[]);let U=(0,a.useCallback)(()=>{an(),Kt(e??null),Ue(s=>s+1),Mt("expanding"),_t(()=>Mt("card"))},[_t,an,e]),V=(0,a.useCallback)(()=>{Mt("collapsing"),_t(()=>Mt("buttons"))},[_t]),Y=(0,a.useCallback)(s=>{Mn(s),Mt("apm-expanding"),_t(()=>Mt("apm-form"))},[_t]),le=(0,a.useCallback)(()=>{Mt("apm-collapsing"),_t(()=>{Mt("buttons"),Mn(null)})},[_t]);(0,a.useEffect)(()=>{J==="buttons"&&He&&gn&&(Kt(e??null),Mt("card"))},[J,He,gn,e]);let[Ae,y]=(0,a.useState)(null),d=(0,a.useRef)(!1),m=(0,a.useRef)(null),T=(0,a.useRef)("idle"),[A,me]=(0,a.useState)(null),Xe=(0,a.useRef)(A);(0,a.useEffect)(()=>{Xe.current=A},[A]);let Q=n||de,ne=(0,a.useRef)(null),Se=(0,a.useMemo)(()=>{if(Ee||Ge.claimBuyerIdentity||L?.buyerIdentified!==!1||!e||!t)return;let s=`${Q}|${e}|${t}`;ne.current?.key!==s&&(ne.current={key:s,claim:Nr(new sr.PaymentAPI(Q,{telemetry:!1}),e,t,{...o?{userId:o}:{},...g?{firstName:g}:{},...b?{lastName:b}:{}})});let _=ne.current.claim;return async K=>{await _(K)}},[Ee,Ge.claimBuyerIdentity,L?.buyerIdentified,e,t,Q,o,g,b]),z=Ee??Ge.claimBuyerIdentity??Se,k=f??Pt,W=(0,a.useMemo)(()=>(0,p.resolveTheme)(he),[he]),F=(0,a.useMemo)(()=>{let s=W?.buttonsLayout??(0,p.resolveButtonsLayoutTheme)(ze);return we?{...s,...we,cardButton:{...s.cardButton,...we.cardButton},cardFormContainer:{...s.cardFormContainer,...we.cardFormContainer},backButton:{...s.backButton,...we.backButton},backButtonIcon:{...s.backButtonIcon,...we.backButtonIcon},submitButton:{...s.submitButton,...we.submitButton},title:{...s.title,...we.title}}:s},[W,ze,we]),ee=yt??W?.appearance,Ve=(0,a.useMemo)(()=>Xo({appearance:ee,buttonsStyles:F,layout:J}),[ee,F,J]),vr=Ge.inlineSessionPatchProcessing??!1,lt=(B??at)||vr,dt=Q.replace(/\/+$/,""),ve=(0,a.useMemo)(()=>Ra({userId:o,email:r,firstName:g,lastName:b,country:x,zip:q},it),[o,r,g,b,x,q,it]),sn=[ve.firstName,ve.lastName].filter(s=>!!s?.trim()).join(" "),Xa=!(0,p.isValidEmail)(ve.email?.trim()),la=(0,a.useRef)(null);h&&la.current===null&&(la.current=Xa);let yr=h&&(la.current??Xa),ca=(0,a.useMemo)(()=>xl(je,yr),[je,yr]),xr=ca.empty||ca.malformed,Pn=(0,a.useMemo)(()=>ce?ce.getRawProvider():null,[ce]),Tr=(0,a.useMemo)(()=>tt?tt.getRawProvider():null,[tt]),Gr=H||100,wo=(0,a.useMemo)(()=>ee?(0,sr.toStripeAppearance)(ee):null,[ee]),ko=wo?{appearance:wo}:null,Za=(0,a.useMemo)(()=>{let s=wo??{},_=s.rules??{};return{...s,rules:{..._,".AccordionItem":{padding:"10px 14px",boxShadow:"none",..._[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",..._[".AccordionItemContents"]??{}}}}},[wo]),Qa=(0,a.useMemo)(()=>{let s=Di(H);return{...s,currency:Te.toLowerCase(),paymentMethodCreation:"manual",...s.mode==="payment"?{captureMethod:"manual"}:{},...ko}},[H,Te,ko]),ei=(0,a.useMemo)(()=>({mode:"payment",amount:Gr,currency:Te.toLowerCase(),captureMethod:"manual",setupFutureUsage:"off_session",...ko}),[Gr,Te,ko]),be=(0,a.useCallback)(s=>{Je(s),C?.(s)},[C]),da=(0,a.useRef)(""),[ti,ks]=(0,a.useState)(!1),ua=(0,a.useCallback)(()=>{ks(!0)},[]);(0,a.useEffect)(()=>{if(!h||!yr||!z||!ti||xr||da.current)return;let s=nn({email:(0,p.isValidEmail)(ve.email?.trim())?ve.email?.trim():dr.current.trim(),firstName:ve.firstName?.trim(),lastName:ve.lastName?.trim()});da.current=JSON.stringify(s),cr(_=>({..._,...s})),Promise.resolve(z(s)).catch(_=>{da.current="",be(_ instanceof Error?_.message:"Failed to attach buyer details.")})},[h,yr,z,ti,xr,ve.email,ve.firstName,ve.lastName,be]),(0,a.useEffect)(()=>{!h||!ct||ct.setCardFieldOrder?.(X??null,ue==null&&!yr)},[h,ct,X,ue,yr]),(0,a.useEffect)(()=>{(qe==="expanding"||qe==="collapsing"||qe==="apm-expanding"||qe==="apm-collapsing")&&be(null)},[qe,be]);let Fn=(0,a.useCallback)((s,_,K)=>{c?.(Ft(s,_,K))},[c]),Ar=(0,a.useCallback)((s,_,K)=>{let De=K?.popupBlocked??gr(_),G=Rl(s,De),Be=kr(K?.code)??rr(_)??"external_payment_method_failed",$e=new p.FloPayError(G,"api_error",{code:"external_payment_method_failed",param:s});y(null),J==="buttons"&&(Mt("buttons"),Mn(null)),be(G),u?.($e),console.error("[FloPay] External payment method failed:",{method:s,code:Be,popupBlocked:De})},[J,u,be]);(0,a.useEffect)(()=>{if(!h||!e){Bn(null);return}let s=Fa(L?.vault);if(s){Bn(s);return}if(!wt){Bn(null);return}Bn(null);let _=!0;return new sr.PaymentAPI(dt).getVaultCapture(e,t).then(K=>{if(!_)return;let De=Fa(K);De?Bn(De):be("Failed to load the secure card form.")}).catch(K=>{_&&be(K instanceof Error?K.message:"Failed to load the secure card form.")}),()=>{_=!1}},[h,wt,Gn,e,L?.vault?.html,L?.vault?.messageToken,L?.vault?.expectedOrigin,dt,t,be]);let jn=(0,a.useRef)({onComplete:i,onError:u,updateError:be,emitDecline:Fn,resolvedAccount:ve,avsConfig:ue,avsCheckProp:Le,sessionId:e,nonce:t,baseUrl:dt,captureMethod:L?.captureMethod,paymentId:L?.paymentId,authorizationExpiresAt:L?.authorizationExpiresAt});jn.current={onComplete:i,onError:u,updateError:be,emitDecline:Fn,resolvedAccount:ve,avsConfig:ue,avsCheckProp:Le,sessionId:e,nonce:t,baseUrl:dt,captureMethod:L?.captureMethod,paymentId:L?.paymentId,authorizationExpiresAt:L?.authorizationExpiresAt};let pa=(0,a.useRef)(!1),Is=(0,a.useCallback)(()=>{let{resolvedAccount:s,avsConfig:_,avsCheckProp:K}=jn.current,De=s.email?.trim(),G=(0,p.isValidEmail)(De)?De:dr.current.trim();if(!(0,p.isValidEmail)(G))return null;let Be=s.firstName?.trim(),$e=s.lastName?.trim(),rt=Vt.current||s.country||"US",Ut=_?(0,p.isAVSFieldVisible)(_.state,rt):!1,ut=_?(0,p.isAVSFieldVisible)(_.address_line_1,rt):!1,pt=_?(0,p.isAVSFieldVisible)(_.postal_code,rt):!1,Ze=_?(0,p.isAVSFieldVisible)(_.city,rt):!1,Wt=_?(0,p.isAVSFieldVisible)(_.address_line_2,rt):!1,We=ut&&!Ut&&pt?(0,p.getStateFromPostalCode)(rt,(Nt.current??"").trim()):null,Gt=Ut?Bt.current:We;return{accountData:{userId:s.userId??"",email:G,...Be?{firstName:Be}:{},...$e?{lastName:$e}:{},...pt&&Nt.current?{zip:Nt.current}:{},...Ze&&mn.current?{city:mn.current}:{},...Gt?{state:Gt}:{},...ut&&pn.current?{addressLine1:pn.current}:{},...Wt&&rn.current?{addressLine2:rn.current}:{},country:rt},...K!==void 0?{avsCheck:K}:{},..._?{avsConfig:{country:(0,p.isAVSFieldVisible)(_.country,rt),postal_code:pt,address_line_1:ut,address_line_2:Wt,city:Ze,state:Ut}}:{}}},[]),ni=(0,a.useRef)(St);ni.current=St,(0,a.useEffect)(()=>{St||k!==ts||jn.current.updateError(null)},[St,k]),(0,a.useEffect)(()=>{!h||!ct||ct.setSubmitGate?.(Jn||St||xr)},[h,ct,Jn,St,xr]),(0,a.useEffect)(()=>{if(!h||!ct)return;pa.current=!1;let s=!1,_=ct.on("submitting",()=>{br(!0),m.current&&clearTimeout(m.current),T.current="validation-window",m.current=setTimeout(()=>{m.current=null,T.current==="validation-window"&&(T.current="processing")},Pl),y("processing");let{baseUrl:$e,sessionId:rt,nonce:Ut,updateError:ut,onError:pt}=jn.current;if(!rt||!Ut)return;let Ze=Is();if(!Ze){ut("Enter a valid email address."),T.current="idle",y(null);return}new sr.PaymentAPI($e).patchAccountSnapshot(rt,Ut,Ze,{telemetryMode:"best_effort"}).catch(Wt=>{if(!Cl(Wt))return;let We=Wt instanceof Error?Wt.message:"Please check your billing address and try again.";ut(We),T.current="idle",y(null),pt?.(Wt instanceof p.FloPayError?Wt:new p.FloPayError(We,"api_error"))})}),K=ct.on("complete",async $e=>{if(Vr($e.sessionId??jn.current.sessionId),T.current="terminal",y("success"),await new Promise(ut=>setTimeout(ut,1200)),pa.current)return;pa.current=!0;let rt=jn.current,Ut=(0,p.isAuthorizationOnlySession)(rt)||$e.outcome==="authorized";jn.current.onComplete?.(Ut?{status:"authorized",paymentIntentId:$e.intentId,paymentId:$e.paymentId??rt.paymentId,sessionId:$e.sessionId??rt.sessionId,authorizationExpiresAt:$e.authorizationExpiresAt??rt.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",paymentIntentId:$e.intentId,checkoutMethod:"card"})}),De=ct.on("decline",async $e=>{let{updateError:rt,emitDecline:Ut}=jn.current,ut=$e.message??"Your payment was declined. Please try another card or contact your bank.";T.current="terminal",rt(ut),y("error");let pt=$e.failureOutcome??(0,p.normalizeCheckoutFailureOutcome)($e.declineReason)??"authorization_declined";Ut("card",ut,{code:pt,declineCode:pt}),await new Promise(Ze=>setTimeout(Ze,1500)),!s&&(T.current="idle",y(null))}),G=ct.on("error",async $e=>{let{updateError:rt,onError:Ut}=jn.current,ut=$e.message??"There was a problem processing your payment. Please try again.";T.current="terminal",rt(ut),y("error"),Ut?.(new p.FloPayError(ut,"api_error",{code:$e.failureOutcome??"capture_failed"})),await new Promise(pt=>setTimeout(pt,1500)),!s&&(T.current="idle",y(null))}),Be=ct.on("blocked",()=>{if(!ni.current){br(!0);return}ua(),jn.current.updateError(ts)});return()=>{s=!0,m.current&&(clearTimeout(m.current),m.current=null),T.current="idle",_(),K(),De(),G(),Be()}},[h,ct,ua]);let Vn=!!M?.clientId,Jr=Array.isArray(S),Io=Jr&&S.length>0,Rs=Jr&&S.includes("paypal"),{expressMethods:Ro,paymentElementMethods:Xr}=(0,a.useMemo)(()=>(0,p.partitionStripeMethods)(S,{excludePaypal:Vn}),[S,Vn]),ri=Vn||!!tt,Es=(0,a.useMemo)(()=>ri?Ro.filter(s=>s!=="paypal"):Ro,[Ro,ri]),_s=(0,a.useMemo)(()=>{let s=[];return j&&s.push("apple_pay"),pe&&s.push("google_pay"),s},[j,pe]),Eo=Jr?Es:_s,xs=$&&Eo.length>0,ma=ur?Ye:x,_o=(0,a.useMemo)(()=>{let s=ma?.trim().toUpperCase();return s?ye?Xr.filter(_=>{let K=ye[_];return!K||K.length===0||K.includes(s)}):(0,p.filterStripeMethodsByCountry)(Xr,ma):Xr},[Xr,ma,ye]),ya=(0,a.useMemo)(()=>({mode:"payment",amount:Gr,currency:Te.toLowerCase(),paymentMethodCreation:"manual",appearance:Za}),[Gr,Te,Za]),[oi,ai]=(0,a.useState)("loading"),[ii,si]=(0,a.useState)("loading"),[li,ci]=(0,a.useState)("loading"),[Ts,fa]=(0,a.useState)(!1),[di,ga]=(0,a.useState)("loading"),[xo,As]=(0,a.useState)();(0,a.useEffect)(()=>{As(Xi())},[]);let ui=ge&&(Vn||(Jr?Rs:xo===!1)),pi=$&&xs,Zr=!se&&ui&&Vn,mi=di==="retrying"||di==="exhausted",Qr=!se&&ui&&!!Tr&&(!Vn||mi),eo=!se&&pi&&!!Pn,to=!se&&$&&Io&&_o.length>0&&!!Pn,Bs=Zr&&!mi?Ts:Qr&&os(oi),Ms=eo&&os(ii),Fs=to&&li!=="load_error",yi=s=>s==="loading"||s==="ready",fi=Zr||Qr&&yi(oi)||eo&&yi(ii)||to&&li!=="load_error",To=(0,a.useRef)(!1);(0,a.useEffect)(()=>{if(!To.current){if(!$&&!ge){To.current=!0;let s=new p.FloPayError("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");u?.(s),be(s.message)}else if(!$&&ge&&!Vn&&!Tr){To.current=!0;let s=new p.FloPayError("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");u?.(s),be(s.message)}else if(xo!==void 0&&!se&&!gn&&!fi){To.current=!0;let s=new p.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"});u?.(s),be(s.message)}}},[$,ge,Vn,Tr,xo,se,gn,fi,u,be]);let gi=(0,a.useRef)(!1);(0,a.useEffect)(()=>{if(gi.current||!Io)return;let s=[];j!==!0&&s.push("showApplePay"),pe!==!0&&s.push("showGooglePay"),s.length!==0&&(gi.current=!0,console.warn(`[FloPay] ${s.join(" / ")} ${s.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.`))},[Io,j,pe]);let hi=(0,a.useCallback)((s,_)=>Ge.applyInlineSessionPatch?Ge.applyInlineSessionPatch(s).then(K=>({error:null,sessionId:K.sessionId||e,nonce:K.session?.clientSecret||t})).catch(K=>{let De=rs(_,K);return be(De.message),u?.(De),{error:De,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[Ge.applyInlineSessionPatch,t,u,e,be]),Dn=(0,a.useCallback)(async s=>{if(!O)return{proceed:!0};try{let _=await O({method:s,sessionId:e||void 0,createSession:Ge.inlineSessionDraft});if(_===!1)return{proceed:!1};if(_&&typeof _=="object"){_.account&&cr(De=>({...De??{},..._.account}));let K=await hi(_,s);return K.error?{proceed:!1,accountPatch:_.account}:{proceed:!0,accountPatch:_.account,sessionId:K.sessionId,nonce:K.nonce}}return{proceed:!0}}catch(_){let K=rs(s,_);return be(K.message),u?.(K),{proceed:!1}}},[hi,Ge.inlineSessionDraft,O,u,e,be]),bi=(0,a.useCallback)(async(s,_)=>{if(d.current)return;d.current=!0,Tt(!0),y("processing"),be(null);let K=_?.sessionId??e,De=_?.nonce??t,G=Ra(ve,_?.accountPatch),Be=_?.completionPaymentMethodId??co(s),$e=s.originalPaymentMethodId?{...s,originalPaymentMethodId:void 0}:s,rt=s.gateway==="stripe"?"stripe":s.gateway==="paypal"||s.isPaypal?"paypal":void 0,Ut=()=>{gt?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"process_payment",provider:rt})};try{let pt=await new sr.PaymentAPI(dt).processPayment(G.userId??"",{sessionId:K,nonce:De,tokenizedData:$e,accountData:{userId:G.userId??"",email:G.email??"",...G.firstName?{firstName:G.firstName}:{},...G.lastName?{lastName:G.lastName}:{},...ue?(()=>{let We=Vt.current,Gt=(0,p.isAVSFieldVisible)(ue.state,We),wn=(0,p.isAVSFieldVisible)(ue.address_line_1,We),qt=(0,p.isAVSFieldVisible)(ue.postal_code,We),io=wn&&!Gt&&qt?(0,p.getStateFromPostalCode)(We,(Nt.current??"").trim()):null,so=Gt?Bt.current:io;return{country:We,...qt&&Nt.current?{zip:Nt.current}:{},...(0,p.isAVSFieldVisible)(ue.city,We)&&mn.current?{city:mn.current}:{},...so?{state:so}:{},...wn&&pn.current?{addressLine1:pn.current}:{},...(0,p.isAVSFieldVisible)(ue.address_line_2,We)&&rn.current?{addressLine2:rn.current}:{}}})():{}},chv:v,avsCheck:Le??!1,checkoutType:ae,checkoutLayout:Z,avsConfig:ue?{country:(0,p.isAVSFieldVisible)(ue.country,Vt.current),postal_code:(0,p.isAVSFieldVisible)(ue.postal_code,Vt.current),address_line_1:(0,p.isAVSFieldVisible)(ue.address_line_1,Vt.current),address_line_2:(0,p.isAVSFieldVisible)(ue.address_line_2,Vt.current),city:(0,p.isAVSFieldVisible)(ue.city,Vt.current),state:(0,p.isAVSFieldVisible)(ue.state,Vt.current)}:void 0});if(pt.ok){let We=pt.status===204?null:await pt.json().catch(()=>null),Gt=(0,p.isAuthorizationOnlySession)(L)||We?.status==="authorized";Vr(K),y("success"),me(null),await new Promise(wn=>setTimeout(wn,1200)),i?.(Gt?{status:"authorized",...typeof We?.paymentId=="string"?{paymentId:We.paymentId}:L?.paymentId?{paymentId:L.paymentId}:{},sessionId:typeof We?.sessionId=="string"?We.sessionId:K,...typeof We?.authorizationExpiresAt=="string"?{authorizationExpiresAt:We.authorizationExpiresAt}:L?.authorizationExpiresAt?{authorizationExpiresAt:L.authorizationExpiresAt}:{},paymentIntentId:s.threeDSecureActionResultTokenId,paymentMethodId:Be,checkoutMethod:s.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:s.threeDSecureActionResultTokenId,paymentMethodId:Be,checkoutMethod:s.isPaypal?"paypal":"card"});return}let Ze=await pt.json().catch(()=>null);if(Ze?.type==="paypal_redirect_required"){let We=Ze.threeDSecureToken,Gt=Ze.paymentMethodId||s.id||"";if(!ce||!We){y("error"),be("PayPal authorization required but no token provided.");return}try{let wn=tt?.getRawProvider();if(!wn){be("PayPal is not available.");return}let qt={return_url:window.location.href};Gt&&(qt.payment_method=Gt);let{error:io}=await wn.confirmPayment({clientSecret:We,confirmParams:qt,redirect:"if_required"});if(io){y("error");let so=io.message??"PayPal payment failed.";be(so),Fn("paypal",so,{code:io.code})}}catch(wn){y("error"),be(wn instanceof Error?wn.message:"PayPal authorization failed.")}return}if(Ze?.type==="paypal_direct_required"){let We=Ze.orderId;if(!We){y("error"),be("PayPal retry required but no order id provided.");return}let Gt=Xe.current?.attempts??0;if(Gt>=2){y("error"),be("PayPal payment could not be completed after multiple attempts."),Fn("paypal","paypal_direct_required retry limit exceeded");return}fa(!1),ga("loading"),me({orderId:We,attempts:Gt+1}),y(null);return}(0,p.classifyPaymentRejection)(pt.status,Ze)||Ut(),y("error");let Wt=Ze?.message??"Payment failed. Please try again.";be(Wt),Fn(s.isPaypal?"paypal":"card",Wt,{code:Ze?.code??Ze?.gatewayErrorCode,declineCode:Ze?.declineCode??Ze?.gatewayDeclineReason}),await new Promise(We=>setTimeout(We,1500))}catch(ut){ls(ut)||Ut(),y("error"),be(ut instanceof Error?ut.message:"An unexpected error occurred"),await new Promise(pt=>setTimeout(pt,1500))}finally{Tt(!1),y(null),d.current=!1}},[dt,e,t,ve,sn,v,ce,tt,L,i,u,be,Fn,gt]),Cn=(0,a.useCallback)((s,_)=>{P?P(s):bi(s,_)},[P,bi]),vi=(0,a.useRef)(!1);(0,a.useEffect)(()=>{if(typeof window>"u"||vi.current)return;let s=new URLSearchParams(window.location.search),_=s.get("payment_intent"),K=s.get("payment_intent_client_secret"),De=s.get("redirect_status");if(!_||!K)return;let G=pt=>{let Ze=localStorage.getItem(pt);if(!Ze)return null;try{return JSON.parse(Ze)}catch{return localStorage.removeItem(pt),null}},Be=G(Kn)??G(es),$e;if(Be?.clientSecret){if(Be.clientSecret!==K)return;$e={...Be.accountPatch?{accountPatch:Be.accountPatch}:{},...Be.sessionId?{sessionId:Be.sessionId}:{},...Be.nonce?{nonce:Be.nonce}:{}}}else if(Be?.sessionId&&Be.sessionId!==e)return;vi.current=!0,localStorage.removeItem(Kn),localStorage.removeItem(es);let rt=new URL(window.location.href);rt.searchParams.delete("payment_intent"),rt.searchParams.delete("payment_intent_client_secret"),rt.searchParams.delete("redirect_status"),window.history.replaceState({},"",rt.toString());let Ut=Be?.paymentMethodType??Be?.tokenType??"card",ut="card";(async()=>{let pt=ce?.getRawProvider();if(!pt){let qt="Payment is not available \u2014 please refresh and try again.";be(qt),Fn(ut,qt);return}if(De==="failed"){let qt="Payment was declined. Please try again.";be(qt),Fn(ut,qt);return}let{paymentIntent:Ze,error:Wt}=await pt.retrievePaymentIntent(K);if(Wt){let qt=Wt.message??"Failed to retrieve payment status.";be(qt),Fn(ut,qt,{code:Wt.code});return}let We=Ze?.status,Gt=zo(We);if(!Ze||!Gt){let qt=We==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";be(qt),Fn(ut,qt,{code:We??"missing_payment_intent"});return}let wn=typeof Ze.payment_method=="string"?Ze.payment_method:Ze.payment_method?.id;Cn({id:wn??Be?.paymentMethodId??Be?.tokenId??Ze.id,type:"card",threeDSecureActionResultTokenId:Ze.id,gateway:Be?.gateway??"stripe",paymentMethodType:Ut},$e)})()},[e,Cn,ce,be,Fn]);let ha=(0,a.useCallback)(s=>{s.preventDefault()},[]);if(!(ce!==null))return(0,l.jsx)("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let no=J==="buttons",tn=ee?.variables,Ds=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),ba=tn?.colorBackground,Ls=ba&&!Ds.has(ba)?ba:void 0,ro=F.cardInputBorder??(no?"#e5e7eb":"#A4A4FF"),Pi=tn?.colorDanger??"#dc2626",Ct=s=>pr[s]&&(bt[s]||Xn),Ao=xr&&($n||Xn),Sn=s=>s?Pi:ro,Bo=(Yt.malformed||Yt.empty)&&(hn||Xn),Ns=Sn(Bo),va=F.cardFormContainer?.backgroundColor??Ls??(no?"white":"#EDEDFF"),Br=F.cardInputBackground??tn?.colorBackground??"white",Pa=Fr(Ie),Ci=Fr(Re),Mr=F.nameInput,Si=F.cardInputFontSize??Tl(Mr?.fontSize)??tn?.fontSizeBase??"16px",wi=typeof Mr?.fontFamily=="string"?Mr.fontFamily:tn?.fontFamily??"Poppins, sans-serif",ki=Ma(Mr?.fontWeight)??400,Os=F.cardInputColor??(typeof Mr?.color=="string"?Mr.color:void 0)??tn?.colorText??"#262833",zs=F.cardInputPlaceholderColor??"#9ca3af",kt=tn?.borderRadius??"8px",Pr=tn?.borderRadius??F.cardButton?.borderRadius??kt,Cr=tn?.colorPrimary??"#4A49FF",Us=tn?.colorPrimaryHover??Wr(Cr,.12),Ca=tn?.colorText??"#262833",Sa={fontSize:Si,fontFamily:wi,fontWeight:ki,color:Os,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},oo={marginTop:"0.375rem",...Sa,fontSize:"0.75rem",lineHeight:1.4,color:Pi},qs={"--flopay-input-placeholder-color":zs,"--flopay-input-font-size":Si,"--flopay-input-font-family":wi,"--flopay-input-font-weight":String(ki)},ao=F.cardFormContainer??{},wa=ao.padding??(no?"0":"1rem"),ka=ao.borderRadius??kt,$s=ct&&bn?(0,l.jsx)(Yr,{capture:ct,html:bn.html,messageToken:bn.messageToken,expectedOrigin:bn.expectedOrigin,theme:Ve,onReady:()=>{if(!yr&&!ue||typeof document>"u")return;let s=()=>{let K=(document.querySelector('[data-testid="flopay-vault-identity-fields"]')??document.querySelector('[data-testid="flopay-avs-fields"]'))?.querySelector("input:not([disabled]), select:not([disabled])");if(K){on.current=!0;try{K.focus()}finally{on.current=!1}}};en.current||s()},onError:s=>be(s),onValidation:s=>{let _=T.current;(_==="idle"||_==="validation-window")&&(be(s),s&&T.current==="validation-window"&&(m.current&&(clearTimeout(m.current),m.current=null),T.current="idle",y(null)))}}):(0,l.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"}),Ii=(0,l.jsxs)("div",{onFocusCapture:s=>{["INPUT","SELECT","TEXTAREA","IFRAME"].includes(s.target.tagName)&&an()},style:{backgroundColor:va,borderRadius:ka,...ao,padding:wa,...qs,display:"flex",flexDirection:"column"},children:[(0,l.jsx)("style",{children:`
30
+ `,ta=44,_r=280;function Ua(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 kl={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"},us={width:"100%",minHeight:ta,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 Il(e){switch(e){case"paypal":return"PayPal";case"apple_pay":return"Apple Pay";case"google_pay":return"Google Pay";default:return"Card"}}function rs(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function Na(e){return e==="paypal"?"PayPal":(0,u.getStripeMethodDisplayName)(e)}function Rl(e,t){let n=`We couldn't open ${Na(e)}. Try again or choose another payment method.`;return t?`${n} Allow pop-ups for this site, then try again.`:n}function ps(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 P=p;P?.timer&&(clearTimeout(P.timer),P.timer=null)},[]),i=(0,a.useCallback)((p,P)=>{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"}))},P))},[o,e]),d=(0,a.useCallback)(p=>{p.yieldedControl&&i(p,600)},[i]),c=(0,a.useCallback)(p=>{o();let P=t.current+1;t.current=P,n.current=null;let he={generation:P,method:p,timer:null,yieldedControl:!1};return r.current=he,P},[o]),v=(0,a.useCallback)(p=>{let P=r.current;return typeof p=="number"&&P?.generation!==p?!1:(o(P),r.current=null,(typeof p!="number"||n.current===p)&&(n.current=null),!0)},[o]),y=(0,a.useCallback)(p=>{let P=r.current,he=p??P?.generation??t.current;(!p||P?.generation===p)&&(o(P),r.current=null),n.current=he},[o]),g=(0,a.useCallback)(p=>n.current===(p??t.current),[]),b=(0,a.useCallback)(p=>r.current?.generation===p&&n.current!==p,[]),B=(0,a.useCallback)(()=>{let p=r.current;p&&d(p)},[d]),T=(0,a.useCallback)(()=>{let p=r.current;p&&(p.yieldedControl=!0,o(p))},[o]);return(0,a.useEffect)(()=>{let p=()=>{document.visibilityState==="visible"?B():T()},P=()=>{T()};return document.addEventListener("visibilitychange",p),window.addEventListener("blur",P),window.addEventListener("focus",B),()=>{document.removeEventListener("visibilitychange",p),window.removeEventListener("blur",P),window.removeEventListener("focus",B),o()}},[o,T,B]),{startAttempt:c,finishAttempt:v,invalidateAttempt:y,isAttemptInvalidated:g,isAttemptCurrent:b}}function El(e){let t=(0,u.getPostalCodeExample)(e);return`Enter a valid ${(0,u.getPostalCodeLabel)(e)}${t?` (e.g. ${t})`:""}`}function _l(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 xl(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 os(e,t){return t instanceof u.FloPayError?t:new u.FloPayError(t instanceof Error?t.message:`${Il(e)} before-click hook failed.`,"validation_error")}function La(){return(0,l.jsx)("style",{children:wl})}function Tl(e){return typeof e=="number"?`${e}px`:e}function ms(e,t){let n=e.availablePaymentMethods;return n&&t.some(r=>n[r])?"ready":"unavailable"}function ys({state:e,placeholderTestId:t,borderRadius:n=8,children:r}){return e==="unavailable"||e==="load_error"?null:(0,l.jsxs)("div",{style:{position:"relative",minHeight:44},children:[(0,l.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,l.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 as(e){return e!=="unavailable"&&e!=="load_error"}function oa(e){return(0,l.jsx)(Al,{...e})}function is({sessionId:e,nonce:t,email:n,billingApiUrl:r,onTokenizedBody:o,onErrorChange:i,isProcessing:d=!1,onButtonClick:c,onDecline:v,onTechnicalFailure:y,runBeforeButtonClick:g,billingName:b,onBuyerIdentityReady:B,onLoadStateChange:T,placeholderBorderRadius:p}){let P=ir(),{emitInstrument:he}=(0,a.useContext)(An),q=(0,Tt.useStripe)(),S=(0,Tt.useElements)(),[ue,$]=(0,a.useState)("loading");(0,a.useEffect)(()=>{T?.(ue)},[ue,T]);let[ce,W]=(0,a.useState)(!1),be=!(0,u.isValidEmail)(n?.trim())||!b?.trim(),{request:He,collect:we,finish:vt}=qr(),$e=(0,a.useRef)(!1),xe=(0,a.useRef)(null),Te=(0,a.useRef)(null),[ne,re]=(0,a.useState)(0),[L,Me]=(0,a.useState)(!1),Ae=(0,a.useRef)(!1),X=(0,a.useRef)(new Map),{startAttempt:Ie,finishAttempt:Se,invalidateAttempt:x,isAttemptInvalidated:U,isAttemptCurrent:Be}=ps((te,G,H)=>{y?.(te,G,{...H,popupBlocked:H?.popupBlocked??br(G)}),Me(!0),re(Fe=>Fe+1)});(0,a.useEffect)(()=>{L&&Te.current?.focus()},[L,ne]);let me=(0,a.useCallback)(()=>{re(te=>te+1)},[]),ee=(0,a.useCallback)((te,G,H)=>{x(H),y?.("paypal",te,{code:G,popupBlocked:br(te)}),Me(!0),me()},[x,y,me]),Le=(0,a.useCallback)(()=>{window.setTimeout(()=>{(xe.current?.querySelector("iframe")??xe.current)?.focus()},0)},[]);(0,a.useEffect)(()=>{Ae.current&&(Ae.current=!1,Le())},[Le,ne]);let rt=(0,a.useCallback)(()=>{Me(!1),i?.(null),Le()},[Le,i]);(0,a.useEffect)(()=>{if(!q||$e.current)return;let te=new URLSearchParams(window.location.search),G=te.get("payment_intent"),H=te.get("payment_intent_client_secret"),Fe=te.get("redirect_status");if(!G||!H)return;$e.current=!0;let Xe;try{let oe=localStorage.getItem(So);if(oe){let D=JSON.parse(oe);D.clientSecret===H&&(Xe={...D.accountPatch?{accountPatch:D.accountPatch}:{},...D.sessionId?{sessionId:D.sessionId}:{},...D.nonce?{nonce:D.nonce}:{}})}}catch{}try{localStorage.removeItem(So)}catch{}let M=new URL(window.location.href);M.searchParams.delete("payment_intent"),M.searchParams.delete("payment_intent_client_secret"),M.searchParams.delete("redirect_status"),window.history.replaceState({},"",M.toString()),(async()=>{try{if(W(!0),Fe==="failed"){let I="PayPal payment was declined. Please try again.";i?.(I),v?.(Ut("paypal",I));return}let{paymentIntent:oe,error:D}=await q.retrievePaymentIntent(H);if(D){i?.(D.message??"Failed to retrieve PayPal payment status.");return}if(oe&&(oe.status==="requires_capture"||oe.status==="succeeded")){let I=typeof oe.payment_method=="string"?oe.payment_method:oe.payment_method?.id;o({id:I??oe.id,type:"card",threeDSecureActionResultTokenId:oe.id,isPaypal:!0},Xe)}else{let I="PayPal payment was not completed. Please try again.";i?.(I),v?.(Ut("paypal",I))}}catch(oe){i?.(oe instanceof Error?oe.message:"Failed to complete PayPal payment.")}finally{W(!1)}})()},[q,o,i,v]);let pt=(0,a.useCallback)(async te=>{if(d||ce){te.reject();return}let G=g?await g("paypal"):{proceed:!0};if(!G.proceed){X.current.delete(ne),te.reject();return}let H=Ie("paypal");X.current.set(ne,{generation:H,accountPatch:G.accountPatch,sessionId:G.sessionId,nonce:G.nonce}),Me(!1),c?.("paypal"),te.resolve()},[d,c,g,Ie,ce,ne]),qe=(0,a.useCallback)(async te=>{if(!q||!S)return;let G=X.current.get(ne);if(G&&!Be(G.generation)){X.current.delete(ne);return}if(!G&&U()||G&&!Se(G.generation))return;G||Se();let H=G??null;if(X.current.delete(ne),!H&&g){let I=await g("paypal");if(!I.proceed){te.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}H={accountPatch:I.accountPatch,sessionId:I.sessionId,nonce:I.nonce}}let Fe=H?.sessionId??e,Xe=H?.nonce??t,M=await ds({event:te,prepared:H,email:n,billingName:b,methodLabel:"PayPal",collect:we});if(!M){te.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let oe=M.email,D=an({...H?.accountPatch,...M});try{if(W(!0),i?.(null),!Fe||!(0,u.isValidEmail)(oe))throw new Error("Missing sessionId or email for PayPal payment");await B?.(M);let I=q.createPaymentMethod,{error:lt,paymentMethod:Pt}=await I({type:"paypal"});if(lt){ee(lt,"stripe_paypal_create_payment_method_failed",G?.generation),te.paymentFailed({reason:"fail"});return}let ie=await na(r,he,Fe,Xe??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:Pt?.id??null,intentKind:"payment"});if(ie.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let ct=ie.clientSecret,et={return_url:window.location.href};if(Pt?.id&&(et.payment_method=Pt.id),typeof window<"u")try{localStorage.setItem(So,JSON.stringify({clientSecret:ct,sessionId:Fe,nonce:Xe,accountPatch:D}))}catch{}let{error:Ct,paymentIntent:kt}=await q.confirmPayment({clientSecret:ct,confirmParams:et,redirect:"if_required"});if(Ct){if(typeof window<"u")try{localStorage.removeItem(So)}catch{}if(mo(Ct)){let Z=Ct.message??"Your payment was declined.";i?.(Z),v?.(Ut("paypal",Z,{code:ar(Ct),declineCode:jr(Ct)})),await ra({billingApiUrl:r,sessionId:Fe,nonce:Xe,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:ar(Ct)??"provider_declined"}})}else ee(Ct,"stripe_paypal_confirm_failed",G?.generation);return}if(typeof window<"u")try{localStorage.removeItem(So)}catch{}let C=typeof kt?.payment_method=="string"?kt.payment_method:kt?.payment_method?.id;o({id:C??kt?.id,type:"card",threeDSecureActionResultTokenId:kt?.id,isPaypal:!0},{accountPatch:D,sessionId:Fe,nonce:Xe});return}catch(I){ee(I,"stripe_paypal_failed",G?.generation)}finally{W(!1)}},[q,S,e,t,n,b,we,B,r,he,o,i,v,g,ee,Se,Be,U,ne]);return(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(ys,{state:ue,placeholderTestId:"flopay-paypal-placeholder",borderRadius:p,children:(0,l.jsxs)("div",{ref:xe,tabIndex:-1,"data-testid":"flopay-paypal-focus-target",role:"group","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[L&&(0,l.jsx)("button",{ref:Te,type:"button","data-testid":"flopay-paypal-retry-button",onClick:rt,style:us,children:"Try PayPal again"}),He&&(0,l.jsx)($r,{identity:He.identity,methodLabel:He.methodLabel,onComplete:vt,onCancel:()=>vt(null)},He.id),(0,l.jsx)("div",{style:{display:He?"none":void 0},children:(0,l.jsx)(Tt.ExpressCheckoutElement,{onReady:te=>$(ms(te,["paypal"])),onLoadError:()=>{$("load_error"),za(qt(P),"paypal","paypal")},onClick:pt,onConfirm:qe,onCancel:()=>{let te=X.current.get(ne);X.current.delete(ne),qt(P)?.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),x(te?.generation),Me(!1),Ae.current=!0,me()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:be,emailRequired:be,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},ne)})]})}),ce&&(0,l.jsx)(Fn,{status:"processing"})]})}function ss({sessionId:e,nonce:t,email:n,billingApiUrl:r,intentKind:o,expressMethods:i,onTokenizedBody:d,onErrorChange:c,onButtonClick:v,onDecline:y,onTechnicalFailure:g,runBeforeButtonClick:b,billingName:B,onBuyerIdentityReady:T,onLoadStateChange:p,placeholderBorderRadius:P}){let he=ir(),{emitInstrument:q}=(0,a.useContext)(An),S=(0,Tt.useStripe)(),ue=(0,Tt.useElements)(),[$,ce]=(0,a.useState)("loading");(0,a.useEffect)(()=>{p?.($)},[$,p]);let[W,be]=(0,a.useState)(!1),He=!(0,u.isValidEmail)(n?.trim())||!B?.trim(),{request:we,collect:vt,finish:$e}=qr(),xe=(0,a.useRef)(null),Te=(0,a.useRef)(null),[ne,re]=(0,a.useState)(0),[L,Me]=(0,a.useState)(!1),[Ae,X]=(0,a.useState)("google_pay"),Ie=(0,a.useRef)(!1),Se=(0,a.useRef)("google_pay"),x=(0,a.useRef)("google_pay"),U=(0,a.useRef)(new Map),{startAttempt:Be,finishAttempt:me,invalidateAttempt:ee,isAttemptInvalidated:Le,isAttemptCurrent:rt}=ps((M,oe,D)=>{g?.(M,oe,{...D,popupBlocked:D?.popupBlocked??br(oe)}),X(M),Me(!0),re(I=>I+1)});(0,a.useEffect)(()=>{L&&Te.current?.focus()},[L,ne]);let pt=(0,a.useCallback)(()=>{re(M=>M+1)},[]),qe=(0,a.useCallback)((M,oe,D,I)=>{ee(I),g?.(M,oe,{code:D,popupBlocked:br(oe)}),X(M),Me(!0),pt()},[ee,g,pt]),te=(0,a.useCallback)(()=>{window.setTimeout(()=>{(xe.current?.querySelector("iframe")??xe.current)?.focus()},0)},[]);(0,a.useEffect)(()=>{Ie.current&&(Ie.current=!1,te())},[te,ne]);let G=(0,a.useCallback)(()=>{Me(!1),c?.(null),te()},[te,c]),H=(0,a.useCallback)(async M=>{if(!S||!ue)return;let oe=U.current.get(ne);if(oe&&!rt(oe.generation)){U.current.delete(ne);return}if(!oe&&Le()||oe&&!me(oe.generation))return;oe||me();let D=M.expressPaymentType??oe?.method??Se.current,I=oe??null;U.current.delete(ne);let lt=rs(D);if(!I&&b){let C=await b(lt);if(!C.proceed){M.paymentFailed({reason:"fail",message:"Wallet checkout was cancelled."});return}I={accountPatch:C.accountPatch,sessionId:C.sessionId,nonce:C.nonce}}let Pt=lt,ie=I?.sessionId??e,ct=I?.nonce??t,et=await ds({event:M,prepared:I,email:n,billingName:B,methodLabel:Na(D),collect:vt});if(!et){M.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let Ct=et.email,kt=an({...I?.accountPatch,...et});try{if(be(!0),c?.(null),!(0,u.isValidEmail)(Ct))throw new Error("Missing sessionId or email for wallet payment");await T?.(et);let{error:C}=await ue.submit();if(C){qe(D,C,"stripe_wallet_submit_failed",oe?.generation);return}let{error:Z,paymentMethod:dt}=await S.createPaymentMethod({elements:ue});if(Z||!dt){qe(D,Z??new Error("Failed to create payment method."),"stripe_wallet_create_payment_method_failed",oe?.generation);return}if(!ie)throw new Error("Missing sessionId or email for wallet payment");let yt=await na(r,q,ie,ct??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:D??lt,paymentMethodId:dt.id,intentKind:o});if(yt.provider!=="stripe")throw new Error("Invalid provider returned for wallet intent");let ye=yt.clientSecret,{error:It,intentId:it}=(0,u.isSetupIntentClientSecret)(ye)?await S.confirmCardSetup(ye,{payment_method:dt.id}).then(Ye=>({error:Ye.error,intentId:Ye.setupIntent?.id})):await S.confirmCardPayment(ye,{payment_method:dt.id}).then(Ye=>({error:Ye.error,intentId:Ye.paymentIntent?.id}));if(It){if(mo(It)){let Ye=It.message??"Your payment was declined.";c?.(Ye),y?.(Ut(Pt,Ye,{code:ar(It),declineCode:jr(It)})),await ra({billingApiUrl:r,sessionId:ie,nonce:ct,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:D??lt,providerDeclineReason:ar(It)??"provider_declined"}})}else qe(D,It,"stripe_wallet_confirm_failed",oe?.generation);return}d({id:dt.id,type:"card",threeDSecureActionResultTokenId:it},{accountPatch:kt,sessionId:ie,nonce:ct})}catch(C){qe(D,C,"stripe_wallet_failed",oe?.generation)}finally{be(!1)}},[S,ue,e,t,n,B,vt,T,r,q,o,d,c,y,b,qe,me,rt,Le,ne]),Fe=(0,a.useMemo)(()=>{let M=["applePay","googlePay","paypal","link","amazonPay","klarna"],oe=new Set(["applePay","googlePay"]),D=new Set(i.map(u.stripeExpressMethodToOptionKey)),I={};for(let lt of M)D.has(lt)?I[lt]=oe.has(lt)?"always":"auto":I[lt]="never";return I},[i]),Xe=(0,a.useMemo)(()=>i.map(u.stripeExpressMethodToOptionKey),[i]);return(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(ys,{state:$,placeholderTestId:"flopay-wallet-placeholder",borderRadius:P,children:(0,l.jsxs)("div",{ref:xe,tabIndex:-1,"data-testid":"flopay-wallet-focus-target",role:"group","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[L&&(0,l.jsxs)("button",{ref:Te,type:"button","data-testid":"flopay-wallet-retry-button",onClick:G,style:us,children:["Try ",Na(Ae)," again"]}),we&&(0,l.jsx)($r,{identity:we.identity,methodLabel:we.methodLabel,onComplete:$e,onCancel:()=>$e(null)},we.id),(0,l.jsx)("div",{style:{display:we?"none":void 0},children:(0,l.jsx)(Tt.ExpressCheckoutElement,{onReady:M=>{ce(ms(M,Xe))},onLoadError:M=>{ce("load_error"),za(qt(he),"stripe","wallet")},onClick:async M=>{Se.current=M.expressPaymentType,x.current=rs(M.expressPaymentType);let oe=b?await b(x.current):{proceed:!0};if(!oe.proceed){U.current.delete(ne),M.reject();return}let D=Be(M.expressPaymentType);U.current.set(ne,{generation:D,method:M.expressPaymentType,accountPatch:oe.accountPatch,sessionId:oe.sessionId,nonce:oe.nonce}),Me(!1),v?.(x.current),M.resolve()},onConfirm:H,onCancel:()=>{let M=U.current.get(ne);U.current.delete(ne),qt(he)?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet"}),ee(M?.generation),Me(!1),Ie.current=!0,pt()},options:{buttonType:{applePay:"plain",googlePay:"plain"},paymentMethods:Fe,emailRequired:He,billingAddressRequired:He,layout:{maxColumns:1,overflow:"never"}}},ne)})]})}),W&&(0,l.jsx)(Fn,{status:"processing"})]})}function Ml({method:e,themeId:t,submitting:n=!1,disabled:r=!1,highlighted:o=!1,hasNextStep:i=!1,onClick:d,backgroundColor:c,borderColor:v,textColor:y,borderRadius:g,fontFamily:b}){let B=(0,u.resolveStripeMethodBrandVariant)(e,t),T=Qi[e],[p,P]=(0,a.useState)(!1),he=B?.backgroundColor??c??"#ffffff",q=B?.borderColor??v??"#d1d5db",S=B?.textColor??y??"#262833";return(0,l.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:ta,padding:"0 1rem",backgroundColor:he,color:S,border:`1px solid ${q}`,borderRadius:g??8,fontSize:"0.95rem",fontWeight:600,fontFamily:b,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,l.jsx)("span",{style:{margin:"0 auto"},children:`Connecting to ${(0,u.getStripeMethodDisplayName)(e)}\u2026`}):(0,l.jsxs)(l.Fragment,{children:[(0,l.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:(0,u.hasVendoredStripeMethodLogo)(e)?8:0},children:[T&&!p?(0,l.jsx)("img",{src:T,alt:"","aria-hidden":"true",onError:()=>P(!0),loading:"lazy",decoding:"async",width:30,height:20,style:{width:30,height:20,flexShrink:0,borderRadius:3,objectFit:"contain",display:"inline-flex"}}):B?.logoSvg?(0,l.jsx)("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:B.logoSvg}}):null,(0,l.jsx)("span",{children:(0,u.getStripeMethodDisplayName)(e)})]}),i&&(0,l.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,l.jsx)("path",{d:"M9 18l6-6-6-6"})})]})})}function Oa({method:e,sessionId:t,nonce:n,email:r,billingName:o,onBuyerIdentityReady:i,billingApiUrl:d,onTokenizedBody:c,onErrorChange:v,onDecline:y,onCancel:g,runBeforeButtonClick:b,onButtonClick:B,isProcessing:T,submitButtonColor:p,submitButtonBorderRadius:P,submitButtonStyle:he,errorText:q}){let S=ir(),{emitInstrument:ue}=(0,a.useContext)(An),$=(0,Tt.useStripe)(),ce=(0,Tt.useElements)(),[W,be]=(0,a.useState)(!1),He=(0,a.useRef)(!1),[we,vt]=(0,a.useState)(!1),[$e,xe]=(0,a.useState)("loading"),[Te,ne]=(0,a.useState)(""),re=!(0,u.isValidEmail)(r?.trim()),L=!re||(0,u.isValidEmail)(Te.trim()),Me=(0,a.useCallback)(async()=>{if(!$||!ce||T||He.current||!we)return;He.current=!0,be(!0);let Ae=b?await b("card"):{proceed:!0};if(!Ae.proceed){He.current=!1,be(!1);return}B?.("card");let X=Ae.sessionId??t,Ie=Ae.nonce??n,Se=kr(o?.trim()),x=an({email:Ae.accountPatch?.email?.trim()||r?.trim()||Te.trim(),firstName:Ae.accountPatch?.firstName?.trim()||Se.firstName,lastName:Ae.accountPatch?.lastName?.trim()||Se.lastName}),U=x.email,Be=an({...Ae.accountPatch,...x});try{if(v?.(null),!(0,u.isValidEmail)(U))throw new Error("A valid email address is required for payment.");await i?.(x);let me=await ce.submit();if(me.error){v?.(me.error.message??"Payment failed.");return}let ee=[x.firstName,x.lastName].filter(Boolean).join(" "),Le=await $.createPaymentMethod({elements:ce,params:{billing_details:{email:U,...ee?{name:ee}:{}}}});if(Le.error||!Le.paymentMethod){v?.(Le.error?.message??"Failed to create payment method.");return}let rt=Le.paymentMethod;if(!X||!U)throw new Error("Missing sessionId or email for payment.");let pt=rt.type||e,qe=await na(d,ue,X,Ie??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:pt,paymentMethodId:null,intentKind:"payment"});if(qe.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let te=qe.clientSecret;if(typeof window<"u")try{localStorage.setItem(Jn,JSON.stringify({clientSecret:te,sessionId:X,nonce:Ie,accountPatch:Be,paymentMethodId:rt.id,paymentMethodType:rt.type??e,gateway:"stripe"}))}catch{}let{error:G,paymentIntent:H}=await $.confirmPayment({clientSecret:te,confirmParams:{return_url:window.location.href,payment_method:rt.id},redirect:"if_required"});if(G){if(typeof window<"u")try{localStorage.removeItem(Jn)}catch{}let M=G.message??"Payment failed.";v?.(M),y?.(Ut("card",M,{code:G.code})),await ra({billingApiUrl:d,sessionId:X,nonce:Ie,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:G.code??"provider_declined"}});return}let Fe=H?.status;if(!jo(Fe)){if(typeof window<"u")try{localStorage.removeItem(Jn)}catch{}let M=Fe==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";v?.(M),y?.(Ut("card",M,{code:Fe??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(Jn)}catch{}let Xe=typeof H?.payment_method=="string"?H.payment_method:H?.payment_method?.id;c({id:Xe??rt.id,type:"card",threeDSecureActionResultTokenId:H?.id,gateway:"stripe",paymentMethodType:rt.type??e},{accountPatch:Be,sessionId:X,nonce:Ie})}catch(me){v?.(me instanceof Error?me.message:"Payment failed. Please try again.")}finally{He.current=!1,be(!1)}},[$,ce,T,we,b,B,t,n,r,o,Te,i,d,ue,e,c,v,y]);return(0,l.jsxs)("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[re&&(0,l.jsx)("div",{"data-testid":"flopay-apm-identity-fields",style:{display:"flex",flexDirection:"column",gap:"0.75rem",marginBottom:"0.75rem"},children:re&&(0,l.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",(0,l.jsx)("input",{type:"email",autoComplete:"email",required:!0,value:Te,onChange:Ae=>ne(Ae.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]})}),(0,l.jsx)(Tt.PaymentElement,{onReady:()=>xe("ready"),onLoadError:()=>{xe("load_error"),za(qt(S),"stripe","apm")},onChange:Ae=>{vt(!!Ae.complete)},options:{layout:{type:"accordion",defaultCollapsed:!1,radios:"never"},fields:{billingDetails:{email:"never"}},defaultValues:{billingDetails:{...o?.trim()?{name:o.trim()}:{},...(0,u.isValidEmail)(r?.trim())?{email:r?.trim()}:{}}}}}),(0,l.jsx)("button",{type:"button","data-testid":`flopay-stripe-method-pay-${e}`,onClick:()=>{Me()},disabled:!we||!L||W||T||$e!=="ready",style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:p,color:"white",border:"none",borderRadius:P,fontSize:"1rem",fontWeight:600,cursor:!we||!L||W||T||$e!=="ready"?"not-allowed":"pointer",opacity:!we||!L||W||T||$e!=="ready"?.5:1,transition:"opacity 120ms ease-out",...he??{}},children:W?"Processing\u2026":`Pay with ${(0,u.getStripeMethodDisplayName)(e)}`}),q&&(0,l.jsx)(Kr,{margin:"0.75rem 0 0",children:q})]})}function ls({sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:i,paymentElementMethods:d,stripeInstance:c,paymentElementBaseOptions:v,onTokenizedBody:y,onErrorChange:g,onButtonClick:b,onDecline:B,runBeforeButtonClick:T,onLoadStateChange:p,isProcessing:P=!1,submitButtonColor:he="#4A49FF",submitButtonBorderRadius:q=8,submitButtonStyle:S,buttonAppearance:ue,themeId:$,onExpandApm:ce,expandedApmMethod:W}){let{emitInstrument:be}=(0,a.useContext)(An),[He,we]=(0,a.useState)(null),[vt,$e]=(0,a.useState)(null),xe=(0,a.useRef)(!1),{request:Te,collect:ne,finish:re}=qr();(0,a.useEffect)(()=>{d.length>0&&c?p?.("ready"):c||p?.("loading")},[d.length,c,p]);let L=(0,a.useCallback)(async x=>{if(!c||xe.current||P)return;xe.current=!0,$e(x);let U=T?await T("card"):{proceed:!0};if(!U.proceed){xe.current=!1,$e(null);return}b?.("card");let Be=U.sessionId??e,me=U.nonce??t,ee=kr([U.accountPatch?.firstName,U.accountPatch?.lastName].filter(Boolean).join(" ")||r),Le=an({email:U.accountPatch?.email?.trim()||n?.trim(),firstName:U.accountPatch?.firstName?.trim()||ee.firstName,lastName:U.accountPatch?.lastName?.trim()||ee.lastName});if(!(0,u.isValidEmail)(Le.email)){$e(null);let qe=await ne((0,u.getStripeMethodDisplayName)(x),Le);if(!qe){xe.current=!1;return}Le=qe,$e(x)}let rt=Le.email,pt=an({...U.accountPatch,...Le});try{if(g?.(null),!Be||!(0,u.isValidEmail)(rt))throw new Error("Missing sessionId or email for payment.");await o?.(Le);let qe=await na(i,be,Be,me??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:x,paymentMethodId:null,intentKind:"payment"});if(qe.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let te=qe.clientSecret;if(typeof window<"u")try{localStorage.setItem(Jn,JSON.stringify({clientSecret:te,sessionId:Be,nonce:me,accountPatch:pt,paymentMethodType:x,gateway:"stripe"}))}catch{}let{error:G,paymentIntent:H}=await c.confirmPayment({clientSecret:te,confirmParams:{return_url:window.location.href,payment_method_data:{type:x,billing_details:{name:[Le.firstName,Le.lastName].filter(Boolean).join(" "),...rt?{email:rt}:{}}}},redirect:"if_required"});if(G){if(typeof window<"u")try{localStorage.removeItem(Jn)}catch{}let M=G.message??"Payment failed.";g?.(M),B?.(Ut("card",M,{code:G.code})),await ra({billingApiUrl:i,sessionId:Be,nonce:me,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:x,providerDeclineReason:G.code??"provider_declined"}});return}let Fe=H?.status;if(!jo(Fe)){if(typeof window<"u")try{localStorage.removeItem(Jn)}catch{}let M=Fe==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";g?.(M),B?.(Ut("card",M,{code:Fe??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(Jn)}catch{}let Xe=typeof H?.payment_method=="string"?H.payment_method:H?.payment_method?.id;y({id:Xe??H?.id,type:"card",threeDSecureActionResultTokenId:H?.id,gateway:"stripe",paymentMethodType:x},{accountPatch:pt,sessionId:Be,nonce:me})}catch(qe){g?.(qe instanceof Error?qe.message:"Payment failed. Please try again.")}finally{xe.current=!1,$e(null)}},[c,P,T,b,e,t,n,ne,i,be,r,o,y,g,B]),[Me,Ae]=(0,a.useState)(null),X=ce?W??null:Me,Ie=(0,a.useCallback)(x=>{xe.current||P||X&&X!==x||((0,u.needsStripeMethodExplicitConfirm)(x)?ce?ce(x):Ae(x):L(x))},[X,P,L,ce]),Se=(0,a.useMemo)(()=>Me?{...v,paymentMethodTypes:[Me]}:null,[Me,v]);return(0,l.jsx)("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:Te?(0,l.jsx)($r,{identity:Te.identity,methodLabel:Te.methodLabel,onComplete:re,onCancel:()=>re(null)},Te.id):d.map(x=>{let U=W===x,Be=vt===x,me=vt!==null&&vt!==x||W!=null&&W!==x;return(0,l.jsxs)(a.default.Fragment,{children:[(0,l.jsx)(Ml,{method:x,themeId:$,submitting:Be,disabled:me,highlighted:U,hasNextStep:(0,u.needsStripeMethodExplicitConfirm)(x),onClick:()=>Ie(x),backgroundColor:ue?.backgroundColor,borderColor:ue?.borderColor,textColor:ue?.textColor,borderRadius:ue?.borderRadius,fontFamily:ue?.fontFamily}),!ce&&Me===x&&Se&&c&&(0,l.jsx)(Tt.Elements,{stripe:c,options:Se,children:(0,l.jsx)(Oa,{method:x,sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:i,onTokenizedBody:y,onErrorChange:g,onDecline:B,onCancel:()=>Ae(null),runBeforeButtonClick:T,onButtonClick:b,isProcessing:P,submitButtonColor:he,submitButtonBorderRadius:q,submitButtonStyle:S})},x)]},x)})})}function Al({sessionId:e,nonce:t,billingApiUrl:n,email:r,userId:o,onComplete:i,onError:d,onDecline:c,onTokenizedBody:v,firstName:y,lastName:g,chv:b,className:B,isProcessing:T,error:p,onErrorChange:P,showPayPal:he=!0,showStripe:q=!0,enabledPaymentMethods:S,enabledPaymentMethodCountries:ue,showApplePay:$=!0,showGooglePay:ce=!0,layout:W="default",theme:be,buttonsTheme:He,buttonsStyles:we,appearance:vt,cardButtonContent:$e,cardBackButtonContent:xe,cardTitleContent:Te,showSecurityFooter:ne,onButtonClick:re,onBeforeButtonClick:L,onBuyerIdentityReady:Me,enableAVS:Ae,cardFieldOrder:X,cardPreFormSlot:Ie,avsLayout:Se="row",country:x,zip:U,addressLine1:Be,addressLine2:me,city:ee,state:Le,onCountryChange:rt,onZipChange:pt,avsCheck:qe,checkoutType:te,checkoutLayout:G,totalAmount:H=0,currency:Fe="usd",initialCardOpen:Xe=!1,directPaypal:M,isSubscription:oe=!1,session:D,dataAttachmentPending:I=!1,dataAttachmentRequiresIdentity:lt=!1,debug:Pt=!1}){let ie=ir(),ct=Vo(),et=(0,a.useContext)($n),{emitInstrument:Ct}=(0,a.useContext)(An),kt=I||et.claimPending===!0,C=lt||et.claimRequiresIdentity===!0,Z=kt&&!C,dt=Ui(),[yt,ye]=(0,a.useState)(!1),[It,it]=(0,a.useState)(null),[Ye,Nt]=(0,a.useState)(x??"US"),[$t,Yt]=(0,a.useState)(U??""),[Ln,tn]=(0,a.useState)(Be??""),[Kn,sn]=(0,a.useState)(me??""),[Cn,nn]=(0,a.useState)(ee??""),[Ot,Sn]=(0,a.useState)(Le??""),[tt,ur]=(0,a.useState)(""),[ot,Nn]=(0,a.useState)({}),ft=(0,a.useRef)(U??""),jt=(0,a.useRef)(x??"US"),ln=(0,a.useRef)(Be??""),wn=(0,a.useRef)(me??""),kn=(0,a.useRef)(ee??""),Jt=(0,a.useRef)(Le??""),Qn=(0,a.useRef)(""),Mt=(0,a.useRef)({});(0,a.useEffect)(()=>{let s=(_,K,Ue,Y,De)=>{if(Mt.current[_])return;let Ge=K?.trim();!Ge||Ge===Ue.current||(Ue.current=Ge,Y(Ge),De?.(Ge))};s("country",x,jt,Nt,rt),s("zip",U,ft,Yt,pt),s("addressLine1",Be,ln,tn),s("addressLine2",me,wn,sn),s("city",ee,kn,nn),s("state",Le,Jt,Sn)},[x,U,Be,me,ee,Le,rt,pt]);let le=(0,a.useMemo)(()=>(0,u.resolveAVSConfig)(Ae),[Ae]),er=le!==null,cn=(0,a.useMemo)(()=>(0,u.isAuthorizationOnlySession)(D),[D]),dn=!!D?.vault?.html,pr=!!D?.gateways?.pcivault,tr=!!(D?.gateways?.stripe?.enabledPaymentMethods??S)?.includes("card"),Xt=dn||tr||pr,Je=!!(q&&Xt&&ie&&e),[In,A]=(0,a.useState)(()=>W!=="buttons"||Xe?e??null:null),[Dt,Rt]=(0,a.useState)(0),Et=W!=="buttons"||Xe||!!e&&In===e,fe=(0,a.useMemo)(()=>!ie||!Je||!e||!Et?null:ie.cardCapture({sessionId:e,captureMethod:D?.captureMethod}),[ie,Je,e,Et,D?.captureMethod]),Wt=(0,a.useMemo)(()=>{let s=Ye,_=le?(0,u.isAVSFieldVisible)(le.postal_code,s):!1;return _l(s,$t,_)},[le,Ye,$t]),{avsInvalid:mr,invalidAvsFields:yr}=(0,a.useMemo)(()=>{let s={line1:!1,city:!1,state:!1,zip:!1};if(!Je||!le)return{avsInvalid:!1,invalidAvsFields:s};let _=Ye,K=(De,Ge)=>(0,u.isAVSFieldVisible)(De,_)&&!Ge.trim(),Ue={line1:K(le.address_line_1,Ln),city:K(le.city,Cn),state:K(le.state,Ot),zip:Wt.empty||Wt.malformed};return{avsInvalid:Ue.line1||Ue.city||Ue.state||Ue.zip,invalidAvsFields:Ue}},[Je,le,Ye,Ln,Cn,Ot,Wt]),[nr,Pr]=(0,a.useState)(!1),[Rn,Cr]=(0,a.useState)(!1),[Yn,un]=(0,a.useState)(!1),[At,rn]=(0,a.useState)({line1:!1,city:!1,state:!1}),Zt=(0,a.useRef)(!1),En=(0,a.useRef)({email:!1,line1:!1,city:!1,state:!1,zip:!1}),pn=(0,a.useRef)(!1),st=(0,a.useCallback)(s=>{En.current[s]=!0,pn.current=!0},[]),mn=(0,a.useCallback)(s=>!Zt.current&&En.current[s],[]),yn=(0,a.useCallback)(s=>{mn(s)&&rn(_=>_[s]?_:{..._,[s]:!0})},[mn]),[fn,gn]=(0,a.useState)(()=>Da(D?.vault)),[Ne,Gt]=(0,a.useState)(Xe&&Xt?"card":"buttons"),[Bt,fr]=(0,a.useState)(null),On=Ne==="expanding"||Ne==="card",gr=D?.gateways?.stripe?"stripe":void 0,zn=(0,a.useCallback)(()=>{Ct?.({class:"card_surface",provider:gr})},[gr,Ct]),hn=(0,a.useRef)(null),zt=(0,a.useCallback)(s=>{hn.current&&clearTimeout(hn.current),hn.current=setTimeout(()=>{hn.current=null,s()},_r)},[]);(0,a.useEffect)(()=>()=>{hn.current&&clearTimeout(hn.current)},[]);let Mr=(0,a.useCallback)(()=>{zn(),A(e??null),Rt(s=>s+1),Gt("expanding"),zt(()=>Gt("card"))},[zt,zn,e]),_n=(0,a.useCallback)(()=>{Gt("collapsing"),zt(()=>Gt("buttons"))},[zt]),O=(0,a.useCallback)(s=>{fr(s),Gt("apm-expanding"),zt(()=>Gt("apm-form"))},[zt]),z=(0,a.useCallback)(()=>{Gt("apm-collapsing"),zt(()=>{Gt("buttons"),fr(null)})},[zt]);(0,a.useEffect)(()=>{W==="buttons"&&Xe&&Xt&&(A(e??null),Gt("card"))},[W,Xe,Xt,e]);let[Q,F]=(0,a.useState)(null),je=(0,a.useRef)(!1),ae=(0,a.useRef)(null),N=(0,a.useRef)("idle"),[h,pe]=(0,a.useState)(null),de=(0,a.useRef)(h);(0,a.useEffect)(()=>{de.current=h},[h]);let Oe=n||dt,Ze=(0,a.useRef)(null),ze=(0,a.useMemo)(()=>{if(Me||et.claimBuyerIdentity||D?.buyerIdentified!==!1||!e||!t)return;let s=`${Oe}|${e}|${t}`;Ze.current?.key!==s&&(Ze.current={key:s,claim:zr(new cr.PaymentAPI(Oe,{telemetry:!1}),e,t,{...o?{userId:o}:{},...y?{firstName:y}:{},...g?{lastName:g}:{}})});let _=Ze.current.claim;return async K=>{await _(K)}},[Me,et.claimBuyerIdentity,D?.buyerIdentified,e,t,Oe,o,y,g]),Re=Me??et.claimBuyerIdentity??ze,R=p??It,f=(0,a.useMemo)(()=>(0,u.resolveTheme)(be),[be]),m=(0,a.useMemo)(()=>{let s=f?.buttonsLayout??(0,u.resolveButtonsLayoutTheme)(He);return we?{...s,...we,cardButton:{...s.cardButton,...we.cardButton},cardFormContainer:{...s.cardFormContainer,...we.cardFormContainer},backButton:{...s.backButton,...we.backButton},backButtonIcon:{...s.backButtonIcon,...we.backButtonIcon},submitButton:{...s.submitButton,...we.submitButton},title:{...s.title,...we.title}}:s},[f,He,we]),J=vt??f?.appearance,ke=(0,a.useMemo)(()=>ea({appearance:J,buttonsStyles:m,layout:W}),[J,m,W]),ge=et.inlineSessionPatchProcessing??!1,se=(T??yt)||ge,Ee=Oe.replace(/\/+$/,""),j=(0,a.useMemo)(()=>Ea({userId:o,email:r,firstName:y,lastName:g,country:x,zip:U},ot),[o,r,y,g,x,U,ot]),V=[j.firstName,j.lastName].filter(s=>!!s?.trim()).join(" "),ve=!(0,u.isValidEmail)(j.email?.trim()),_e=(0,a.useRef)(null);Je&&_e.current===null&&(_e.current=ve);let mt=Je&&(_e.current??ve),We=(0,a.useMemo)(()=>xl(tt,mt),[tt,mt]),Lt=We.empty||We.malformed,bn=(0,a.useMemo)(()=>ie?ie.getRawProvider():null,[ie]),Ar=(0,a.useMemo)(()=>ct?ct.getRawProvider():null,[ct]),Xr=H||100,Eo=(0,a.useMemo)(()=>J?(0,cr.toStripeAppearance)(J):null,[J]),_o=Eo?{appearance:Eo}:null,Za=(0,a.useMemo)(()=>{let s=Eo??{},_=s.rules??{};return{...s,rules:{..._,".AccordionItem":{padding:"10px 14px",boxShadow:"none",..._[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",..._[".AccordionItemContents"]??{}}}}},[Eo]),Qa=(0,a.useMemo)(()=>{let s=Li(H);return{...s,currency:Fe.toLowerCase(),paymentMethodCreation:"manual",...s.mode==="payment"?{captureMethod:"manual"}:{},..._o}},[H,Fe,_o]),ei=(0,a.useMemo)(()=>({mode:"payment",amount:Xr,currency:Fe.toLowerCase(),captureMethod:"manual",setupFutureUsage:"off_session",..._o}),[Xr,Fe,_o]),Pe=(0,a.useCallback)(s=>{it(s),P?.(s)},[P]),ua=(0,a.useRef)(""),[ti,Is]=(0,a.useState)(!1),pa=(0,a.useCallback)(()=>{Is(!0)},[]);(0,a.useEffect)(()=>{if(!Je||!mt||!Re||!ti||Lt||ua.current)return;let s=an({email:(0,u.isValidEmail)(j.email?.trim())?j.email?.trim():Qn.current.trim(),firstName:j.firstName?.trim(),lastName:j.lastName?.trim()});ua.current=JSON.stringify(s),Nn(_=>({..._,...s})),Promise.resolve(Re(s)).catch(_=>{ua.current="",Pe(_ instanceof Error?_.message:"Failed to attach buyer details.")})},[Je,mt,Re,ti,Lt,j.email,j.firstName,j.lastName,Pe]),(0,a.useEffect)(()=>{!Je||!fe||fe.setCardFieldOrder?.(X??null,le==null&&!mt)},[Je,fe,X,le,mt]),(0,a.useEffect)(()=>{(Ne==="expanding"||Ne==="collapsing"||Ne==="apm-expanding"||Ne==="apm-collapsing")&&Pe(null)},[Ne,Pe]);let Un=(0,a.useCallback)((s,_,K)=>{c?.(Ut(s,_,K))},[c]),Br=(0,a.useCallback)((s,_,K)=>{let Ue=K?.popupBlocked??br(_),Y=Rl(s,Ue),De=Rr(K?.code)??ar(_)??"external_payment_method_failed",Ge=new u.FloPayError(Y,"api_error",{code:"external_payment_method_failed",param:s});F(null),W==="buttons"&&(Gt("buttons"),fr(null)),Pe(Y),d?.(Ge),console.error("[FloPay] External payment method failed:",{method:s,code:De,popupBlocked:Ue})},[W,d,Pe]);(0,a.useEffect)(()=>{if(!Je||!e){gn(null);return}let s=Da(D?.vault);if(s){gn(s);return}if(!Et){gn(null);return}gn(null);let _=!0;return new cr.PaymentAPI(Ee).getVaultCapture(e,t).then(K=>{if(!_)return;let Ue=Da(K);Ue?gn(Ue):Pe("Failed to load the secure card form.")}).catch(K=>{_&&Pe(K instanceof Error?K.message:"Failed to load the secure card form.")}),()=>{_=!1}},[Je,Et,Dt,e,D?.vault,Ee,t,Pe]);let Wn=(0,a.useRef)({onComplete:i,onError:d,updateError:Pe,emitDecline:Un,resolvedAccount:j,avsConfig:le,avsCheckProp:qe,sessionId:e,nonce:t,baseUrl:Ee,captureMethod:D?.captureMethod,paymentId:D?.paymentId,authorizationExpiresAt:D?.authorizationExpiresAt});Wn.current={onComplete:i,onError:d,updateError:Pe,emitDecline:Un,resolvedAccount:j,avsConfig:le,avsCheckProp:qe,sessionId:e,nonce:t,baseUrl:Ee,captureMethod:D?.captureMethod,paymentId:D?.paymentId,authorizationExpiresAt:D?.authorizationExpiresAt};let ma=(0,a.useRef)(!1),ni=(0,a.useCallback)(()=>{let{resolvedAccount:s,avsConfig:_,avsCheckProp:K}=Wn.current,Ue=s.email?.trim(),Y=(0,u.isValidEmail)(Ue)?Ue:Qn.current.trim();if(!(0,u.isValidEmail)(Y))return null;let De=s.firstName?.trim(),Ge=s.lastName?.trim(),ut=jt.current||s.country||"US",Vt=_?(0,u.isAVSFieldVisible)(_.state,ut):!1,gt=_?(0,u.isAVSFieldVisible)(_.address_line_1,ut):!1,ht=_?(0,u.isAVSFieldVisible)(_.postal_code,ut):!1,nt=_?(0,u.isAVSFieldVisible)(_.city,ut):!1,Qt=_?(0,u.isAVSFieldVisible)(_.address_line_2,ut):!1,Qe=gt&&!Vt&&ht?(0,u.getStateFromPostalCode)(ut,(ft.current??"").trim()):null,en=Vt?Jt.current:Qe;return{accountData:{userId:s.userId??"",email:Y,...De?{firstName:De}:{},...Ge?{lastName:Ge}:{},...ht&&ft.current?{zip:ft.current}:{},...nt&&kn.current?{city:kn.current}:{},...en?{state:en}:{},...gt&&ln.current?{addressLine1:ln.current}:{},...Qt&&wn.current?{addressLine2:wn.current}:{},country:ut},...K!==void 0?{avsCheck:K}:{},..._?{avsConfig:{country:(0,u.isAVSFieldVisible)(_.country,ut),postal_code:ht,address_line_1:gt,address_line_2:Qt,city:nt,state:Vt}}:{}}},[]),ri=(0,a.useRef)(kt);ri.current=kt,(0,a.useEffect)(()=>{kt||R!==ns||Wn.current.updateError(null)},[kt,R]),(0,a.useEffect)(()=>{!Je||!fe||fe.setSubmitGate?.(mr||kt||Lt)},[Je,fe,mr,kt,Lt]),(0,a.useEffect)(()=>{if(!Je||!fe)return;ma.current=!1;let s=!1,_=fe.on("submitting",()=>{Pr(!0),ae.current&&clearTimeout(ae.current),N.current="validation-window",ae.current=setTimeout(()=>{ae.current=null,N.current==="validation-window"&&(N.current="processing")},Pl),F("processing");let{baseUrl:Ge,sessionId:ut,nonce:Vt,updateError:gt,onError:ht}=Wn.current;if(!ut||!Vt)return;let nt=ni();if(!nt){gt("Enter a valid email address."),N.current="idle",F(null);return}new cr.PaymentAPI(Ge).patchAccountSnapshot(ut,Vt,nt,{telemetryMode:"best_effort"}).catch(Qt=>{if(!Cl(Qt))return;let Qe=Qt instanceof Error?Qt.message:"Please check your billing address and try again.";gt(Qe),N.current="idle",F(null),ht?.(Qt instanceof u.FloPayError?Qt:new u.FloPayError(Qe,"api_error"))})}),K=fe.on("complete",async Ge=>{if(Hr(Ge.sessionId??Wn.current.sessionId),N.current="terminal",F("success"),await new Promise(gt=>setTimeout(gt,1200)),ma.current)return;ma.current=!0;let ut=Wn.current,Vt=(0,u.isAuthorizationOnlySession)(ut)||Ge.outcome==="authorized";Wn.current.onComplete?.(Vt?{status:"authorized",paymentIntentId:Ge.intentId,paymentId:Ge.paymentId??ut.paymentId,sessionId:Ge.sessionId??ut.sessionId,authorizationExpiresAt:Ge.authorizationExpiresAt??ut.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",paymentIntentId:Ge.intentId,checkoutMethod:"card"})}),Ue=fe.on("decline",async Ge=>{let{updateError:ut,emitDecline:Vt}=Wn.current,gt=Ge.message??"Your payment was declined. Please try another card or contact your bank.";N.current="terminal",ut(gt),F("error");let ht=Ge.failureOutcome??(0,u.normalizeCheckoutFailureOutcome)(Ge.declineReason)??"authorization_declined";Vt("card",gt,{code:ht,declineCode:ht}),await new Promise(nt=>setTimeout(nt,1500)),!s&&(N.current="idle",F(null))}),Y=fe.on("error",async Ge=>{let{updateError:ut,onError:Vt}=Wn.current,gt=Ge.message??"There was a problem processing your payment. Please try again.";N.current="terminal",ut(gt),F("error"),Vt?.(new u.FloPayError(gt,"api_error",{code:Ge.failureOutcome??"capture_failed"})),await new Promise(ht=>setTimeout(ht,1500)),!s&&(N.current="idle",F(null))}),De=fe.on("blocked",()=>{if(!ri.current){Pr(!0);return}pa(),Wn.current.updateError(ns)});return()=>{s=!0,ae.current&&(clearTimeout(ae.current),ae.current=null),N.current="idle",_(),K(),Ue(),Y(),De()}},[Je,fe,pa,ni]);let Gn=!!M?.clientId,Zr=Array.isArray(S),xo=Zr&&S.length>0,Rs=Zr&&S.includes("paypal"),{expressMethods:To,paymentElementMethods:Qr}=(0,a.useMemo)(()=>(0,u.partitionStripeMethods)(S,{excludePaypal:Gn}),[S,Gn]),oi=Gn||!!ct,Es=(0,a.useMemo)(()=>oi?To.filter(s=>s!=="paypal"):To,[To,oi]),_s=(0,a.useMemo)(()=>{let s=[];return $&&s.push("apple_pay"),ce&&s.push("google_pay"),s},[$,ce]),Mo=Zr?Es:_s,xs=q&&Mo.length>0,ya=er?Ye:x,Ao=(0,a.useMemo)(()=>{let s=ya?.trim().toUpperCase();return s?ue?Qr.filter(_=>{let K=ue[_];return!K||K.length===0||K.includes(s)}):(0,u.filterStripeMethodsByCountry)(Qr,ya):Qr},[Qr,ya,ue]),fa=(0,a.useMemo)(()=>({mode:"payment",amount:Xr,currency:Fe.toLowerCase(),paymentMethodCreation:"manual",appearance:Za}),[Xr,Fe,Za]),[ai,ii]=(0,a.useState)("loading"),[si,li]=(0,a.useState)("loading"),[ci,di]=(0,a.useState)("loading"),[Ts,ga]=(0,a.useState)(!1),[ui,ha]=(0,a.useState)("loading"),[Bo,Ms]=(0,a.useState)();(0,a.useEffect)(()=>{Ms(Zi())},[]);let pi=he&&(Gn||(Zr?Rs:Bo===!1)),mi=q&&xs,eo=!Z&&pi&&Gn,yi=ui==="retrying"||ui==="exhausted",to=!Z&&pi&&!!Ar&&(!Gn||yi),no=!Z&&mi&&!!bn,ro=!Z&&q&&xo&&Ao.length>0&&!!bn,As=eo&&!yi?Ts:to&&as(ai),Bs=no&&as(si),Fs=ro&&ci!=="load_error",fi=s=>s==="loading"||s==="ready",gi=eo||to&&fi(ai)||no&&fi(si)||ro&&ci!=="load_error",Fo=(0,a.useRef)(!1);(0,a.useEffect)(()=>{if(!Fo.current){if(!q&&!he){Fo.current=!0;let s=new u.FloPayError("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");d?.(s),Pe(s.message)}else if(!q&&he&&!Gn&&!Ar){Fo.current=!0;let s=new u.FloPayError("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");d?.(s),Pe(s.message)}else if(Bo!==void 0&&!Z&&!Xt&&!gi){Fo.current=!0;let s=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?.(s),Pe(s.message)}}},[q,he,Gn,Ar,Bo,Z,Xt,gi,d,Pe]);let hi=(0,a.useRef)(!1);(0,a.useEffect)(()=>{if(hi.current||!xo)return;let s=[];$!==!0&&s.push("showApplePay"),ce!==!0&&s.push("showGooglePay"),s.length!==0&&(hi.current=!0,console.warn(`[FloPay] ${s.join(" / ")} ${s.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.`))},[xo,$,ce]);let bi=(0,a.useCallback)((s,_)=>et.applyInlineSessionPatch?et.applyInlineSessionPatch(s).then(K=>({error:null,sessionId:K.sessionId||e,nonce:K.session?.clientSecret||t})).catch(K=>{let Ue=os(_,K);return Pe(Ue.message),d?.(Ue),{error:Ue,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[et.applyInlineSessionPatch,t,d,e,Pe]),qn=(0,a.useCallback)(async s=>{if(!L)return{proceed:!0};try{let _=await L({method:s,sessionId:e||void 0,createSession:et.inlineSessionDraft});if(_===!1)return{proceed:!1};if(_&&typeof _=="object"){_.account&&Nn(Ue=>({...Ue??{},..._.account}));let K=await bi(_,s);return K.error?{proceed:!1,accountPatch:_.account}:{proceed:!0,accountPatch:_.account,sessionId:K.sessionId,nonce:K.nonce}}return{proceed:!0}}catch(_){let K=os(s,_);return Pe(K.message),d?.(K),{proceed:!1}}},[bi,et.inlineSessionDraft,L,d,e,Pe]),vi=(0,a.useCallback)(async(s,_)=>{if(je.current)return;je.current=!0,ye(!0),F("processing"),Pe(null);let K=_?.sessionId??e,Ue=_?.nonce??t,Y=Ea(j,_?.accountPatch),De=_?.completionPaymentMethodId??po(s),Ge=s.originalPaymentMethodId?{...s,originalPaymentMethodId:void 0}:s,ut=s.gateway==="stripe"?"stripe":s.gateway==="paypal"||s.isPaypal?"paypal":void 0,Vt=()=>{Ct?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"process_payment",provider:ut})};try{let ht=await new cr.PaymentAPI(Ee).processPayment(Y.userId??"",{sessionId:K,nonce:Ue,tokenizedData:Ge,accountData:{userId:Y.userId??"",email:Y.email??"",...Y.firstName?{firstName:Y.firstName}:{},...Y.lastName?{lastName:Y.lastName}:{},...le?(()=>{let Qe=jt.current,en=(0,u.isAVSFieldVisible)(le.state,Qe),Mn=(0,u.isAVSFieldVisible)(le.address_line_1,Qe),Kt=(0,u.isAVSFieldVisible)(le.postal_code,Qe),lo=Mn&&!en&&Kt?(0,u.getStateFromPostalCode)(Qe,(ft.current??"").trim()):null,co=en?Jt.current:lo;return{country:Qe,...Kt&&ft.current?{zip:ft.current}:{},...(0,u.isAVSFieldVisible)(le.city,Qe)&&kn.current?{city:kn.current}:{},...co?{state:co}:{},...Mn&&ln.current?{addressLine1:ln.current}:{},...(0,u.isAVSFieldVisible)(le.address_line_2,Qe)&&wn.current?{addressLine2:wn.current}:{}}})():{}},chv:b,avsCheck:qe??!1,checkoutType:te,checkoutLayout:G,avsConfig:le?{country:(0,u.isAVSFieldVisible)(le.country,jt.current),postal_code:(0,u.isAVSFieldVisible)(le.postal_code,jt.current),address_line_1:(0,u.isAVSFieldVisible)(le.address_line_1,jt.current),address_line_2:(0,u.isAVSFieldVisible)(le.address_line_2,jt.current),city:(0,u.isAVSFieldVisible)(le.city,jt.current),state:(0,u.isAVSFieldVisible)(le.state,jt.current)}:void 0});if(ht.ok){let Qe=ht.status===204?null:await ht.json().catch(()=>null),en=(0,u.isAuthorizationOnlySession)(D)||Qe?.status==="authorized";Hr(K),F("success"),pe(null),await new Promise(Mn=>setTimeout(Mn,1200)),i?.(en?{status:"authorized",...typeof Qe?.paymentId=="string"?{paymentId:Qe.paymentId}:D?.paymentId?{paymentId:D.paymentId}:{},sessionId:typeof Qe?.sessionId=="string"?Qe.sessionId:K,...typeof Qe?.authorizationExpiresAt=="string"?{authorizationExpiresAt:Qe.authorizationExpiresAt}:D?.authorizationExpiresAt?{authorizationExpiresAt:D.authorizationExpiresAt}:{},paymentIntentId:s.threeDSecureActionResultTokenId,paymentMethodId:De,checkoutMethod:s.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:s.threeDSecureActionResultTokenId,paymentMethodId:De,checkoutMethod:s.isPaypal?"paypal":"card"});return}let nt=await ht.json().catch(()=>null);if(nt?.type==="paypal_redirect_required"){let Qe=nt.threeDSecureToken,en=nt.paymentMethodId||s.id||"";if(!ie||!Qe){F("error"),Pe("PayPal authorization required but no token provided.");return}try{let Mn=ct?.getRawProvider();if(!Mn){Pe("PayPal is not available.");return}let Kt={return_url:window.location.href};en&&(Kt.payment_method=en);let{error:lo}=await Mn.confirmPayment({clientSecret:Qe,confirmParams:Kt,redirect:"if_required"});if(lo){F("error");let co=lo.message??"PayPal payment failed.";Pe(co),Un("paypal",co,{code:lo.code})}}catch(Mn){F("error"),Pe(Mn instanceof Error?Mn.message:"PayPal authorization failed.")}return}if(nt?.type==="paypal_direct_required"){let Qe=nt.orderId;if(!Qe){F("error"),Pe("PayPal retry required but no order id provided.");return}let en=de.current?.attempts??0;if(en>=2){F("error"),Pe("PayPal payment could not be completed after multiple attempts."),Un("paypal","paypal_direct_required retry limit exceeded");return}ga(!1),ha("loading"),pe({orderId:Qe,attempts:en+1}),F(null);return}(0,u.classifyPaymentRejection)(ht.status,nt)||Vt(),F("error");let Qt=nt?.message??"Payment failed. Please try again.";Pe(Qt),Un(s.isPaypal?"paypal":"card",Qt,{code:nt?.code??nt?.gatewayErrorCode,declineCode:nt?.declineCode??nt?.gatewayDeclineReason}),await new Promise(Qe=>setTimeout(Qe,1500))}catch(gt){cs(gt)||Vt(),F("error"),Pe(gt instanceof Error?gt.message:"An unexpected error occurred"),await new Promise(ht=>setTimeout(ht,1500))}finally{ye(!1),F(null),je.current=!1}},[Ee,e,t,j,le,qe,te,G,b,ie,ct,D,i,Pe,Un,Ct]),xn=(0,a.useCallback)((s,_)=>{v?v(s):vi(s,_)},[v,vi]),Pi=(0,a.useRef)(!1);(0,a.useEffect)(()=>{if(typeof window>"u"||Pi.current)return;let s=new URLSearchParams(window.location.search),_=s.get("payment_intent"),K=s.get("payment_intent_client_secret"),Ue=s.get("redirect_status");if(!_||!K)return;let Y=ht=>{let nt=localStorage.getItem(ht);if(!nt)return null;try{return JSON.parse(nt)}catch{return localStorage.removeItem(ht),null}},De=Y(Jn)??Y(ts),Ge;if(De?.clientSecret){if(De.clientSecret!==K)return;Ge={...De.accountPatch?{accountPatch:De.accountPatch}:{},...De.sessionId?{sessionId:De.sessionId}:{},...De.nonce?{nonce:De.nonce}:{}}}else if(De?.sessionId&&De.sessionId!==e)return;Pi.current=!0,localStorage.removeItem(Jn),localStorage.removeItem(ts);let ut=new URL(window.location.href);ut.searchParams.delete("payment_intent"),ut.searchParams.delete("payment_intent_client_secret"),ut.searchParams.delete("redirect_status"),window.history.replaceState({},"",ut.toString());let Vt=De?.paymentMethodType??De?.tokenType??"card",gt="card";(async()=>{let ht=ie?.getRawProvider();if(!ht){let Kt="Payment is not available \u2014 please refresh and try again.";Pe(Kt),Un(gt,Kt);return}if(Ue==="failed"){let Kt="Payment was declined. Please try again.";Pe(Kt),Un(gt,Kt);return}let{paymentIntent:nt,error:Qt}=await ht.retrievePaymentIntent(K);if(Qt){let Kt=Qt.message??"Failed to retrieve payment status.";Pe(Kt),Un(gt,Kt,{code:Qt.code});return}let Qe=nt?.status,en=jo(Qe);if(!nt||!en){let Kt=Qe==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";Pe(Kt),Un(gt,Kt,{code:Qe??"missing_payment_intent"});return}let Mn=typeof nt.payment_method=="string"?nt.payment_method:nt.payment_method?.id;xn({id:Mn??De?.paymentMethodId??De?.tokenId??nt.id,type:"card",threeDSecureActionResultTokenId:nt.id,gateway:De?.gateway??"stripe",paymentMethodType:Vt},Ge)})()},[e,xn,ie,Pe,Un]);let ba=(0,a.useCallback)(s=>{s.preventDefault()},[]);if(!(ie!==null))return(0,l.jsx)("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let oo=W==="buttons",on=J?.variables,Ds=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),va=on?.colorBackground,Ls=va&&!Ds.has(va)?va:void 0,ao=m.cardInputBorder??(oo?"#e5e7eb":"#A4A4FF"),Ci=on?.colorDanger??"#dc2626",wt=s=>yr[s]&&(At[s]||nr),Do=Lt&&(Yn||nr),Tn=s=>s?Ci:ao,Lo=(Wt.malformed||Wt.empty)&&(Rn||nr),Ns=Tn(Lo),Pa=m.cardFormContainer?.backgroundColor??Ls??(oo?"white":"#EDEDFF"),Fr=m.cardInputBackground??on?.colorBackground??"white",Ca=Lr(xe),Si=Lr(Te),Dr=m.nameInput,wi=m.cardInputFontSize??Tl(Dr?.fontSize)??on?.fontSizeBase??"16px",ki=typeof Dr?.fontFamily=="string"?Dr.fontFamily:on?.fontFamily??"Poppins, sans-serif",Ii=Fa(Dr?.fontWeight)??400,Os=m.cardInputColor??(typeof Dr?.color=="string"?Dr.color:void 0)??on?.colorText??"#262833",zs=m.cardInputPlaceholderColor??"#9ca3af",_t=on?.borderRadius??"8px",Sr=on?.borderRadius??m.cardButton?.borderRadius??_t,wr=on?.colorPrimary??"#4A49FF",Us=on?.colorPrimaryHover??Jr(wr,.12),Sa=on?.colorText??"#262833",wa={fontSize:wi,fontFamily:ki,fontWeight:Ii,color:Os,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},io={marginTop:"0.375rem",...wa,fontSize:"0.75rem",lineHeight:1.4,color:Ci},qs={"--flopay-input-placeholder-color":zs,"--flopay-input-font-size":wi,"--flopay-input-font-family":ki,"--flopay-input-font-weight":String(Ii)},so=m.cardFormContainer??{},ka=so.padding??(oo?"0":"1rem"),Ia=so.borderRadius??_t,$s=fe&&fn?(0,l.jsx)(Gr,{capture:fe,html:fn.html,messageToken:fn.messageToken,expectedOrigin:fn.expectedOrigin,theme:ke,onReady:()=>{if(!mt&&!le||typeof document>"u")return;let s=()=>{let K=(document.querySelector('[data-testid="flopay-vault-identity-fields"]')??document.querySelector('[data-testid="flopay-avs-fields"]'))?.querySelector("input:not([disabled]), select:not([disabled])");if(K){Zt.current=!0;try{K.focus()}finally{Zt.current=!1}}};pn.current||s()},onError:s=>Pe(s),onValidation:s=>{let _=N.current;(_==="idle"||_==="validation-window")&&(Pe(s),s&&N.current==="validation-window"&&(ae.current&&(clearTimeout(ae.current),ae.current=null),N.current="idle",F(null)))}}):(0,l.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"}),Ri=(0,l.jsxs)("div",{onFocusCapture:s=>{["INPUT","SELECT","TEXTAREA","IFRAME"].includes(s.target.tagName)&&zn()},style:{backgroundColor:Pa,borderRadius:Ia,...so,padding:ka,...qs,display:"flex",flexDirection:"column"},children:[(0,l.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 @@ ${w.join(`
35
35
  font-family: var(--flopay-input-font-family);
36
36
  font-weight: var(--flopay-input-font-weight);
37
37
  }
38
- `}),no&&mr&&(0,l.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:h?-2:0},children:[(0,l.jsxs)("button",{type:"button",onClick:V,style:{display:"inline-flex",alignItems:"center",gap:Pa?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:F.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...F.backButton},"aria-label":"Back to payment methods",children:[(0,l.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...F.backButtonIcon},children:(0,l.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,l.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,l.jsx)(Lr,{content:Ie})]}),Ci?(0,l.jsx)("div",{style:{flex:1}}):(0,l.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:F.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...F.title},children:(0,l.jsx)(lo,{content:Re})})]}),!no&&!Ci&&(0,l.jsx)("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:Ca,order:h?-3:0,...F.title},children:(0,l.jsx)(lo,{content:Re})}),h&&ke&&(0,l.jsx)("div",{style:{order:-2,width:"100%"},children:ke}),h&&yr&&(0,l.jsxs)("div",{"data-testid":"flopay-vault-identity-fields",style:{order:-1,marginTop:"0.5rem"},children:[(0,l.jsx)("div",{style:{backgroundColor:Br,border:`1px solid ${Sn(Ao)}`,borderRadius:kt,padding:"10px"},children:(0,l.jsx)("input",{className:"flopay-shared-input",id:"flopay-buyer-email",name:"email",type:"email",autoComplete:"email","aria-label":"Email address",placeholder:"Email address",value:je,onChange:s=>{st("email"),dr.current=s.target.value,Un(s.target.value)},onPointerDown:()=>st("email"),onKeyDown:()=>st("email"),onBlur:()=>{Qn("email")&&Zt(!0),xr||ua()},disabled:lt,required:!0,"aria-invalid":Ao||void 0,"aria-describedby":Ao?"flopay-buyer-email-error":void 0,"data-testid":"flopay-email",style:{width:"100%",border:"none",outline:"none",background:"transparent",...Sa}})}),Ao&&(0,l.jsx)("div",{id:"flopay-buyer-email-error",role:"alert","data-testid":"flopay-email-error",style:oo,children:ca.empty?"Email address is required":"Enter a valid email address"})]}),ue&&(0,l.jsx)("div",{style:{order:h?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let s=Ye,_=(G=!1)=>({backgroundColor:Br,border:`1px solid ${Sn(G)}`,borderRadius:kt,marginTop:"0.5rem",padding:"10px"}),K=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...Sa}),De=(0,p.getStateOptions)(s);return(0,l.jsxs)(l.Fragment,{children:[(0,p.isAVSFieldVisible)(ue.address_line_1,s)&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)("div",{style:_(Ct("line1")),children:(0,l.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:dn,onChange:G=>{st("line1"),Ot.current.addressLine1=!0,pn.current=G.target.value,_n(G.target.value)},onPointerDown:()=>st("line1"),onKeyDown:()=>st("line1"),onBlur:()=>An("line1"),disabled:lt,required:!0,"aria-invalid":Ct("line1")||void 0,"aria-describedby":Ct("line1")?"flopay-billing-address-line1-error":void 0,"data-testid":"flopay-address-line1",style:K()})}),Ct("line1")&&(0,l.jsx)("div",{id:"flopay-billing-address-line1-error",role:"alert","data-testid":"flopay-address-line1-error",style:oo,children:"Street address is required"})]}),(0,p.isAVSFieldVisible)(ue.address_line_2,s)&&(0,l.jsx)("div",{style:_(),children:(0,l.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:zn,onChange:G=>{Ot.current.addressLine2=!0,rn.current=G.target.value,Jt(G.target.value)},disabled:lt,"data-testid":"flopay-address-line2",style:K()})}),((0,p.isAVSFieldVisible)(ue.city,s)||(0,p.isAVSFieldVisible)(ue.state,s))&&(0,l.jsxs)("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[(0,p.isAVSFieldVisible)(ue.city,s)&&(0,l.jsx)("div",{style:{flex:1,backgroundColor:Br,borderTop:`1px solid ${Sn(Ct("city"))}`,borderRight:`1px solid ${Sn(Ct("city"))}`,borderBottom:`1px solid ${Sn(Ct("city"))}`,borderLeft:`1px solid ${Sn(Ct("city"))}`,padding:"10px",borderTopLeftRadius:kt,borderBottomLeftRadius:kt,...(0,p.isAVSFieldVisible)(ue.state,s)?{borderRight:"none",borderTopRightRadius:0,borderBottomRightRadius:0}:{borderRadius:kt}},children:(0,l.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-city",name:"billing-city",placeholder:"City",autoComplete:"billing address-level2",value:xn,onChange:G=>{st("city"),Ot.current.city=!0,mn.current=G.target.value,Ht(G.target.value)},onPointerDown:()=>st("city"),onKeyDown:()=>st("city"),onBlur:()=>An("city"),disabled:lt,required:!0,"aria-invalid":Ct("city")||void 0,"aria-describedby":Ct("city")?"flopay-billing-city-error":void 0,"data-testid":"flopay-city",style:K()})}),(0,p.isAVSFieldVisible)(ue.state,s)&&(0,l.jsx)("div",{style:{flex:1,backgroundColor:Br,borderTop:`1px solid ${Sn(Ct("state"))}`,borderRight:`1px solid ${Sn(Ct("state"))}`,borderBottom:`1px solid ${Sn(Ct("state"))}`,borderLeft:`1px solid ${Sn(Ct("state"))}`,padding:"10px",borderTopRightRadius:kt,borderBottomRightRadius:kt,...(0,p.isAVSFieldVisible)(ue.city,s)?{borderTopLeftRadius:0,borderBottomLeftRadius:0,borderLeft:`1px solid ${Sn(Ct("state")||Ct("city"))}`}:{borderRadius:kt}},children:De?(0,l.jsxs)("select",{id:"flopay-billing-state",name:"billing-state",value:nt,onChange:G=>{st("state"),Ot.current.state=!0,Bt.current=G.target.value,un(G.target.value)},onPointerDown:()=>st("state"),onKeyDown:()=>st("state"),onBlur:()=>An("state"),disabled:lt,autoComplete:"billing address-level1",required:!0,"aria-invalid":Ct("state")||void 0,"aria-describedby":Ct("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:{...K(),cursor:"pointer"},children:[(0,l.jsx)("option",{value:"",children:(0,p.getStateLabel)(s)}),De.map(G=>(0,l.jsx)("option",{value:G.code,children:G.name},G.code))]}):(0,l.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-state",name:"billing-state",placeholder:(0,p.getStateLabel)(s),autoComplete:"billing address-level1",value:nt,onChange:G=>{st("state"),Ot.current.state=!0,Bt.current=G.target.value,un(G.target.value)},onPointerDown:()=>st("state"),onKeyDown:()=>st("state"),onBlur:()=>An("state"),disabled:lt,required:!0,"aria-invalid":Ct("state")||void 0,"aria-describedby":Ct("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:K()})})]}),Ct("city")&&(0,l.jsx)("div",{id:"flopay-billing-city-error",role:"alert","data-testid":"flopay-city-error",style:oo,children:"City is required"}),Ct("state")&&(0,l.jsxs)("div",{id:"flopay-billing-state-error",role:"alert","data-testid":"flopay-state-error",style:oo,children:[(0,p.getStateLabel)(s)," is required"]}),((0,p.isAVSFieldVisible)(ue.country,s)||(0,p.isAVSFieldVisible)(ue.postal_code,s))&&(0,l.jsxs)("div",{style:{display:"flex",flexDirection:Ce==="column"?"column":"row",gap:Ce==="column"?"0.5rem":"0",marginTop:"0.5rem"},children:[(0,p.isAVSFieldVisible)(ue.country,s)&&(0,l.jsx)("div",{style:{flex:Ce==="row"?1:void 0,backgroundColor:Br,borderTop:`1px solid ${ro}`,borderRight:`1px solid ${ro}`,borderBottom:`1px solid ${ro}`,borderLeft:`1px solid ${ro}`,padding:"10px",...Ce==="row"&&(0,p.isAVSFieldVisible)(ue.postal_code,s)?{borderRadius:"0",borderTopLeftRadius:kt,borderBottomLeftRadius:kt,borderRight:"none"}:{borderRadius:kt}},children:(0,l.jsx)("select",{id:"flopay-billing-country",name:"billing-country",value:Ye,onChange:G=>{Ot.current.country=!0,Vt.current=G.target.value,jt(G.target.value),Qe?.(G.target.value),Bt.current="",un("")},disabled:lt,autoComplete:"billing country","data-testid":"flopay-country",style:{...K(),cursor:"pointer"},children:p.COUNTRY_OPTIONS.map(G=>(0,l.jsxs)("option",{value:G.code,children:[G.flag," ",G.name]},G.code))})}),(0,p.isAVSFieldVisible)(ue.postal_code,s)&&(0,l.jsx)("div",{style:{flex:Ce==="row"?1:void 0,backgroundColor:Br,border:`1px solid ${Ns}`,padding:"10px",...Ce==="row"&&(0,p.isAVSFieldVisible)(ue.country,s)?{borderRadius:"0",borderTopRightRadius:kt,borderBottomRightRadius:kt}:{borderRadius:kt}},children:(0,l.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-postal-code",name:"billing-postal-code",placeholder:(0,p.getPostalCodeLabel)(Ye),autoComplete:"billing postal-code",value:Lt,onChange:G=>{st("zip"),Ot.current.zip=!0,Nt.current=G.target.value,At(G.target.value),ot?.(G.target.value)},onPointerDown:()=>st("zip"),onKeyDown:()=>st("zip"),onBlur:()=>{Qn("zip")&&Zn(!0)},disabled:lt,required:Yt.required,"aria-invalid":Bo||void 0,"aria-describedby":Bo?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:K()})})]}),Bo&&(0,l.jsx)("div",{id:"flopay-billing-postal-code-error",role:"alert","data-testid":"flopay-zip-error",style:oo,children:Yt.empty?`${(0,p.getPostalCodeLabel)(s)} is required`:El(s)})]})})()}),h&&$s,k&&(0,l.jsx)(jr,{margin:"0.75rem 0",styleOverride:F.errorBanner,children:k})]}),Mo={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"},Ri=s=>ft?!ge||!Vn?(0,l.jsx)("pre",{"data-testid":s,style:Mo,children:"FloPay/DirectPayPal-debug - not enabled"}):(0,l.jsx)("pre",{"data-testid":s,style:Mo,children:["FloPay/DirectPayPal-debug (parent gate)",` showPayPal=${ge}`,` directPaypalConfigured=${Vn}`,` inAppBrowserDetected=${String(xo)}`,` shouldRenderDirectPayPal=${Zr}`,` shouldRenderStripePayPal=${Qr}`,` hasPaypalStripeInstance=${!!Tr}`].join(`
39
- `)}):null,Ei=s=>ft?!$||!Pn?(0,l.jsx)("pre",{"data-testid":s,style:Mo,children:"FloPay/Stripe-debug - not enabled"}):(0,l.jsx)("pre",{"data-testid":s,style:Mo,children:["FloPay/Stripe-debug (parent gate)",` showStripe=${$}`,` currency=${Te}`,` amountInCents=${Gr}`,` enabledPaymentMethods: ${JSON.stringify(S??[])}`,` enabledPaymentMethodsProvided=${Jr}`,` hasEnabledMethods=${Io}`,` expressMethods: ${JSON.stringify(Ro)}`,` walletExpressMethods: ${JSON.stringify(Eo)}`,` paymentElementMethods: ${JSON.stringify(Xr)}`,` paymentElementMethodsForCurrency: ${JSON.stringify(_o)}`,` hasStripeInstance=${!!Pn}`,` shouldRenderWallets=${eo}`,` shouldRenderPaymentElement=${to}`].join(`
40
- `)}):null,_i=qe==="apm-expanding"||qe==="apm-form"||qe==="apm-collapsing",Fo=qe==="apm-expanding"?`flopay-card-enter ${zt}ms cubic-bezier(0, 0, 0.2, 1) both`:qe==="apm-collapsing"?`flopay-card-exit ${zt}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0,Do=Et?{...ya,paymentMethodTypes:[Et]}:null;if(J==="buttons"){let s=qe==="buttons"||qe==="expanding"||qe==="apm-expanding",_=qe==="expanding"||qe==="card"||qe==="collapsing",K=Me===void 0?{boxSizing:"border-box",height:Zo,padding:"0 1rem"}:{padding:"0.9rem 1rem"},De=qe==="expanding"||qe==="apm-expanding"?`flopay-buttons-exit ${zt}ms cubic-bezier(0.4, 0, 0.2, 1) both`:qe==="collapsing"||qe==="apm-collapsing"?`flopay-buttons-enter ${zt}ms cubic-bezier(0, 0, 0.2, 1) both`:void 0,G=qe==="expanding"?`flopay-card-enter ${zt}ms cubic-bezier(0, 0, 0.2, 1) both`:qe==="collapsing"?`flopay-card-exit ${zt}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0;return(0,l.jsxs)("form",{onSubmit:ha,className:N,noValidate:!0,style:{position:"relative"},children:[(0,l.jsx)(Da,{}),Ae&&(0,l.jsx)(Rn,{status:Ae,errorMessage:k,authorized:yn}),(0,l.jsxs)("div",{style:{display:"grid"},children:[(0,l.jsxs)("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!s&&!De?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!s&&!De?kl:{},...De?{animation:De,pointerEvents:"none"}:{}},children:[Ri("flopay-direct-paypal-gate-debug"),Ei("flopay-stripe-gate-debug"),Zr&&M&&(0,l.jsxs)(l.Fragment,{children:[A&&(0,l.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,l.jsx)(mo,{sessionId:e,nonce:t,billingApiUrl:Q,email:ve.email,billingName:sn||void 0,onBuyerIdentityReady:z,clientId:M.clientId,environment:M.environment,currency:Te.toUpperCase(),isSubscription:ie,providerObjectType:M.providerObjectType,onTokenizedBody:Cn,onComplete:i,onErrorChange:be,onDecline:c,onTechnicalFailure:Ar,onButtonClick:oe,runBeforeButtonClick:Dn,isProcessing:lt,onLoadStateChange:fa,onInitializationStateChange:ga,session:L??null,existingOrderId:A?.orderId,debug:ft},A?.orderId??"fresh")]}),Qr&&(0,l.jsx)(Rt.Elements,{stripe:Tr,options:ei,children:(0,l.jsx)(as,{sessionId:e,nonce:t,email:ve.email,billingName:sn||void 0,onBuyerIdentityReady:z,billingApiUrl:Q,onTokenizedBody:Cn,onErrorChange:be,isProcessing:lt,onButtonClick:oe,onDecline:c,onTechnicalFailure:Ar,runBeforeButtonClick:Dn,onLoadStateChange:ai,placeholderBorderRadius:Pr})}),eo?(0,l.jsx)(Rt.Elements,{stripe:Pn,options:Qa,children:(0,l.jsx)(is,{sessionId:e,nonce:t,email:ve.email,billingName:sn||void 0,onBuyerIdentityReady:z,billingApiUrl:Q,intentKind:H>0?"payment":"setup",expressMethods:Eo,onTokenizedBody:Cn,onErrorChange:be,onButtonClick:oe,onDecline:c,onTechnicalFailure:Ar,runBeforeButtonClick:Dn,onLoadStateChange:si,placeholderBorderRadius:Pr})}):pi?(0,l.jsx)("div",{style:{height:Zo,borderRadius:Pr,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,to&&(0,l.jsx)(ss,{sessionId:e,nonce:t,email:ve.email,billingName:[ve.firstName,ve.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:z,billingApiUrl:Q,paymentElementMethods:_o,stripeInstance:Pn,paymentElementBaseOptions:ya,onTokenizedBody:Cn,onErrorChange:be,onButtonClick:oe,onDecline:c,runBeforeButtonClick:Dn,onLoadStateChange:ci,isProcessing:lt,submitButtonColor:Cr,submitButtonBorderRadius:kt,submitButtonStyle:F.submitButton,onExpandApm:Y,expandedApmMethod:Et,themeId:he,buttonAppearance:{backgroundColor:F.cardButton?.backgroundColor,borderColor:F.cardInputBorder,textColor:F.cardButton?.color,borderRadius:Pr}}),h&&(0,l.jsx)("button",{type:"button",onClick:async()=>{lt||!(await Dn("card")).proceed||(oe?.("card"),U())},disabled:lt,style:{width:"100%",...K,...F.cardButton,...za({themeBundle:W,resolvedPrimaryColor:Cr,resolvedBorderRadius:kt,submitButtonStyle:F.submitButton,explicitPrimaryColor:tn?.colorPrimary}),fontSize:F.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:lt?"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:lt?.6:1},onMouseEnter:Be=>{!lt&&(W||tn?.colorPrimary)&&(Be.currentTarget.style.backgroundColor=Us)},onMouseLeave:Be=>{(W||tn?.colorPrimary)&&(Be.currentTarget.style.backgroundColor=Cr)},onMouseDown:Be=>{Be.currentTarget.style.transform="scale(0.985)"},onMouseUp:Be=>{Be.currentTarget.style.transform="scale(1)"},children:(0,l.jsx)(Dr,{content:Me})}),k&&qe==="buttons"&&(0,l.jsx)(jr,{margin:"0.25rem 0",styleOverride:F.errorBanner,children:k})]}),h&&_&&(0,l.jsx)("div",{style:{gridArea:"1 / 1",...G?{animation:G}:{},...qe==="collapsing"?{pointerEvents:"none"}:{}},children:Ii}),$&&_i&&Et&&Do&&Pn&&(0,l.jsx)("div",{style:{gridArea:"1 / 1",...Fo?{animation:Fo}:{},...qe==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,l.jsxs)("div",{style:{backgroundColor:va,borderRadius:ka,...ao,padding:wa},children:[(0,l.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,l.jsxs)("button",{type:"button","data-testid":"flopay-apm-back-button",onClick:le,style:{display:"inline-flex",alignItems:"center",gap:Pa?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:F.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...F.backButton},"aria-label":"Back to payment methods",children:[(0,l.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...F.backButtonIcon},children:(0,l.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,l.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,l.jsx)(Lr,{content:Ie})]}),(0,l.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:F.titleFontSize??"1.05rem",color:Ca,paddingRight:80,...F.title},children:`Pay with ${(0,p.getStripeMethodDisplayName)(Et)}`})]}),(0,l.jsx)(Rt.Elements,{stripe:Pn,options:Do,children:(0,l.jsx)(Na,{method:Et,sessionId:e,nonce:t,email:ve.email,billingName:[ve.firstName,ve.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:z,billingApiUrl:Q,onTokenizedBody:Cn,onErrorChange:be,onDecline:c,onCancel:le,runBeforeButtonClick:Dn,onButtonClick:oe,isProcessing:lt,submitButtonColor:Cr,submitButtonBorderRadius:kt,submitButtonStyle:F.submitButton,errorText:k})},Et)]})})]})]})}return _i&&Et&&Do&&Pn&&$?(0,l.jsxs)("form",{onSubmit:ha,className:N,noValidate:!0,style:{position:"relative"},children:[(0,l.jsx)(Da,{}),Ae&&(0,l.jsx)(Rn,{status:Ae,errorMessage:k,authorized:yn}),(0,l.jsx)("div",{style:{...Fo?{animation:Fo}:{},...qe==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,l.jsxs)("div",{style:{backgroundColor:va,borderRadius:ka,...ao,padding:wa},children:[(0,l.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,l.jsxs)("button",{type:"button","data-testid":"flopay-apm-back-button-default",onClick:le,style:{display:"inline-flex",alignItems:"center",gap:Pa?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:F.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...F.backButton},"aria-label":"Back to payment methods",children:[(0,l.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...F.backButtonIcon},children:(0,l.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,l.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,l.jsx)(Lr,{content:Ie})]}),(0,l.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:F.titleFontSize??"1.05rem",color:Ca,paddingRight:80,...F.title},children:`Pay with ${(0,p.getStripeMethodDisplayName)(Et)}`})]}),(0,l.jsx)(Rt.Elements,{stripe:Pn,options:Do,children:(0,l.jsx)(Na,{method:Et,sessionId:e,nonce:t,email:ve.email,billingName:[ve.firstName,ve.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:z,billingApiUrl:Q,onTokenizedBody:Cn,onErrorChange:be,onDecline:c,onCancel:le,runBeforeButtonClick:Dn,onButtonClick:oe,isProcessing:lt,submitButtonColor:Cr,submitButtonBorderRadius:kt,submitButtonStyle:F.submitButton,errorText:k})},Et)]})})]}):(0,l.jsxs)("form",{onSubmit:ha,className:N,noValidate:!0,style:{position:"relative"},children:[(0,l.jsx)(Da,{}),Ae&&(0,l.jsx)(Rn,{status:Ae,errorMessage:k,authorized:yn}),(0,l.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Ri("flopay-direct-paypal-gate-debug-default"),Ei("flopay-stripe-gate-debug-default"),Zr&&M&&(0,l.jsxs)(l.Fragment,{children:[A&&(0,l.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,l.jsx)(mo,{sessionId:e,nonce:t,billingApiUrl:Q,email:ve.email,billingName:sn||void 0,onBuyerIdentityReady:z,clientId:M.clientId,environment:M.environment,currency:Te.toUpperCase(),isSubscription:ie,providerObjectType:M.providerObjectType,onTokenizedBody:Cn,onComplete:i,onErrorChange:be,onDecline:c,onTechnicalFailure:Ar,onButtonClick:oe,runBeforeButtonClick:Dn,isProcessing:lt,onLoadStateChange:fa,onInitializationStateChange:ga,session:L??null,existingOrderId:A?.orderId,debug:ft},A?.orderId??"fresh")]}),Qr&&(0,l.jsx)(Rt.Elements,{stripe:Tr,options:ei,children:(0,l.jsx)(as,{sessionId:e,nonce:t,email:ve.email,billingName:sn||void 0,onBuyerIdentityReady:z,billingApiUrl:Q,onTokenizedBody:Cn,onErrorChange:be,isProcessing:lt,onButtonClick:oe,onDecline:c,onTechnicalFailure:Ar,runBeforeButtonClick:Dn,onLoadStateChange:ai,placeholderBorderRadius:Pr})}),eo&&(0,l.jsx)(Rt.Elements,{stripe:Pn,options:Qa,children:(0,l.jsx)(is,{sessionId:e,nonce:t,email:ve.email,billingName:sn||void 0,onBuyerIdentityReady:z,billingApiUrl:Q,intentKind:H>0?"payment":"setup",expressMethods:Eo,onTokenizedBody:Cn,onErrorChange:be,onButtonClick:oe,onDecline:c,onTechnicalFailure:Ar,runBeforeButtonClick:Dn,onLoadStateChange:si,placeholderBorderRadius:Pr})}),to&&(0,l.jsx)(ss,{sessionId:e,nonce:t,email:ve.email,billingName:[ve.firstName,ve.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:Q,paymentElementMethods:_o,stripeInstance:Pn,paymentElementBaseOptions:ya,onTokenizedBody:Cn,onErrorChange:be,onButtonClick:oe,onDecline:c,runBeforeButtonClick:Dn,onLoadStateChange:ci,isProcessing:lt,submitButtonColor:Cr,submitButtonBorderRadius:kt,submitButtonStyle:F.submitButton,themeId:he,onExpandApm:Y,expandedApmMethod:Et,buttonAppearance:{backgroundColor:F.cardButton?.backgroundColor,borderColor:F.cardInputBorder,textColor:F.cardButton?.color,borderRadius:Pr}})]}),h&&(Ms||Bs||Fs)&&(0,l.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem",margin:"0.5rem 0 0.75rem",color:"#999",fontSize:"0.85rem"},children:[(0,l.jsx)("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}}),(0,l.jsx)("span",{children:"or pay with card"}),(0,l.jsx)("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}})]}),h&&Ii]})}var I=require("react/jsx-runtime"),_r=44,Ga="flopay_checkout_saved_payment_resume",oa=new Map,na=new Map;function ys(e,t){t.settled&&t.consumers===0&&oa.get(e)===t&&oa.delete(e)}function Ml(e,t,n){let r=na.get(e);if(r&&(!r.sdkGeneratedIdempotencyKey||!t||r.sdkGeneratedIdempotencyKey===t))return r.attempt;let o=n(),i={attempt:o,sdkGeneratedIdempotencyKey:t};na.set(e,i);let u=()=>{na.get(e)===i&&na.delete(e)};return o.then(u,u),o}function vo(e){return new Promise(t=>setTimeout(t,e))}function ra(e,t,n){let r=jo({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:Pe.SDK_VERSION,enabled:t!==!1});return r.beginCheckout(n),r}function Po(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function Ua(e,t,n,r,o){let i=ra(e,t,n);i.error({errorCode:r,stage:o,paymentMethodCategory:"unknown",...o==="session_read"?{requestCategory:"session_read"}:{}}),Po(i)}function Fl(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 Ya(e){let t=e?.data.paypal?.publishableKey;if(t)return{clientId:t,environment:e?.data.paypal?.environment,providerObjectType:e?.data.paypal?.providerObjectType}}function qa(e){return!e||e.data.stripe?.publishableKey?!1:!!Ya(e)?.clientId}function lr(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function Dl(){if(!lr())return null;try{let e=window.sessionStorage.getItem(Ga);return e?JSON.parse(e):null}catch{return null}}function fs(e){if(lr())try{window.sessionStorage.setItem(Ga,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function $a(){if(lr())try{window.sessionStorage.removeItem(Ga)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}var Ja=":idempotency-key";function hs(e,t){if(!lr())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 ja(e,t,n,r){if(lr())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 Wa(e,t){if(lr())try{hs(e,t)&&window.sessionStorage.removeItem(e)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout session cache.",n)}}function bs(e,t){if(!lr())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 Va(e,t,n){if(lr())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 Ka(e,t){if(Wa(e,t),!!lr())try{bs(e,t)&&window.sessionStorage.removeItem(e+Ja)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout idempotency key.",n)}}function Ll(){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 gs(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 Nl(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 Ha(e,t){return`${e}:${t.totalAmount??""}:${t.overrideAmount??""}:${t.quantity??1}:${t.currency??""}`}function Co(e,t=!1){let n=e?.account?.email?.trim().toLowerCase()??"",r={c:e?.clientId,cur:e?.currency??"",captureMethod:e?.captureMethod??"",a:{e:n,u:n?"":e?.account?.userId??"",country:e?.account?.country??""},successUrl:e?.successUrl,cancelUrl:e?.cancelUrl,p:e?.products?.map(o=>Ha(`${o.type??""}:${o.code??o.providerItemId??o.providerPlanId??""}`,o)).sort(),i:e?.items?.map(o=>Ha(o.code??o.providerItemId??"",o)).sort(),s:e?.subscriptions?.map(o=>Ha(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 Ol(e,t=!1){let n=Co(e,t),r=0;for(let o=0;o<n.length;o++)r=(r<<5)-r+n.charCodeAt(o)|0;return`flopay_session_${Math.abs(r).toString(36)}`}function zl(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,Pe.resolveSessionCurrency)(t.currency,t.items,t.subscriptions,t.products);if(!o||e.currency.toUpperCase()!==o.toUpperCase())return!1;let i=(t.products??(0,Pe.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,b)=>`${g.code}:${g.type??""}`.localeCompare(`${b.code}:${b.type??""}`)),u=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,b)=>`${g.code}:${g.type??""}`.localeCompare(`${b.code}:${b.type??""}`));if(i.length!==u.length)return!1;for(let g=0;g<i.length;g+=1){let b=i[g],v=u[g];if(b.code!==v.code||b.type!==void 0&&b.type!==v.type||b.quantity!==v.quantity||b.totalAmount!==v.totalAmount||b.overrideAmount!==v.overrideAmount||b.currency!==v.currency)return!1}let c=[...t.couponCodes??[]].sort(),P=[...e.coupons??[]].sort();return c.length===P.length&&c.every((g,b)=>g===P[b])}function aa({sessionId:e,nonce:t,createSession:n,billingApiUrl:r,telemetry:o,appearance:i,locale:u,loading:c,error:P,onComplete:g,onError:b,onInstrument:v,onDecline:N,onCountryChange:B,onZipChange:f,showPayPal:C=!0,showStripe:ge=!0,enabledPaymentMethods:$,showApplePay:S=!0,showGooglePay:ye=!0,debug:j=!1,layout:pe,theme:J,buttonsTheme:he,buttonsStyles:ze,cardButtonContent:we,cardBackButtonContent:yt,cardTitleContent:Me,showSecurityFooter:Ie,onButtonClick:Re,onBeforeButtonClick:re,enableAVS:oe,cardFieldOrder:O,cardPreFormSlot:Ee,avsLayout:_e,className:X,initialErrorMessage:ke=null,children:Ce,checkoutMode:x,confirmLabel:q,renderConfirmButton:xe,onSessionCompleted:fe}){let te=(0,Pe.resolveBillingApiUrl)(r),Fe=(0,R.useMemo)(()=>(0,Pe.resolveTheme)(J),[J]),Qe=i??Fe?.appearance,ot=n?"embedded_checkout":"standard_checkout",Le=Ce?"custom_layout":pe==="buttons"?"buttons_layout":"default_layout",[ae,Z]=(0,R.useState)(null),[H,Te]=(0,R.useState)(null),He=(0,R.useRef)(null),[M,ie]=(0,R.useState)(null),L=(0,R.useRef)(null),[E,et]=(0,R.useState)(null),ft=(0,R.useMemo)(()=>n?Co(n):"",[n]),ce=n?`create:${ft}`:`session:${e??""}`,tt=E?.gateways?.stripe?"stripe":E?.gateways?.paypal?"paypal":void 0,Ge=(0,R.useRef)(new Set),gt=(0,R.useRef)(ce),St=(0,R.useRef)(ce);$o(()=>{St.current=ce,gt.current!==ce&&(gt.current=ce,Ge.current.clear())},[ce]);let w=(0,R.useCallback)(U=>{if(St.current===ce){if(_a.has(U.name)){if(Ge.current.has(U.name))return;Ge.current.add(U.name)}Ke(()=>v?.(U))}},[ce,v]),se=$r(w,ce),de=(0,R.useRef)(!1),at=(0,R.useCallback)(U=>{if(de.current)return;let V=U.gateway||!tt?U:{...U,gateway:tt};w(V)},[w,tt]);(0,R.useEffect)(()=>{se({class:"lifecycle",name:"checkout.mount"})},[se]);let[Tt,Pt]=(0,R.useState)(e??""),Je=e??Tt,Ye=n?"":Je,[jt,Lt]=(0,R.useState)(!0),[At,dn]=(0,R.useState)(null),[_n,zn]=(0,R.useState)("full"),[Jt,xn]=(0,R.useState)(!1),[Ht,nt]=(0,R.useState)(ke),[un,je]=(0,R.useState)(null),[Un,it]=(0,R.useState)(null),[cr,Nt]=(0,R.useState)(!1),[Vt,pn]=(0,R.useState)(void 0),[rn,mn]=(0,R.useState)(""),[Bt,dr]=(0,R.useState)(!1),[Ot,ue]=(0,R.useState)(!1),[ur,yn]=(0,R.useState)(!1),Xt=(0,R.useRef)(0),qn=(0,R.useRef)(void 0),[fn,Wn]=(0,R.useState)("loading"),[gn,h]=(0,R.useState)(0),ht=(0,R.useRef)(!1),Kt=(0,R.useRef)(!1),Gn=(0,R.useRef)(!1),Ue=(0,R.useRef)(null),wt=(0,R.useMemo)(()=>({checkoutMode:x??_n,layout:Ce?"unknown":pe==="buttons"?"buttons":"embedded"}),[x,Ce,_n,pe]),ct=(0,R.useRef)(g);ct.current=g;let Yt=(0,R.useRef)(b);Yt.current=b;let Jn=(0,R.useRef)(N);Jn.current=N,(0,R.useEffect)(()=>{Dt(H)?.setCheckoutContext(wt),M&&M!==H&&Dt(M)?.setCheckoutContext(wt)},[H,M,wt]);let pr=(0,R.useRef)(fe);pr.current=fe;let Xn=(0,R.useCallback)(U=>{Wn(U),!(U!=="exhausted"||Gn.current)&&(Gn.current=!0,Yt.current?.(new Pe.FloPayError("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),br=(0,R.useCallback)(()=>{Wn("retrying"),h(U=>U+1)},[]);(0,R.useEffect)(()=>{Wn("loading"),h(0),Gn.current=!1},[Je]),(0,R.useEffect)(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:Pe.SDK_VERSION,checkout_type:ot,checkout_layout:Le,billing_api_url:te})},[Le,ot,te]);let hn=(0,R.useMemo)(()=>n?Co(n,!0):"",[n]),Zn=(0,R.useMemo)(()=>rn===hn?Vt:void 0,[Vt,rn,hn]),$n=(0,R.useMemo)(()=>n?Ia(n,Zn):void 0,[n,Zn]),Zt=x??$n?.checkoutMode??"full",bt=(0,R.useMemo)(()=>$n?{...$n,checkoutMode:Zt}:void 0,[$n,Zt]);(0,R.useEffect)(()=>{pn(void 0),mn(hn),qn.current=void 0,yn(!1)},[hn]),(0,R.useEffect)(()=>{nt(ke)},[ke]);let Tn=(0,R.useCallback)((U,V,Y)=>{Ke(()=>{Jn.current?.(Ft(U,V,Y))})},[Ke]),on=(0,R.useCallback)(async(U,V)=>{nt(null),it(null),Nt(!1),je("processing");let Y=V?.sessionId??U.id,le=U.gateways?.stripe?"stripe":U.gateways?.paypal?"paypal":void 0,Ae=He.current??L.current,y=Dt(Ae),d=Ae?null:ra(te,o,wt),m={log:k=>{y?y.log(k):d?.log(k)},error:k=>{y?y.error(k):d?.error(k)},terminal:k=>{y?y.terminal(k):d?.terminal(k)},performance:k=>{y?y.performance(k):d?.performance(k)},now:()=>y?.now()??d?.now()??0,elapsed:k=>y?.elapsed(k)??Math.max(0,(d?.now()??k)-k)},T=m.now(),A=!!(V?.initialAutoProcessingError||V?.initialAutoProcessingPending),me=!1,Xe,Q=()=>{me||(me=!0,A=!0,Xe=m.now(),m.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),m.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},ne=!1,Se=()=>{ne||(ne=!0,m.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),m.performance({stage:"processing",durationMs:m.elapsed(T),durationMode:"machine",paymentMethodCategory:"saved"}),Xe!==void 0&&m.performance({stage:"recovery",durationMs:m.elapsed(Xe),durationMode:"machine",paymentMethodCategory:"saved"}))};m.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),de.current=!0;try{m.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"})}finally{de.current=!1}se({class:"lifecycle",name:"payment.processing.started",provider:le}),A&&Q();let z;try{let k=Wi(V?.initialAutoProcessingError),W;if(k)Q(),k.type==="paypal_redirect_required"&&Ue.current?.publishableKey&&fs({sessionId:Y,publishableKey:Ue.current.publishableKey,paypalPublishableKey:Ue.current.paypalPublishableKey}),W=await Wo(k,{flopay:He.current,paypalFlopay:L.current,attempt3DS:V?.attempt3DS,billingApiUrl:te,sessionId:Y,session:U,telemetry:!1}),k.type==="paypal_redirect_required"&&$a();else if(V?.initialAutoProcessingPending){let Ve=(await new Er.PaymentAPI(te,{telemetry:!1}).waitForCheckoutSessionCompletion(V.initialAutoProcessingPending.sessionId,{initialDelayMs:V.initialAutoProcessingPending.retryAfterMs})).data.session;if(!Or(Ve))throw Oo(Ve);W=wr(Ve,Y)}else{if(V?.initialAutoProcessingError)throw hr(V.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:V.initialAutoProcessingError.checkoutMethod});if(V?.fromCreateSession)return V?.fallbackToFull&&(zn("full"),gs("full")),!1;{let F=await Hr({billingApiUrl:te,sessionId:Y,session:U,telemetry:!1});F.type==="success"?W=F.result:(Q(),F.type==="paypal_redirect_required"&&Ue.current?.publishableKey&&fs({sessionId:Y,publishableKey:Ue.current.publishableKey,paypalPublishableKey:Ue.current.paypalPublishableKey}),W=await Wo(F,{flopay:He.current,paypalFlopay:L.current,attempt3DS:V?.attempt3DS,billingApiUrl:te,sessionId:Y,session:U,telemetry:!1}),F.type==="paypal_redirect_required"&&$a())}}Y&&Vr(Y),Se(),A&&(m.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),m.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),m.terminal({outcome:W.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),Nt(W.status==="authorized"),je("success"),await vo(1200),z=()=>ct.current?.(W)}catch(k){let W=Rr(k),F=W.checkoutMethod??ho;nt(W.message),it(W.message),Nt(!1),V?.fallbackToFull&&(m.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),zn("full"),gs("full")),Se();let ee=W.statusCode!==void 0?(0,Pe.telemetryStatusClass)(W.statusCode,"unknown"):void 0,Ve=ee==="4xx"?{requestCategory:"process_payment",statusClass:ee}:{},vr=ee===void 0||ee==="4xx";if(vr&&(W.telemetryOutcome==="payment_declined"||!!(W.declineCode||W.code?.toLowerCase().includes("declin"))))m.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...Ve});else if(vr&&(W.telemetryOutcome==="validation_rejected"||W.type==="validation_error"))m.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...Ve});else{let ve=(0,Pe.classifyTelemetryFailure)(k,A?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown"),sn=W.telemetryRequestCategory??"process_payment";de.current=!0;try{m.error({...ve,...W.telemetryFailureCategory?{failureCategory:W.telemetryFailureCategory}:{},stage:A?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:sn})}finally{de.current=!1}se({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:sn,provider:le})}return Ke(()=>Yt.current?.(W)),Tn(F,W,{code:W.code,declineCode:W.declineCode}),je("error"),await Promise.allSettled([vo(1500),V?.ensureProvidersReady?V.ensureProvidersReady():Promise.resolve()]),A&&(m.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),m.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{Se(),d&&Po(d),je(null),it(null)}return Ke(z),!0},[Tn,se,Ke,Rr,te,o,wt]);(0,R.useEffect)(()=>{if(typeof window>"u"||Kt.current)return;let U=new URLSearchParams(window.location.search),V=U.get("payment_intent_client_secret");if(!V)return;let Y=Dl();Y&&(Kt.current=!0,(async()=>{let le,Ae=0;nt(null),it(null),je("processing"),xn(!0);try{if(U.get("redirect_status")==="failed")throw Object.assign(new Pe.FloPayError("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:y,paypalFlopay:d}=await Jo({publishableKey:Y.publishableKey,paypalPublishableKey:Y.paypalPublishableKey,billingApiUrl:te,locale:u,telemetry:o});le=Dt(d??y),Ae=le?.now()??0,le?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),le?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let m=(d??y)?.getRawProvider();if(!m)throw Object.assign(new Pe.FloPayError("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:T,error:A}=await m.retrievePaymentIntent(V);if(A)throw Object.assign(new Pe.FloPayError(A.message??"Failed to retrieve PayPal payment status.","api_error",{code:A.code}),{checkoutMethod:"paypal"});let me=Fi(T?.status);if(!T||me==="failed")throw Object.assign(new Pe.FloPayError("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let Xe=typeof T.payment_method=="string"?T.payment_method:T.payment_method?.id,Q=me;if(Y.sessionId){let z=(await new Er.PaymentAPI(te,{telemetry:!1}).getUnifiedCheckoutSession(Y.sessionId)).data.session;if(z&&z.status!=="complete"){let k=await Hr({billingApiUrl:te,sessionId:Y.sessionId,session:z,telemetry:!1,tokenizedData:{id:Xe??T.id,type:"card",threeDSecureActionResultTokenId:T.id,isPaypal:!0}});if(k.type!=="success")throw Object.assign(new Pe.FloPayError("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});Q=k.result.status}}Y.sessionId&&Vr(Y.sessionId),le?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),le?.performance({stage:"redirect_resume",durationMs:le.elapsed(Ae),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),le?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),je("success"),await vo(1200),Ke(()=>ct.current?.({status:Q,paymentIntentId:T.id,paymentMethodId:Xe,checkoutMethod:"paypal"}))}catch(y){let d=Rr(y),m=d.checkoutMethod??"paypal",T=!!(d.declineCode||d.code?.toLowerCase().includes("declin"));if(le)le.performance({stage:"redirect_resume",durationMs:le.elapsed(Ae),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),T?le.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):le.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(T){let A=ra(te,o,wt);A.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),Po(A)}else Ua(te,o,wt,"REDIRECT_RESUME_FAILED","redirect_resume");nt(d.message),it(d.message),Ke(()=>Yt.current?.(d)),Tn(m,d,{code:d.code,declineCode:d.declineCode}),je("error"),await vo(1500)}finally{$a(),Ll(),je(null),it(null),xn(!1)}})())},[Tn,Ke,u,Rr,te,o]);let Qt=(0,R.useRef)(null),en=(0,R.useMemo)(()=>bt?Co(bt):"",[bt]),st=(0,R.useRef)(bt);st.current=bt,(0,R.useEffect)(()=>{Pt(e??"")},[e]),(0,R.useEffect)(()=>{ht.current=!1,nt(ke),it(null),Nt(!1),je(null)},[en,ke,e]);async function Qn(U,V,Y){let le=ra(te,o,wt),Ae=new Er.PaymentAPI(te,{telemetry:!1}),y=!1;try{let d=U.idempotencyKey!==void 0?(0,Pe.resolveIdempotencyKey)(U.idempotencyKey):void 0,m=hs(V,Y),T=bs(V,Y);m?.canonicalIdentity===Y&&T&&T.canonicalIdentity===void 0&&(Va(V,Y,T.idempotencyKey),T={...T,canonicalIdentity:Y});let A=d??(T?.canonicalIdentity===Y?T.idempotencyKey:void 0),me,Xe=!1;le.log({name:m?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let Q=m?.sid??null,ne=null,Se,z,k=!1;if(Q)try{ne=await Ae.getUnifiedCheckoutSession(Q,m?.nonce),m&&m.canonicalIdentity===void 0&&(zl(ne.data.session,U)?(ja(V,Y,Q,m.nonce??ne.data.session?.clientSecret),T&&T.canonicalIdentity===void 0&&(Va(V,Y,T.idempotencyKey),A??(A=T.idempotencyKey))):(Ka(V,Y),T=null,A=d,Q=null,ne=null));let F=ne?.data.session?.status,ee=ne?.data.session,Ve=ee?.clientSecret||m?.nonce;if(Q&&ee?.buyerIdentified===!1&&Ve&&(z=Nr(Ae,Q,Ve,U.account)),Q&&ne&&F==="complete"){if(Ta(Q))return{sid:Q,result:ne};Ka(V,Y),Q=null,ne=null,Xe=!0}}catch{le.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),m?.canonicalIdentity===void 0?(Ka(V,Y),A=d):Wa(V,Y),Q=null}if(!Q){!d&&(Xe||!A)&&(A=(0,Pe.resolveIdempotencyKey)(),me=A),A&&Va(V,Y,A);let F=le.now(),ee=0;le.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let Ve={...U,idempotencyKey:A,avsCheck:!!oe,avsConfig:typeof oe=="object"?oe:void 0,checkoutType:"embedded_checkout",checkoutLayout:Ce?"custom_layout":pe==="buttons"?"buttons_layout":"default_layout"};Object.defineProperty(Ve,Er.SESSION_CREATE_TELEMETRY,{configurable:!1,enumerable:!1,value:{onAttempt:dt=>{ee=Math.max(ee,dt)}}});let vr=()=>{le.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:"2xx"}),le.performance({stage:"session_create",durationMs:le.now()-F,durationMode:"machine",requestCategory:"session_create",attempt:ee,statusClass:"2xx"})},lt=dt=>{let ve=(0,Pe.classifyTelemetryFailure)(dt,"CHECKOUT_SESSION_CREATE_FAILED","unknown");le.performance({stage:"session_create",durationMs:le.now()-F,durationMode:"machine",requestCategory:"session_create",attempt:ee,statusClass:ve.statusClass}),dt instanceof Pe.FloPayError&&dt.type==="validation_error"?le.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown"}):ve.statusClass==="4xx"?le.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create",statusClass:"4xx"}):(le.error({...ve,stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create"}),se({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_create"}))};try{if((0,Pe.isDetachedSessionEligible)(Ve)){let dt=await Ae.createDetachedSession(Ve);dt.claimed.catch(()=>{}),ne=dt.shell,Q=dt.sessionId,z=dt.claim,Se=dt.claimed.then(ve=>{let sn=ve.data.session?.id??dt.sessionId;return sn&&ja(V,Y,sn,ve.data.session?.clientSecret??dt.nonce),vr(),ve},ve=>{throw Wa(V,Y),lt(ve),ve}).finally(()=>Po(le)),Se.catch(()=>{}),y=!0,le.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),le.performance({stage:"session_shell",durationMs:le.now()-F,durationMode:"machine",requestCategory:"session_create",attempt:ee,statusClass:"2xx",paymentMethodCategory:"card"})}else ne=await Ae.createAndFetchSession(Ve),vr()}catch(dt){throw lt(dt),dt}Q=ne.data.session?.id??Q??"",Q&&!Se&&ja(V,Y,Q,ne.data.session?.clientSecret)}let W=ne?.data.session;return!z&&Q&&W?.buyerIdentified===!1&&W.clientSecret&&(z=Nr(Ae,Q,W.clientSecret,U.account)),{sid:Q??"",result:ne,sdkGeneratedIdempotencyKey:me,...Se?{claimed:Se}:{},...z?{claim:z}:{},...k?{claimRequiresIdentity:!0}:{}}}finally{y||Po(le)}}let An=(0,R.useCallback)(async(U,V)=>{let Y=st.current;if(!Y)throw new Pe.FloPayError("createSession is required to bootstrap checkout.","validation_error");let le=Ia(Y,U),Ae=Co(le),y=Ol(le),d=oa.get(Ae);if(!d){let A={canonicalIdentity:Ae,promise:Qn(le,y,Ae),consumers:0,settled:!1};d=A,oa.set(Ae,A);let me=()=>{A.settled=!0,ys(Ae,A)};A.promise.then(me,me)}d.consumers+=1;let m=!1,T=()=>{m||(m=!0,d.consumers-=1,ys(Ae,d))};V?.(T);try{let A=await d.promise;Qt.current=Ae,U&&(mn(hn),pn(ee=>Ai(ee,U)));let{sid:me,result:Xe,claimed:Q,claim:ne,claimRequiresIdentity:Se}=A;if(qn.current=ne,yn(Se===!0),Z(Xe),Xe.data.session&&et(Xe.data.session),me&&Pt(me),Q){Xt.current+=1;let ee=Xt.current;ue(!0),Q.then(Ve=>{Xt.current===ee&&(Z(Ve),Ve.data.session&&et(Ve.data.session),ue(!1),yn(!1))},Ve=>{Xt.current===ee&&(ue(!1),yn(!1),dn(Ve instanceof Pe.FloPayError?Ve:new Pe.FloPayError(Ve instanceof Error?Ve.message:"Failed to create session","api_error")))})}else Xt.current+=1,ue(!1),yn(!1);let{publishableKey:z,paypalPublishableKey:k}=Go(Xe),{flopay:W,paypalFlopay:F}=await Jo({publishableKey:z,paypalPublishableKey:k,billingApiUrl:te,locale:u,telemetry:o});return He.current=W,Te(W),L.current=F,ie(F),Lt(!1),A}catch(A){throw Qt.current===Ae&&(Qt.current=null),A}finally{V||T()}},[hn,u,te,o,wt]),bn=(0,R.useRef)(on);bn.current=on;let Bn=(0,R.useRef)(An);Bn.current=An;let qe=(0,R.useCallback)(async U=>{if(!Nl(U)||Bt)return{sessionId:Tt,session:E};dr(!0);try{let V=await An(U);return{sessionId:V.sid,session:V.result.data.session??null}}finally{dr(!1)}},[An,Bt,Tt,E]),Mt=(0,R.useCallback)(async U=>{let V=qn.current;if(!V)return;let Y=Xt.current,le=await V(U);Xt.current===Y&&(Z(le),le.data.session&&et(le.data.session))},[]);(0,R.useEffect)(()=>{let U=!1,V;if(dn(null),en){let Ae=st.current;return zn(Zt),Lt(!1),Qt.current===en?()=>{U=!0}:(et(Bi(Ae,x)),(async()=>{let y=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),d=Zt==="auto"&&!ht.current&&!y;d&&(nt(null),it(null),je("processing"));try{let m=await Bn.current(void 0,Xe=>{V=Xe}),T=m.result.data.session??null;Ue.current=Go(m.result);let A=qa(m.result),me=Ta(m.sid||T?.id);if(!U&&d&&T&&!A&&!me){ht.current=!0,await Ml(en,m.sdkGeneratedIdempotencyKey,()=>bn.current(T,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:m.result.autoProcessingError,initialAutoProcessingPending:m.result.autoProcessingPending,autoProcessingAttempted:m.result.autoProcessingAttempted,sessionId:m.sid||T.id}));return}!U&&d&&((A||me)&&(ht.current=!0),je(null),it(null))}catch(m){if(U)return;let T=m instanceof Pe.FloPayError||typeof m=="object"&&m!==null&&"code"in m?m.code:void 0;if(d&&T==="session_auto_completed"){ht.current=!0,je("success"),await vo(1200),U||(Ke(()=>{ct.current?.({status:"succeeded"})}),je(null),it(null));return}d&&(je(null),it(null));let A=m instanceof Pe.FloPayError?m:new Pe.FloPayError(m instanceof Error?m.message:"Failed to create session","api_error");dn(A)}finally{V?.(),V=void 0}})(),()=>{U=!0,V?.()})}Lt(!0);async function Y(){let Ae=!1;try{let y=new Er.PaymentAPI(te,{telemetry:!1}),d=await y.getUnifiedCheckoutSession(Je,t);if(U)return;Z(d);let m=d.data.session??null;if(et(m),!m)throw new Pe.FloPayError("No session data returned","api_error");let T=m.checkoutMode;if(T==="setup")throw new Pe.FloPayError("This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.","validation_error",{code:"InvalidCardSetupSurface",param:"sessionId"});if(m.status==="authorized"){Lt(!1),Ke(()=>{ct.current?.(wr(m,Je)),pr.current?.(m.successUrl??"")});return}if(m.status==="complete"){Lt(!1),Ke(()=>{pr.current?.(m.successUrl??"")});return}if(m.status==="expired")throw No(m);Ae=!0;let A=x??T??"full";zn(A),Xt.current+=1;let me=m.clientSecret||t;qn.current=m.buyerIdentified===!1&&me?Nr(y,Je,me,{...m.customer?.id?{userId:m.customer.id}:{}}):void 0,ue(!1),yn(!1);let Xe=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),Q=qa(d);if(A==="auto"&&!ht.current&&!Xe&&!Q){ht.current=!0;let ne=le(d);try{if(await bn.current(m,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>ne,sessionId:Je||m.id}),U)return;await ne,U||Lt(!1);return}catch{if(U)return;await ne,U||Lt(!1);return}}await le(d),U||Lt(!1)}catch(y){if(U)return;Ae&&se({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"}),y instanceof Pe.FloPayError?!Ae&&!Fl(y)&&Ua(te,o,wt,"NETWORK_REQUEST_FAILED","session_read"):Ua(te,o,wt,"INTERNAL_SDK_ERROR","checkout_mount");let d=y instanceof Pe.FloPayError?y:new Pe.FloPayError(y instanceof Error?y.message:"Failed to initialize checkout","api_error");dn(d),Lt(!1)}}async function le(Ae){let{publishableKey:y,paypalPublishableKey:d}=Go(Ae);Ue.current={publishableKey:y,paypalPublishableKey:d};let{flopay:m,paypalFlopay:T}=await Jo({publishableKey:y,paypalPublishableKey:d,billingApiUrl:te,locale:u,telemetry:o});He.current=m,Te(m),L.current=T,ie(T)}return Y(),()=>{U=!0}},[x,en,Zt,Ye,Ke,t]);let Et=(0,R.useCallback)(async()=>{if(!(Jt||!E)){xn(!0),nt(null);try{await on(E,{attempt3DS:!0,fallbackToFull:!0,sessionId:Je||E.id})}finally{xn(!1)}}},[Je,Jt,on,E]),Mn=Ya(ae),mr=qa(ae),er=(0,R.useMemo)(()=>{if(!(!ae||!E||!ae.data.stripe?.publishableKey))return{billingApiUrl:te}},[ae,E,te]),an=!!(n&&!Ce&&pe==="buttons"&&re&&Zt==="full"),zt=(0,R.useMemo)(()=>({session:E,loading:jt,error:At,checkoutMode:_n,inlineSessionDraft:bt,applyInlineSessionPatch:an?qe:void 0,inlineSessionPatchProcessing:Bt,claimPending:Ot,claimRequiresIdentity:ur,claimBuyerIdentity:Mt}),[E,jt,At,_n,bt,an,qe,Bt,Ot,ur,Mt]),vn=!!n&&pe==="buttons"&&!mr&&(!H||!er),_t=un?(0,I.jsx)(Rn,{status:un,errorMessage:Un,authorized:cr}):null;if(jt){if(c)return(0,I.jsxs)(I.Fragment,{children:[c,_t]});if(pe==="buttons"){let U=Fe?.buttonsLayout?.cardButton?.borderRadius??Fe?.appearance.variables?.borderRadius??8,V=Y=>(0,I.jsx)("div",{style:{height:Y,borderRadius:U,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return(0,I.jsxs)(I.Fragment,{children:[(0,I.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[C&&V(_r),ge&&(S||ye)&&V(_r),ge&&V(_r),(0,I.jsx)("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),_t]})}return(0,I.jsxs)(I.Fragment,{children:[(0,I.jsxs)("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[(0,I.jsx)("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),(0,I.jsx)("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),_t]})}return At?P?(0,I.jsx)(Ln.Provider,{value:zt,children:P(At)}):(0,I.jsx)(Ln.Provider,{value:zt,children:(0,I.jsx)("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:At.message})}):vn?(0,I.jsxs)(I.Fragment,{children:[(0,I.jsx)(Ln.Provider,{value:zt,children:(0,I.jsx)(ql,{onButtonClick:Re,showPayPal:C,showStripe:ge,showApplePay:S,showGooglePay:ye,theme:J,buttonsTheme:he,buttonsStyles:ze,cardButtonContent:we,cardBackButtonContent:yt,cardTitleContent:Me})}),_t]}):mr&&E&&Mn?(0,I.jsxs)(I.Fragment,{children:[(0,I.jsx)(Ln.Provider,{value:zt,children:(0,I.jsxs)("div",{className:X,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Ht&&(0,I.jsx)(jr,{icon:!1,children:Ht}),fn==="retrying"&&(0,I.jsx)("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),fn==="exhausted"&&(0,I.jsxs)("div",{role:"alert",children:[(0,I.jsx)("div",{children:"PayPal is temporarily unavailable. Please try again."}),(0,I.jsx)("button",{type:"button",onClick:br,children:"Retry PayPal"})]}),Ot?c??(0,I.jsx)("div",{role:"status","data-testid":"flopay-paypal-catalog-loading","aria-label":"Preparing PayPal",style:{height:_r,borderRadius:8,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"},children:(0,I.jsx)("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})}):fn!=="exhausted"?(0,I.jsx)("div",{"aria-hidden":fn==="retrying"?!0:void 0,style:fn==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:(0,I.jsx)(Ki,{sessionId:Je,nonce:E.clientSecret||void 0,billingApiUrl:te,email:E.customer?.email||bt?.account?.email,billingName:[E.customer?.firstName,E.customer?.lastName].filter(Boolean).join(" ")||[bt?.account?.firstName,bt?.account?.lastName].filter(Boolean).join(" ")||void 0,onBuyerIdentityReady:Mt,clientId:Mn.clientId,environment:Mn.environment,currency:(E.currency??"usd").toUpperCase(),isSubscription:E.mode==="subscription",providerObjectType:Mn.providerObjectType,onComplete:g,onErrorChange:nt,onDecline:N,onButtonClick:Re,onInitializationStateChange:Xn,allowAutomaticRetry:gn===0,session:E,telemetry:o,telemetryContext:wt,onInstrument:at,debug:j},`${ce}:paypal-init-${gn}`)}):null]})}),_t]}):!H||!er?(0,I.jsx)(I.Fragment,{children:_t}):_n==="confirm"?(0,I.jsxs)(I.Fragment,{children:[(0,I.jsx)(Ln.Provider,{value:zt,children:(0,I.jsx)(fo,{flopay:H,paypalFlopay:M,options:er,onInstrument:at,children:(0,I.jsxs)("div",{className:X,children:[Ht&&(0,I.jsx)("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:Ht}),xe?xe({onConfirm:Et,isProcessing:Jt}):(0,I.jsx)("button",{type:"button",onClick:Et,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...":q??"Confirm Purchase"})]})},ce)}),_t]}):(0,I.jsxs)(I.Fragment,{children:[(0,I.jsx)(Ln.Provider,{value:zt,children:(0,I.jsx)(fo,{flopay:H,paypalFlopay:M,options:er,onInstrument:at,children:Ce?(0,I.jsxs)(I.Fragment,{children:[Ht&&(0,I.jsx)("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:Ht}),(0,I.jsx)(Ul,{sessionId:Je,nonce:E?.clientSecret||void 0,billingApiUrl:te,session:E,children:Ce})]}):(0,I.jsx)(ta,{sessionId:Je,nonce:E?.clientSecret||void 0,email:E?.customer?.email||bt?.account?.email,userId:E?.customer?.id||bt?.account?.userId,firstName:E?.customer?.firstName||bt?.account?.firstName,lastName:E?.customer?.lastName||bt?.account?.lastName,totalAmount:E?Math.round((0,Pe.buildCheckoutDisplayData)(E).total*100):0,currency:E?.currency?.toLowerCase()??"usd",onComplete:g,onError:b,onDecline:N,error:Ht,onErrorChange:nt,showPayPal:C,showStripe:ge,enabledPaymentMethods:$??ae?.data.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:ae?.data.stripe?.enabledPaymentMethodCountries,showApplePay:S,showGooglePay:ye,layout:pe,theme:J,buttonsTheme:he,buttonsStyles:ze,appearance:Qe,cardButtonContent:we,cardBackButtonContent:yt,cardTitleContent:Me,onButtonClick:Re,onBeforeButtonClick:re,onBuyerIdentityReady:Mt,enableAVS:oe,...O?{cardFieldOrder:O}:{},...Ee?{cardPreFormSlot:Ee}:{},avsLayout:_e,country:E?.customer?.country,city:E?.customer?.city,state:E?.customer?.state,onCountryChange:B,onZipChange:f,avsCheck:!!oe,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:Ce?"custom_layout":pe==="buttons"?"buttons_layout":"default_layout",className:X,directPaypal:Ya(ae),isSubscription:E?.mode==="subscription",session:E,dataAttachmentPending:Ot,dataAttachmentRequiresIdentity:ur,debug:j})},ce)}),_t]})}function Ul({sessionId:e,nonce:t,billingApiUrl:n,session:r,children:o}){return(0,I.jsx)(I.Fragment,{children:R.default.Children.map(o,i=>{if(!R.default.isValidElement(i))return i;let u=i.props,c={};return u.sessionId||(c.sessionId=e),!u.nonce&&t&&(c.nonce=t),u.billingApiUrl||(c.billingApiUrl=n),r?.customer&&(u.email||(c.email=r.customer.email),u.userId||(c.userId=r.customer.id),u.firstName||(c.firstName=r.customer.firstName),u.lastName||(c.lastName=r.customer.lastName)),Object.keys(c).length===0?i:R.default.cloneElement(i,c)})})}function ql({onButtonClick:e,showPayPal:t,showStripe:n=!0,showApplePay:r,showGooglePay:o,theme:i,buttonsTheme:u,buttonsStyles:c,cardButtonContent:P,cardBackButtonContent:g,cardTitleContent:b}){let[v,N]=(0,R.useState)(!1),B=(0,R.useMemo)(()=>(0,Pe.resolveTheme)(i),[i]),f=(0,R.useMemo)(()=>{let S=B?.buttonsLayout??(0,Pe.resolveButtonsLayoutTheme)(u);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,u,c]),C=B?.buttonsLayout?.cardButton?.borderRadius??B?.appearance.variables?.borderRadius??8,ge=S=>(0,I.jsx)("div",{style:{height:S,borderRadius:C,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),$=P===void 0?{boxSizing:"border-box",height:_r,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(v){let S=f.cardInputBorder??"#e5e7eb",ye=f.cardInputBackground??"white",j=Fr(g),pe=Fr(b);return(0,I.jsxs)("div",{style:{backgroundColor:f.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",...f.cardFormContainer},children:[(0,I.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,I.jsxs)("button",{type:"button",onClick:()=>N(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:j?0:"0.5rem",background:"none",border:"none",color:"#4b5563",fontSize:"0.85rem",fontWeight:500,padding:0,flexShrink:0,opacity:1,cursor:"pointer",...f.backButton},children:[(0,I.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...f.backButtonIcon},children:(0,I.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,I.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,I.jsx)(Lr,{content:g})]}),pe?(0,I.jsx)("div",{style:{flex:1}}):(0,I.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...f.title},children:(0,I.jsx)(lo,{content:b})})]}),(0,I.jsx)("div",{style:{backgroundColor:ye,border:`1px solid ${S}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:(0,I.jsx)("div",{style:{width:"60%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,I.jsxs)("div",{style:{display:"flex"},children:[(0,I.jsx)("div",{style:{flex:1,backgroundColor:ye,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${S}`,borderLeft:`1px solid ${S}`,borderBottomLeftRadius:8,padding:12,height:45},children:(0,I.jsx)("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,I.jsx)("div",{style:{flex:1,backgroundColor:ye,borderTop:"none",borderRight:`1px solid ${S}`,borderBottom:`1px solid ${S}`,borderLeft:`1px solid ${S}`,borderBottomRightRadius:8,padding:12,height:45},children:(0,I.jsx)("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),(0,I.jsx)("div",{style:{backgroundColor:ye,border:`1px solid ${S}`,borderRadius:8,marginTop:8,padding:12,height:45},children:(0,I.jsx)("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,I.jsx)("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",...f.submitButton,opacity:.5}}),(0,I.jsx)("style",{children:`
38
+ `}),oo&&On&&(0,l.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:Je?-2:0},children:[(0,l.jsxs)("button",{type:"button",onClick:_n,style:{display:"inline-flex",alignItems:"center",gap:Ca?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:m.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...m.backButton},"aria-label":"Back to payment methods",children:[(0,l.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...m.backButtonIcon},children:(0,l.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,l.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,l.jsx)(Or,{content:xe})]}),Si?(0,l.jsx)("div",{style:{flex:1}}):(0,l.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:m.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...m.title},children:(0,l.jsx)(uo,{content:Te})})]}),!oo&&!Si&&(0,l.jsx)("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:Sa,order:Je?-3:0,...m.title},children:(0,l.jsx)(uo,{content:Te})}),Je&&Ie&&(0,l.jsx)("div",{style:{order:-2,width:"100%"},children:Ie}),Je&&mt&&(0,l.jsxs)("div",{"data-testid":"flopay-vault-identity-fields",style:{order:-1,marginTop:"0.5rem"},children:[(0,l.jsx)("div",{style:{backgroundColor:Fr,border:`1px solid ${Tn(Do)}`,borderRadius:_t,padding:"10px"},children:(0,l.jsx)("input",{className:"flopay-shared-input",id:"flopay-buyer-email",name:"email",type:"email",autoComplete:"email","aria-label":"Email address",placeholder:"Email address",value:tt,onChange:s=>{st("email"),Qn.current=s.target.value,ur(s.target.value)},onPointerDown:()=>st("email"),onKeyDown:()=>st("email"),onBlur:()=>{mn("email")&&un(!0),Lt||pa()},disabled:se,required:!0,"aria-invalid":Do||void 0,"aria-describedby":Do?"flopay-buyer-email-error":void 0,"data-testid":"flopay-email",style:{width:"100%",border:"none",outline:"none",background:"transparent",...wa}})}),Do&&(0,l.jsx)("div",{id:"flopay-buyer-email-error",role:"alert","data-testid":"flopay-email-error",style:io,children:We.empty?"Email address is required":"Enter a valid email address"})]}),le&&(0,l.jsx)("div",{style:{order:Je?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let s=Ye,_=(Y=!1)=>({backgroundColor:Fr,border:`1px solid ${Tn(Y)}`,borderRadius:_t,marginTop:"0.5rem",padding:"10px"}),K=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...wa}),Ue=(0,u.getStateOptions)(s);return(0,l.jsxs)(l.Fragment,{children:[(0,u.isAVSFieldVisible)(le.address_line_1,s)&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)("div",{style:_(wt("line1")),children:(0,l.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:Ln,onChange:Y=>{st("line1"),Mt.current.addressLine1=!0,ln.current=Y.target.value,tn(Y.target.value)},onPointerDown:()=>st("line1"),onKeyDown:()=>st("line1"),onBlur:()=>yn("line1"),disabled:se,required:!0,"aria-invalid":wt("line1")||void 0,"aria-describedby":wt("line1")?"flopay-billing-address-line1-error":void 0,"data-testid":"flopay-address-line1",style:K()})}),wt("line1")&&(0,l.jsx)("div",{id:"flopay-billing-address-line1-error",role:"alert","data-testid":"flopay-address-line1-error",style:io,children:"Street address is required"})]}),(0,u.isAVSFieldVisible)(le.address_line_2,s)&&(0,l.jsx)("div",{style:_(),children:(0,l.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:Kn,onChange:Y=>{Mt.current.addressLine2=!0,wn.current=Y.target.value,sn(Y.target.value)},disabled:se,"data-testid":"flopay-address-line2",style:K()})}),((0,u.isAVSFieldVisible)(le.city,s)||(0,u.isAVSFieldVisible)(le.state,s))&&(0,l.jsxs)("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[(0,u.isAVSFieldVisible)(le.city,s)&&(0,l.jsx)("div",{style:{flex:1,backgroundColor:Fr,borderTop:`1px solid ${Tn(wt("city"))}`,borderRight:`1px solid ${Tn(wt("city"))}`,borderBottom:`1px solid ${Tn(wt("city"))}`,borderLeft:`1px solid ${Tn(wt("city"))}`,padding:"10px",borderTopLeftRadius:_t,borderBottomLeftRadius:_t,...(0,u.isAVSFieldVisible)(le.state,s)?{borderRight:"none",borderTopRightRadius:0,borderBottomRightRadius:0}:{borderRadius:_t}},children:(0,l.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-city",name:"billing-city",placeholder:"City",autoComplete:"billing address-level2",value:Cn,onChange:Y=>{st("city"),Mt.current.city=!0,kn.current=Y.target.value,nn(Y.target.value)},onPointerDown:()=>st("city"),onKeyDown:()=>st("city"),onBlur:()=>yn("city"),disabled:se,required:!0,"aria-invalid":wt("city")||void 0,"aria-describedby":wt("city")?"flopay-billing-city-error":void 0,"data-testid":"flopay-city",style:K()})}),(0,u.isAVSFieldVisible)(le.state,s)&&(0,l.jsx)("div",{style:{flex:1,backgroundColor:Fr,borderTop:`1px solid ${Tn(wt("state"))}`,borderRight:`1px solid ${Tn(wt("state"))}`,borderBottom:`1px solid ${Tn(wt("state"))}`,borderLeft:`1px solid ${Tn(wt("state"))}`,padding:"10px",borderTopRightRadius:_t,borderBottomRightRadius:_t,...(0,u.isAVSFieldVisible)(le.city,s)?{borderTopLeftRadius:0,borderBottomLeftRadius:0,borderLeft:`1px solid ${Tn(wt("state")||wt("city"))}`}:{borderRadius:_t}},children:Ue?(0,l.jsxs)("select",{id:"flopay-billing-state",name:"billing-state",value:Ot,onChange:Y=>{st("state"),Mt.current.state=!0,Jt.current=Y.target.value,Sn(Y.target.value)},onPointerDown:()=>st("state"),onKeyDown:()=>st("state"),onBlur:()=>yn("state"),disabled:se,autoComplete:"billing address-level1",required:!0,"aria-invalid":wt("state")||void 0,"aria-describedby":wt("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:{...K(),cursor:"pointer"},children:[(0,l.jsx)("option",{value:"",children:(0,u.getStateLabel)(s)}),Ue.map(Y=>(0,l.jsx)("option",{value:Y.code,children:Y.name},Y.code))]}):(0,l.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-state",name:"billing-state",placeholder:(0,u.getStateLabel)(s),autoComplete:"billing address-level1",value:Ot,onChange:Y=>{st("state"),Mt.current.state=!0,Jt.current=Y.target.value,Sn(Y.target.value)},onPointerDown:()=>st("state"),onKeyDown:()=>st("state"),onBlur:()=>yn("state"),disabled:se,required:!0,"aria-invalid":wt("state")||void 0,"aria-describedby":wt("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:K()})})]}),wt("city")&&(0,l.jsx)("div",{id:"flopay-billing-city-error",role:"alert","data-testid":"flopay-city-error",style:io,children:"City is required"}),wt("state")&&(0,l.jsxs)("div",{id:"flopay-billing-state-error",role:"alert","data-testid":"flopay-state-error",style:io,children:[(0,u.getStateLabel)(s)," is required"]}),((0,u.isAVSFieldVisible)(le.country,s)||(0,u.isAVSFieldVisible)(le.postal_code,s))&&(0,l.jsxs)("div",{style:{display:"flex",flexDirection:Se==="column"?"column":"row",gap:Se==="column"?"0.5rem":"0",marginTop:"0.5rem"},children:[(0,u.isAVSFieldVisible)(le.country,s)&&(0,l.jsx)("div",{style:{flex:Se==="row"?1:void 0,backgroundColor:Fr,borderTop:`1px solid ${ao}`,borderRight:`1px solid ${ao}`,borderBottom:`1px solid ${ao}`,borderLeft:`1px solid ${ao}`,padding:"10px",...Se==="row"&&(0,u.isAVSFieldVisible)(le.postal_code,s)?{borderRadius:"0",borderTopLeftRadius:_t,borderBottomLeftRadius:_t,borderRight:"none"}:{borderRadius:_t}},children:(0,l.jsx)("select",{id:"flopay-billing-country",name:"billing-country",value:Ye,onChange:Y=>{Mt.current.country=!0,jt.current=Y.target.value,Nt(Y.target.value),rt?.(Y.target.value),Jt.current="",Sn("")},disabled:se,autoComplete:"billing country","data-testid":"flopay-country",style:{...K(),cursor:"pointer"},children:u.COUNTRY_OPTIONS.map(Y=>(0,l.jsxs)("option",{value:Y.code,children:[Y.flag," ",Y.name]},Y.code))})}),(0,u.isAVSFieldVisible)(le.postal_code,s)&&(0,l.jsx)("div",{style:{flex:Se==="row"?1:void 0,backgroundColor:Fr,border:`1px solid ${Ns}`,padding:"10px",...Se==="row"&&(0,u.isAVSFieldVisible)(le.country,s)?{borderRadius:"0",borderTopRightRadius:_t,borderBottomRightRadius:_t}:{borderRadius:_t}},children:(0,l.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-postal-code",name:"billing-postal-code",placeholder:(0,u.getPostalCodeLabel)(Ye),autoComplete:"billing postal-code",value:$t,onChange:Y=>{st("zip"),Mt.current.zip=!0,ft.current=Y.target.value,Yt(Y.target.value),pt?.(Y.target.value)},onPointerDown:()=>st("zip"),onKeyDown:()=>st("zip"),onBlur:()=>{mn("zip")&&Cr(!0)},disabled:se,required:Wt.required,"aria-invalid":Lo||void 0,"aria-describedby":Lo?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:K()})})]}),Lo&&(0,l.jsx)("div",{id:"flopay-billing-postal-code-error",role:"alert","data-testid":"flopay-zip-error",style:io,children:Wt.empty?`${(0,u.getPostalCodeLabel)(s)} is required`:El(s)})]})})()}),Je&&$s,R&&(0,l.jsx)(Kr,{margin:"0.75rem 0",styleOverride:m.errorBanner,children:R})]}),No={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"},Ei=s=>Pt?!he||!Gn?(0,l.jsx)("pre",{"data-testid":s,style:No,children:"FloPay/DirectPayPal-debug - not enabled"}):(0,l.jsx)("pre",{"data-testid":s,style:No,children:["FloPay/DirectPayPal-debug (parent gate)",` showPayPal=${he}`,` directPaypalConfigured=${Gn}`,` inAppBrowserDetected=${String(Bo)}`,` shouldRenderDirectPayPal=${eo}`,` shouldRenderStripePayPal=${to}`,` hasPaypalStripeInstance=${!!Ar}`].join(`
39
+ `)}):null,_i=s=>Pt?!q||!bn?(0,l.jsx)("pre",{"data-testid":s,style:No,children:"FloPay/Stripe-debug - not enabled"}):(0,l.jsx)("pre",{"data-testid":s,style:No,children:["FloPay/Stripe-debug (parent gate)",` showStripe=${q}`,` currency=${Fe}`,` amountInCents=${Xr}`,` enabledPaymentMethods: ${JSON.stringify(S??[])}`,` enabledPaymentMethodsProvided=${Zr}`,` hasEnabledMethods=${xo}`,` expressMethods: ${JSON.stringify(To)}`,` walletExpressMethods: ${JSON.stringify(Mo)}`,` paymentElementMethods: ${JSON.stringify(Qr)}`,` paymentElementMethodsForCurrency: ${JSON.stringify(Ao)}`,` hasStripeInstance=${!!bn}`,` shouldRenderWallets=${no}`,` shouldRenderPaymentElement=${ro}`].join(`
40
+ `)}):null,xi=Ne==="apm-expanding"||Ne==="apm-form"||Ne==="apm-collapsing",Oo=Ne==="apm-expanding"?`flopay-card-enter ${_r}ms cubic-bezier(0, 0, 0.2, 1) both`:Ne==="apm-collapsing"?`flopay-card-exit ${_r}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0,zo=Bt?{...fa,paymentMethodTypes:[Bt]}:null;if(W==="buttons"){let s=Ne==="buttons"||Ne==="expanding"||Ne==="apm-expanding",_=Ne==="expanding"||Ne==="card"||Ne==="collapsing",K=$e===void 0?{boxSizing:"border-box",height:ta,padding:"0 1rem"}:{padding:"0.9rem 1rem"},Ue=Ne==="expanding"||Ne==="apm-expanding"?`flopay-buttons-exit ${_r}ms cubic-bezier(0.4, 0, 0.2, 1) both`:Ne==="collapsing"||Ne==="apm-collapsing"?`flopay-buttons-enter ${_r}ms cubic-bezier(0, 0, 0.2, 1) both`:void 0,Y=Ne==="expanding"?`flopay-card-enter ${_r}ms cubic-bezier(0, 0, 0.2, 1) both`:Ne==="collapsing"?`flopay-card-exit ${_r}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0;return(0,l.jsxs)("form",{onSubmit:ba,className:B,noValidate:!0,style:{position:"relative"},children:[(0,l.jsx)(La,{}),Q&&(0,l.jsx)(Fn,{status:Q,errorMessage:R,authorized:cn}),(0,l.jsxs)("div",{style:{display:"grid"},children:[(0,l.jsxs)("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!s&&!Ue?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!s&&!Ue?kl:{},...Ue?{animation:Ue,pointerEvents:"none"}:{}},children:[Ei("flopay-direct-paypal-gate-debug"),_i("flopay-stripe-gate-debug"),eo&&M&&(0,l.jsxs)(l.Fragment,{children:[h&&(0,l.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,l.jsx)(go,{sessionId:e,nonce:t,billingApiUrl:Oe,email:j.email,billingName:V||void 0,onBuyerIdentityReady:Re,clientId:M.clientId,environment:M.environment,currency:Fe.toUpperCase(),isSubscription:oe,providerObjectType:M.providerObjectType,onTokenizedBody:xn,onComplete:i,onErrorChange:Pe,onDecline:c,onTechnicalFailure:Br,onButtonClick:re,runBeforeButtonClick:qn,isProcessing:se,onLoadStateChange:ga,onInitializationStateChange:ha,session:D??null,existingOrderId:h?.orderId,debug:Pt},h?.orderId??"fresh")]}),to&&(0,l.jsx)(Tt.Elements,{stripe:Ar,options:ei,children:(0,l.jsx)(is,{sessionId:e,nonce:t,email:j.email,billingName:V||void 0,onBuyerIdentityReady:Re,billingApiUrl:Oe,onTokenizedBody:xn,onErrorChange:Pe,isProcessing:se,onButtonClick:re,onDecline:c,onTechnicalFailure:Br,runBeforeButtonClick:qn,onLoadStateChange:ii,placeholderBorderRadius:Sr})}),no?(0,l.jsx)(Tt.Elements,{stripe:bn,options:Qa,children:(0,l.jsx)(ss,{sessionId:e,nonce:t,email:j.email,billingName:V||void 0,onBuyerIdentityReady:Re,billingApiUrl:Oe,intentKind:H>0?"payment":"setup",expressMethods:Mo,onTokenizedBody:xn,onErrorChange:Pe,onButtonClick:re,onDecline:c,onTechnicalFailure:Br,runBeforeButtonClick:qn,onLoadStateChange:li,placeholderBorderRadius:Sr})}):mi?(0,l.jsx)("div",{style:{height:ta,borderRadius:Sr,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,ro&&(0,l.jsx)(ls,{sessionId:e,nonce:t,email:j.email,billingName:[j.firstName,j.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:Re,billingApiUrl:Oe,paymentElementMethods:Ao,stripeInstance:bn,paymentElementBaseOptions:fa,onTokenizedBody:xn,onErrorChange:Pe,onButtonClick:re,onDecline:c,runBeforeButtonClick:qn,onLoadStateChange:di,isProcessing:se,submitButtonColor:wr,submitButtonBorderRadius:_t,submitButtonStyle:m.submitButton,onExpandApm:O,expandedApmMethod:Bt,themeId:be,buttonAppearance:{backgroundColor:m.cardButton?.backgroundColor,borderColor:m.cardInputBorder,textColor:m.cardButton?.color,borderRadius:Sr}}),Je&&(0,l.jsx)("button",{type:"button",onClick:async()=>{se||!(await qn("card")).proceed||(re?.("card"),Mr())},disabled:se,style:{width:"100%",...K,...m.cardButton,...Ua({themeBundle:f,resolvedPrimaryColor:wr,resolvedBorderRadius:_t,submitButtonStyle:m.submitButton,explicitPrimaryColor:on?.colorPrimary}),fontSize:m.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:se?"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:se?.6:1},onMouseEnter:De=>{!se&&(f||on?.colorPrimary)&&(De.currentTarget.style.backgroundColor=Us)},onMouseLeave:De=>{(f||on?.colorPrimary)&&(De.currentTarget.style.backgroundColor=wr)},onMouseDown:De=>{De.currentTarget.style.transform="scale(0.985)"},onMouseUp:De=>{De.currentTarget.style.transform="scale(1)"},children:(0,l.jsx)(Nr,{content:$e})}),R&&Ne==="buttons"&&(0,l.jsx)(Kr,{margin:"0.25rem 0",styleOverride:m.errorBanner,children:R})]}),Je&&_&&(0,l.jsx)("div",{style:{gridArea:"1 / 1",...Y?{animation:Y}:{},...Ne==="collapsing"?{pointerEvents:"none"}:{}},children:Ri}),q&&xi&&Bt&&zo&&bn&&(0,l.jsx)("div",{style:{gridArea:"1 / 1",...Oo?{animation:Oo}:{},...Ne==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,l.jsxs)("div",{style:{backgroundColor:Pa,borderRadius:Ia,...so,padding:ka},children:[(0,l.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,l.jsxs)("button",{type:"button","data-testid":"flopay-apm-back-button",onClick:z,style:{display:"inline-flex",alignItems:"center",gap:Ca?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:m.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...m.backButton},"aria-label":"Back to payment methods",children:[(0,l.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...m.backButtonIcon},children:(0,l.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,l.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,l.jsx)(Or,{content:xe})]}),(0,l.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:m.titleFontSize??"1.05rem",color:Sa,paddingRight:80,...m.title},children:`Pay with ${(0,u.getStripeMethodDisplayName)(Bt)}`})]}),(0,l.jsx)(Tt.Elements,{stripe:bn,options:zo,children:(0,l.jsx)(Oa,{method:Bt,sessionId:e,nonce:t,email:j.email,billingName:[j.firstName,j.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:Re,billingApiUrl:Oe,onTokenizedBody:xn,onErrorChange:Pe,onDecline:c,onCancel:z,runBeforeButtonClick:qn,onButtonClick:re,isProcessing:se,submitButtonColor:wr,submitButtonBorderRadius:_t,submitButtonStyle:m.submitButton,errorText:R})},Bt)]})})]})]})}return xi&&Bt&&zo&&bn&&q?(0,l.jsxs)("form",{onSubmit:ba,className:B,noValidate:!0,style:{position:"relative"},children:[(0,l.jsx)(La,{}),Q&&(0,l.jsx)(Fn,{status:Q,errorMessage:R,authorized:cn}),(0,l.jsx)("div",{style:{...Oo?{animation:Oo}:{},...Ne==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,l.jsxs)("div",{style:{backgroundColor:Pa,borderRadius:Ia,...so,padding:ka},children:[(0,l.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,l.jsxs)("button",{type:"button","data-testid":"flopay-apm-back-button-default",onClick:z,style:{display:"inline-flex",alignItems:"center",gap:Ca?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:m.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...m.backButton},"aria-label":"Back to payment methods",children:[(0,l.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...m.backButtonIcon},children:(0,l.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,l.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,l.jsx)(Or,{content:xe})]}),(0,l.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:m.titleFontSize??"1.05rem",color:Sa,paddingRight:80,...m.title},children:`Pay with ${(0,u.getStripeMethodDisplayName)(Bt)}`})]}),(0,l.jsx)(Tt.Elements,{stripe:bn,options:zo,children:(0,l.jsx)(Oa,{method:Bt,sessionId:e,nonce:t,email:j.email,billingName:[j.firstName,j.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:Re,billingApiUrl:Oe,onTokenizedBody:xn,onErrorChange:Pe,onDecline:c,onCancel:z,runBeforeButtonClick:qn,onButtonClick:re,isProcessing:se,submitButtonColor:wr,submitButtonBorderRadius:_t,submitButtonStyle:m.submitButton,errorText:R})},Bt)]})})]}):(0,l.jsxs)("form",{onSubmit:ba,className:B,noValidate:!0,style:{position:"relative"},children:[(0,l.jsx)(La,{}),Q&&(0,l.jsx)(Fn,{status:Q,errorMessage:R,authorized:cn}),(0,l.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Ei("flopay-direct-paypal-gate-debug-default"),_i("flopay-stripe-gate-debug-default"),eo&&M&&(0,l.jsxs)(l.Fragment,{children:[h&&(0,l.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,l.jsx)(go,{sessionId:e,nonce:t,billingApiUrl:Oe,email:j.email,billingName:V||void 0,onBuyerIdentityReady:Re,clientId:M.clientId,environment:M.environment,currency:Fe.toUpperCase(),isSubscription:oe,providerObjectType:M.providerObjectType,onTokenizedBody:xn,onComplete:i,onErrorChange:Pe,onDecline:c,onTechnicalFailure:Br,onButtonClick:re,runBeforeButtonClick:qn,isProcessing:se,onLoadStateChange:ga,onInitializationStateChange:ha,session:D??null,existingOrderId:h?.orderId,debug:Pt},h?.orderId??"fresh")]}),to&&(0,l.jsx)(Tt.Elements,{stripe:Ar,options:ei,children:(0,l.jsx)(is,{sessionId:e,nonce:t,email:j.email,billingName:V||void 0,onBuyerIdentityReady:Re,billingApiUrl:Oe,onTokenizedBody:xn,onErrorChange:Pe,isProcessing:se,onButtonClick:re,onDecline:c,onTechnicalFailure:Br,runBeforeButtonClick:qn,onLoadStateChange:ii,placeholderBorderRadius:Sr})}),no&&(0,l.jsx)(Tt.Elements,{stripe:bn,options:Qa,children:(0,l.jsx)(ss,{sessionId:e,nonce:t,email:j.email,billingName:V||void 0,onBuyerIdentityReady:Re,billingApiUrl:Oe,intentKind:H>0?"payment":"setup",expressMethods:Mo,onTokenizedBody:xn,onErrorChange:Pe,onButtonClick:re,onDecline:c,onTechnicalFailure:Br,runBeforeButtonClick:qn,onLoadStateChange:li,placeholderBorderRadius:Sr})}),ro&&(0,l.jsx)(ls,{sessionId:e,nonce:t,email:j.email,billingName:[j.firstName,j.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:Oe,paymentElementMethods:Ao,stripeInstance:bn,paymentElementBaseOptions:fa,onTokenizedBody:xn,onErrorChange:Pe,onButtonClick:re,onDecline:c,runBeforeButtonClick:qn,onLoadStateChange:di,isProcessing:se,submitButtonColor:wr,submitButtonBorderRadius:_t,submitButtonStyle:m.submitButton,themeId:be,onExpandApm:O,expandedApmMethod:Bt,buttonAppearance:{backgroundColor:m.cardButton?.backgroundColor,borderColor:m.cardInputBorder,textColor:m.cardButton?.color,borderRadius:Sr}})]}),Je&&(Bs||As||Fs)&&(0,l.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem",margin:"0.5rem 0 0.75rem",color:"#999",fontSize:"0.85rem"},children:[(0,l.jsx)("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}}),(0,l.jsx)("span",{children:"or pay with card"}),(0,l.jsx)("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}})]}),Je&&Ri]})}var k=require("react/jsx-runtime"),Tr=44,Ja="flopay_checkout_saved_payment_resume",sa=new Map,aa=new Map;function fs(e,t){t.settled&&t.consumers===0&&sa.get(e)===t&&sa.delete(e)}function Bl(e,t,n){let r=aa.get(e);if(r&&(!r.sdkGeneratedIdempotencyKey||!t||r.sdkGeneratedIdempotencyKey===t))return r.attempt;let o=n(),i={attempt:o,sdkGeneratedIdempotencyKey:t};aa.set(e,i);let d=()=>{aa.get(e)===i&&aa.delete(e)};return o.then(d,d),o}function wo(e){return new Promise(t=>setTimeout(t,e))}function ia(e,t,n){let r=Ho({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:Ce.SDK_VERSION,enabled:t!==!1});return r.beginCheckout(n),r}function ko(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function qa(e,t,n,r,o){let i=ia(e,t,n);i.error({errorCode:r,stage:o,paymentMethodCategory:"unknown",...o==="session_read"?{requestCategory:"session_read"}:{}}),ko(i)}function Fl(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 Wa(e){let t=e?.data.paypal?.publishableKey;if(t)return{clientId:t,environment:e?.data.paypal?.environment,providerObjectType:e?.data.paypal?.providerObjectType}}function $a(e){return!e||e.data.stripe?.publishableKey?!1:!!Wa(e)?.clientId}function dr(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function Dl(){if(!dr())return null;try{let e=window.sessionStorage.getItem(Ja);return e?JSON.parse(e):null}catch{return null}}function gs(e){if(dr())try{window.sessionStorage.setItem(Ja,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function ja(){if(dr())try{window.sessionStorage.removeItem(Ja)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}var Xa=":idempotency-key";function bs(e,t){if(!dr())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 Va(e,t,n,r){if(dr())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 Ga(e,t){if(dr())try{bs(e,t)&&window.sessionStorage.removeItem(e)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout session cache.",n)}}function vs(e,t){if(!dr())return null;try{let n=window.sessionStorage.getItem(e+Xa);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 Ka(e,t,n){if(dr())try{window.sessionStorage.setItem(e+Xa,JSON.stringify({canonicalIdentity:t,idempotencyKey:n}))}catch(r){console.warn("[FloPayCheckout] Failed to persist checkout idempotency key.",r)}}function Ha(e,t){if(Ga(e,t),!!dr())try{vs(e,t)&&window.sessionStorage.removeItem(e+Xa)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout idempotency key.",n)}}function Ll(){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 hs(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 Nl(e){return e?!!(e.account&&Object.keys(e.account).length>0||e.couponCodes!==void 0||e.checkoutMetadata!==void 0||e.tagsData!==void 0||e.utmMetadata!==void 0):!1}function Ya(e,t){return`${e}:${t.totalAmount??""}:${t.overrideAmount??""}:${t.quantity??1}:${t.currency??""}`}function Ol(e){if(e==null)return e;let t=JSON.stringify(Object.entries(e).sort(([d],[c])=>d<c?-1:d>c?1:0)),n=1779033703,r=3144134277,o=1013904242,i=2773480762;for(let d=0;d<t.length;d++){let c=t.charCodeAt(d);n=r^Math.imul(n^c,597399067),r=o^Math.imul(r^c,2869860233),o=i^Math.imul(o^c,951274213),i=n^Math.imul(i^c,2716044179)}return n=Math.imul(o^n>>>18,597399067),r=Math.imul(i^r>>>22,2869860233),o=Math.imul(n^o>>>17,951274213),i=Math.imul(r^i>>>19,2716044179),n^=r^o^i,r^=n,o^=n,i^=n,[n,r,o,i].map(d=>(d>>>0).toString(16).padStart(8,"0")).join("")}function Io(e,t=!1){let n=e?.account?.email?.trim().toLowerCase()??"",r={c:e?.clientId,cur:e?.currency??"",captureMethod:e?.captureMethod??"",a:{e:n,u:n?"":e?.account?.userId??"",country:e?.account?.country??""},successUrl:e?.successUrl,cancelUrl:e?.cancelUrl,p:e?.products?.map(o=>Ya(`${o.type??""}:${o.code??o.providerItemId??o.providerPlanId??""}`,o)).sort(),i:e?.items?.map(o=>Ya(o.code??o.providerItemId??"",o)).sort(),s:e?.subscriptions?.map(o=>Ya(o.code??o.providerPlanId??"",o)).sort(),couponCodes:e?.couponCodes?[...e.couponCodes].sort():void 0,checkoutMetadata:Ol(e?.checkoutMetadata),...t?{tagsData:e?.tagsData,utmMetadata:e?.utmMetadata,tokenizedData:e?.tokenizedData,checkoutMode:e?.checkoutMode??"full"}:{}};return JSON.stringify(r)}function zl(e,t=!1){let n=Io(e,t),r=0;for(let o=0;o<n.length;o++)r=(r<<5)-r+n.charCodeAt(o)|0;return`flopay_session_${Math.abs(r).toString(36)}`}function Ul(e,t){if(!e?.customer||!e.products||t.checkoutMetadata!==void 0)return!1;let n=t.account.email?.trim().toLowerCase()??"",r=e.customer.email?.trim().toLowerCase()??"";if((n?r!==n:e.customer.id!==t.account.userId)||(t.account.country??"").trim().toUpperCase()!==(e.customer.country??"").trim().toUpperCase()||e.successUrl!==t.successUrl||e.cancelUrl!==t.cancelUrl||(e.captureMethod??"automatic")!==(t.captureMethod??"automatic"))return!1;let o=(0,Ce.resolveSessionCurrency)(t.currency,t.items,t.subscriptions,t.products);if(!o||e.currency.toUpperCase()!==o.toUpperCase())return!1;let i=(t.products??(0,Ce.foldIntoProducts)(t.items,t.subscriptions)).map(y=>({type:y.type,code:y.code??y.providerItemId??y.providerPlanId??"",quantity:y.quantity??1,totalAmount:y.totalAmount,overrideAmount:y.overrideAmount??null,currency:(y.currency??o).toUpperCase()})).sort((y,g)=>`${y.code}:${y.type??""}`.localeCompare(`${g.code}:${g.type??""}`)),d=e.products.map(y=>({type:y.type,code:y.code??"",quantity:y.quantity??1,totalAmount:y.totalAmount,overrideAmount:y.overrideAmount??null,currency:(y.currency??e.currency).toUpperCase()})).sort((y,g)=>`${y.code}:${y.type??""}`.localeCompare(`${g.code}:${g.type??""}`));if(i.length!==d.length)return!1;for(let y=0;y<i.length;y+=1){let g=i[y],b=d[y];if(g.code!==b.code||g.type!==void 0&&g.type!==b.type||g.quantity!==b.quantity||g.totalAmount!==b.totalAmount||g.overrideAmount!==b.overrideAmount||g.currency!==b.currency)return!1}let c=[...t.couponCodes??[]].sort(),v=[...e.coupons??[]].sort();return c.length===v.length&&c.every((y,g)=>y===v[g])}function la({sessionId:e,nonce:t,createSession:n,billingApiUrl:r,telemetry:o,appearance:i,locale:d,loading:c,error:v,onComplete:y,onError:g,onInstrument:b,onDecline:B,onCountryChange:T,onZipChange:p,showPayPal:P=!0,showStripe:he=!0,enabledPaymentMethods:q,showApplePay:S=!0,showGooglePay:ue=!0,debug:$=!1,layout:ce,theme:W,buttonsTheme:be,buttonsStyles:He,cardButtonContent:we,cardBackButtonContent:vt,cardTitleContent:$e,showSecurityFooter:xe,onButtonClick:Te,onBeforeButtonClick:ne,enableAVS:re,cardFieldOrder:L,cardPreFormSlot:Me,avsLayout:Ae,className:X,initialErrorMessage:Ie=null,children:Se,checkoutMode:x,confirmLabel:U,renderConfirmButton:Be,onSessionCompleted:me}){let ee=(0,Ce.resolveBillingApiUrl)(r),Le=(0,w.useMemo)(()=>(0,Ce.resolveTheme)(W),[W]),rt=i??Le?.appearance,pt=n?"embedded_checkout":"standard_checkout",qe=Se?"custom_layout":ce==="buttons"?"buttons_layout":"default_layout",[te,G]=(0,w.useState)(null),[H,Fe]=(0,w.useState)(null),Xe=(0,w.useRef)(null),[M,oe]=(0,w.useState)(null),D=(0,w.useRef)(null),[I,lt]=(0,w.useState)(null),Pt=(0,w.useMemo)(()=>n?Io(n):"",[n]),ie=n?`create:${Pt}`:`session:${e??""}`,ct=I?.gateways?.stripe?"stripe":I?.gateways?.paypal?"paypal":void 0,et=(0,w.useRef)(new Set),Ct=(0,w.useRef)(ie),kt=(0,w.useRef)(ie);fo(()=>{kt.current=ie,Ct.current!==ie&&(Ct.current=ie,et.current.clear())},[ie]);let C=(0,w.useCallback)(O=>{if(kt.current===ie){if(xa.has(O.name)){if(et.current.has(O.name))return;et.current.add(O.name)}at(()=>b?.(O))}},[ie,b]),Z=Vr(C,ie),dt=(0,w.useRef)(!1),yt=(0,w.useCallback)(O=>{if(dt.current)return;let z=O.gateway||!ct?O:{...O,gateway:ct};C(z)},[C,ct]);(0,w.useEffect)(()=>{Z({class:"lifecycle",name:"checkout.mount"})},[Z]);let[ye,It]=(0,w.useState)(e??""),it=e??ye,Ye=n?"":it,[Nt,$t]=(0,w.useState)(!0),[Yt,Ln]=(0,w.useState)(null),[tn,Kn]=(0,w.useState)("full"),[sn,Cn]=(0,w.useState)(!1),[nn,Ot]=(0,w.useState)(Ie),[Sn,tt]=(0,w.useState)(null),[ur,ot]=(0,w.useState)(null),[Nn,ft]=(0,w.useState)(!1),[jt,ln]=(0,w.useState)(void 0),[wn,kn]=(0,w.useState)(""),[Jt,Qn]=(0,w.useState)(!1),[Mt,le]=(0,w.useState)(!1),[er,cn]=(0,w.useState)(!1),dn=(0,w.useRef)(0),pr=(0,w.useRef)(void 0),[Hn,tr]=(0,w.useState)("loading"),[Xt,Je]=(0,w.useState)(0),In=(0,w.useRef)(!1),A=(0,w.useRef)(!1),Dt=(0,w.useRef)(!1),Rt=(0,w.useRef)(null),Et=(0,w.useMemo)(()=>({checkoutMode:x??tn,layout:Se?"unknown":ce==="buttons"?"buttons":"embedded"}),[x,Se,tn,ce]),fe=(0,w.useRef)(y);fe.current=y;let Wt=(0,w.useRef)(g);Wt.current=g;let mr=(0,w.useRef)(B);mr.current=B,(0,w.useEffect)(()=>{qt(H)?.setCheckoutContext(Et),M&&M!==H&&qt(M)?.setCheckoutContext(Et)},[H,M,Et]);let yr=(0,w.useRef)(me);yr.current=me;let nr=(0,w.useCallback)(O=>{tr(O),!(O!=="exhausted"||Dt.current)&&(Dt.current=!0,Wt.current?.(new Ce.FloPayError("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),Pr=(0,w.useCallback)(()=>{tr("retrying"),Je(O=>O+1)},[]);(0,w.useEffect)(()=>{tr("loading"),Je(0),Dt.current=!1},[it]),(0,w.useEffect)(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:Ce.SDK_VERSION,checkout_type:pt,checkout_layout:qe,billing_api_url:ee})},[qe,pt,ee]);let Rn=(0,w.useMemo)(()=>n?Io(n,!0):"",[n]),Cr=(0,w.useMemo)(()=>wn===Rn?jt:void 0,[jt,wn,Rn]),Yn=(0,w.useMemo)(()=>n?Ra(n,Cr):void 0,[n,Cr]),un=x??Yn?.checkoutMode??"full",At=(0,w.useMemo)(()=>Yn?{...Yn,checkoutMode:un}:void 0,[Yn,un]);(0,w.useEffect)(()=>{ln(void 0),kn(Rn),pr.current=void 0,cn(!1)},[Rn]),(0,w.useEffect)(()=>{Ot(Ie)},[Ie]);let rn=(0,w.useCallback)((O,z,Q)=>{at(()=>{mr.current?.(Ut(O,z,Q))})},[]),Zt=(0,w.useCallback)(async(O,z)=>{Ot(null),ot(null),ft(!1),tt("processing");let Q=z?.sessionId??O.id,F=O.gateways?.stripe?"stripe":O.gateways?.paypal?"paypal":void 0,je=Xe.current??D.current,ae=qt(je),N=je?null:ia(ee,o,Et),h={log:m=>{ae?ae.log(m):N?.log(m)},error:m=>{ae?ae.error(m):N?.error(m)},terminal:m=>{ae?ae.terminal(m):N?.terminal(m)},performance:m=>{ae?ae.performance(m):N?.performance(m)},now:()=>ae?.now()??N?.now()??0,elapsed:m=>ae?.elapsed(m)??Math.max(0,(N?.now()??m)-m)},pe=h.now(),de=!!(z?.initialAutoProcessingError||z?.initialAutoProcessingPending),Oe=!1,Ze,ze=()=>{Oe||(Oe=!0,de=!0,Ze=h.now(),h.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),h.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},Re=!1,R=()=>{Re||(Re=!0,h.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),h.performance({stage:"processing",durationMs:h.elapsed(pe),durationMode:"machine",paymentMethodCategory:"saved"}),Ze!==void 0&&h.performance({stage:"recovery",durationMs:h.elapsed(Ze),durationMode:"machine",paymentMethodCategory:"saved"}))};h.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),dt.current=!0;try{h.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"})}finally{dt.current=!1}Z({class:"lifecycle",name:"payment.processing.started",provider:F}),de&&ze();let f;try{let m=Gi(z?.initialAutoProcessingError),J;if(m)ze(),m.type==="paypal_redirect_required"&&Rt.current?.publishableKey&&gs({sessionId:Q,publishableKey:Rt.current.publishableKey,paypalPublishableKey:Rt.current.paypalPublishableKey}),J=await Xo(m,{flopay:Xe.current,paypalFlopay:D.current,attempt3DS:z?.attempt3DS,billingApiUrl:ee,sessionId:Q,session:O,telemetry:!1}),m.type==="paypal_redirect_required"&&ja();else if(z?.initialAutoProcessingPending){let se=(await new xr.PaymentAPI(ee,{telemetry:!1}).waitForCheckoutSessionCompletion(z.initialAutoProcessingPending.sessionId,{initialDelayMs:z.initialAutoProcessingPending.retryAfterMs})).data.session;if(!Ur(se))throw $o(se);J=Ir(se,Q)}else{if(z?.initialAutoProcessingError)throw vr(z.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:z.initialAutoProcessingError.checkoutMethod});if(z?.fromCreateSession)return z?.fallbackToFull&&(Kn("full"),hs("full")),!1;{let ke=await Wr({billingApiUrl:ee,sessionId:Q,session:O,telemetry:!1});ke.type==="success"?J=ke.result:(ze(),ke.type==="paypal_redirect_required"&&Rt.current?.publishableKey&&gs({sessionId:Q,publishableKey:Rt.current.publishableKey,paypalPublishableKey:Rt.current.paypalPublishableKey}),J=await Xo(ke,{flopay:Xe.current,paypalFlopay:D.current,attempt3DS:z?.attempt3DS,billingApiUrl:ee,sessionId:Q,session:O,telemetry:!1}),ke.type==="paypal_redirect_required"&&ja())}}Q&&Hr(Q),R(),de&&(h.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),h.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),h.terminal({outcome:J.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),ft(J.status==="authorized"),tt("success"),await wo(1200),f=()=>fe.current?.(J)}catch(m){let J=Co(m),ke=J.checkoutMethod??Po;Ot(J.message),ot(J.message),ft(!1),z?.fallbackToFull&&(h.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),Kn("full"),hs("full")),R();let ge=J.statusCode!==void 0?(0,Ce.telemetryStatusClass)(J.statusCode,"unknown"):void 0,se=ge==="4xx"?{requestCategory:"process_payment",statusClass:ge}:{},Ee=ge===void 0||ge==="4xx";if(Ee&&(J.telemetryOutcome==="payment_declined"||!!(J.declineCode||J.code?.toLowerCase().includes("declin"))))h.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...se});else if(Ee&&(J.telemetryOutcome==="validation_rejected"||J.type==="validation_error"))h.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...se});else{let ve=(0,Ce.classifyTelemetryFailure)(m,de?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown"),_e=J.telemetryRequestCategory??"process_payment";dt.current=!0;try{h.error({...ve,...J.telemetryFailureCategory?{failureCategory:J.telemetryFailureCategory}:{},stage:de?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:_e})}finally{dt.current=!1}Z({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:_e,provider:F})}return at(()=>Wt.current?.(J)),rn(ke,J,{code:J.code,declineCode:J.declineCode}),tt("error"),await Promise.allSettled([wo(1500),z?.ensureProvidersReady?z.ensureProvidersReady():Promise.resolve()]),de&&(h.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),h.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{R(),N&&ko(N),tt(null),ot(null)}return at(f),!0},[rn,Z,ee,o,Et]);(0,w.useEffect)(()=>{if(typeof window>"u"||A.current)return;let O=new URLSearchParams(window.location.search),z=O.get("payment_intent_client_secret");if(!z)return;let Q=Dl();Q&&(A.current=!0,(async()=>{let F,je=0;Ot(null),ot(null),tt("processing"),Cn(!0);try{if(O.get("redirect_status")==="failed")throw Object.assign(new Ce.FloPayError("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:ae,paypalFlopay:N}=await Qo({publishableKey:Q.publishableKey,paypalPublishableKey:Q.paypalPublishableKey,billingApiUrl:ee,locale:d,telemetry:o});F=qt(N??ae),je=F?.now()??0,F?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),F?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let h=(N??ae)?.getRawProvider();if(!h)throw Object.assign(new Ce.FloPayError("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:pe,error:de}=await h.retrievePaymentIntent(z);if(de)throw Object.assign(new Ce.FloPayError(de.message??"Failed to retrieve PayPal payment status.","api_error",{code:de.code}),{checkoutMethod:"paypal"});let Oe=Di(pe?.status);if(!pe||Oe==="failed")throw Object.assign(new Ce.FloPayError("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let Ze=typeof pe.payment_method=="string"?pe.payment_method:pe.payment_method?.id,ze=Oe;if(Q.sessionId){let f=(await new xr.PaymentAPI(ee,{telemetry:!1}).getUnifiedCheckoutSession(Q.sessionId)).data.session;if(f&&f.status!=="complete"){let m=await Wr({billingApiUrl:ee,sessionId:Q.sessionId,session:f,telemetry:!1,tokenizedData:{id:Ze??pe.id,type:"card",threeDSecureActionResultTokenId:pe.id,isPaypal:!0}});if(m.type!=="success")throw Object.assign(new Ce.FloPayError("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});ze=m.result.status}}Q.sessionId&&Hr(Q.sessionId),F?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),F?.performance({stage:"redirect_resume",durationMs:F.elapsed(je),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),F?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),tt("success"),await wo(1200),at(()=>fe.current?.({status:ze,paymentIntentId:pe.id,paymentMethodId:Ze,checkoutMethod:"paypal"}))}catch(ae){let N=Co(ae),h=N.checkoutMethod??"paypal",pe=!!(N.declineCode||N.code?.toLowerCase().includes("declin"));if(F)F.performance({stage:"redirect_resume",durationMs:F.elapsed(je),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),pe?F.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):F.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(pe){let de=ia(ee,o,Et);de.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),ko(de)}else qa(ee,o,Et,"REDIRECT_RESUME_FAILED","redirect_resume");Ot(N.message),ot(N.message),at(()=>Wt.current?.(N)),rn(h,N,{code:N.code,declineCode:N.declineCode}),tt("error"),await wo(1500)}finally{ja(),Ll(),tt(null),ot(null),Cn(!1)}})())},[rn,d,ee,o,Et]);let En=(0,w.useRef)(null),pn=(0,w.useMemo)(()=>At?Io(At):"",[At]),st=(0,w.useRef)(At);st.current=At,(0,w.useEffect)(()=>{It(e??"")},[e]),(0,w.useEffect)(()=>{In.current=!1,Ot(Ie),ot(null),ft(!1),tt(null)},[pn,Ie,e]);async function mn(O,z,Q){let F=ia(ee,o,Et),je=new xr.PaymentAPI(ee,{telemetry:!1}),ae=!1;try{let N=O.idempotencyKey!==void 0?(0,Ce.resolveIdempotencyKey)(O.idempotencyKey):void 0,h=bs(z,Q),pe=vs(z,Q);h?.canonicalIdentity===Q&&pe&&pe.canonicalIdentity===void 0&&(Ka(z,Q,pe.idempotencyKey),pe={...pe,canonicalIdentity:Q});let de=N??(pe?.canonicalIdentity===Q?pe.idempotencyKey:void 0),Oe,Ze=!1;F.log({name:h?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let ze=h?.sid??null,Re=null,R,f,m=!1;if(ze)try{Re=await je.getUnifiedCheckoutSession(ze,h?.nonce),h&&h.canonicalIdentity===void 0&&(Ul(Re.data.session,O)?(Va(z,Q,ze,h.nonce??Re.data.session?.clientSecret),pe&&pe.canonicalIdentity===void 0&&(Ka(z,Q,pe.idempotencyKey),de??(de=pe.idempotencyKey))):(Ha(z,Q),pe=null,de=N,ze=null,Re=null));let ke=Re?.data.session?.status,ge=Re?.data.session,se=ge?.clientSecret||h?.nonce;if(ze&&ge?.buyerIdentified===!1&&se&&(f=zr(je,ze,se,O.account)),ze&&Re&&ke==="complete"){if(Ma(ze))return{sid:ze,result:Re};Ha(z,Q),ze=null,Re=null,Ze=!0}}catch{F.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),h?.canonicalIdentity===void 0?(Ha(z,Q),de=N):Ga(z,Q),ze=null}if(!ze){!N&&(Ze||!de)&&(de=(0,Ce.resolveIdempotencyKey)(),Oe=de),de&&Ka(z,Q,de);let ke=F.now(),ge=0;F.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let se={...O,idempotencyKey:de,avsCheck:!!re,avsConfig:typeof re=="object"?re:void 0,checkoutType:"embedded_checkout",checkoutLayout:Se?"custom_layout":ce==="buttons"?"buttons_layout":"default_layout"};Object.defineProperty(se,xr.SESSION_CREATE_TELEMETRY,{configurable:!1,enumerable:!1,value:{onAttempt:V=>{ge=Math.max(ge,V)}}});let Ee=()=>{F.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:"2xx"}),F.performance({stage:"session_create",durationMs:F.now()-ke,durationMode:"machine",requestCategory:"session_create",attempt:ge,statusClass:"2xx"})},j=V=>{let ve=(0,Ce.classifyTelemetryFailure)(V,"CHECKOUT_SESSION_CREATE_FAILED","unknown");F.performance({stage:"session_create",durationMs:F.now()-ke,durationMode:"machine",requestCategory:"session_create",attempt:ge,statusClass:ve.statusClass}),V instanceof Ce.FloPayError&&V.type==="validation_error"?F.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown"}):ve.statusClass==="4xx"?F.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create",statusClass:"4xx"}):(F.error({...ve,stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create"}),Z({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_create"}))};try{if((0,Ce.isDetachedSessionEligible)(se)){let V=await je.createDetachedSession(se);V.claimed.catch(()=>{}),Re=V.shell,ze=V.sessionId,f=V.claim,R=V.claimed.then(ve=>{let _e=ve.data.session?.id??V.sessionId;return _e&&Va(z,Q,_e,ve.data.session?.clientSecret??V.nonce),Ee(),ve},ve=>{throw Ga(z,Q),j(ve),ve}).finally(()=>ko(F)),R.catch(()=>{}),ae=!0,F.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),F.performance({stage:"session_shell",durationMs:F.now()-ke,durationMode:"machine",requestCategory:"session_create",attempt:ge,statusClass:"2xx",paymentMethodCategory:"card"})}else Re=await je.createAndFetchSession(se),Ee()}catch(V){throw j(V),V}ze=Re.data.session?.id??ze??"",ze&&!R&&Va(z,Q,ze,Re.data.session?.clientSecret)}let J=Re?.data.session;return!f&&ze&&J?.buyerIdentified===!1&&J.clientSecret&&(f=zr(je,ze,J.clientSecret,O.account)),{sid:ze??"",result:Re,sdkGeneratedIdempotencyKey:Oe,...R?{claimed:R}:{},...f?{claim:f}:{},...m?{claimRequiresIdentity:!0}:{}}}finally{ae||ko(F)}}let yn=(0,w.useRef)(mn);fo(()=>{yn.current=mn},[mn]);let fn=(0,w.useCallback)(async(O,z)=>{let Q=st.current;if(!Q)throw new Ce.FloPayError("createSession is required to bootstrap checkout.","validation_error");let F=Ra(Q,O),je=Io(F),ae=zl(F),N=sa.get(je);if(!N){let de={canonicalIdentity:je,promise:yn.current(F,ae,je),consumers:0,settled:!1};N=de,sa.set(je,de);let Oe=()=>{de.settled=!0,fs(je,de)};de.promise.then(Oe,Oe)}N.consumers+=1;let h=!1,pe=()=>{h||(h=!0,N.consumers-=1,fs(je,N))};z?.(pe);try{let de=await N.promise;En.current=je,O&&(kn(Rn),ln(ge=>Ai(ge,O)));let{sid:Oe,result:Ze,claimed:ze,claim:Re,claimRequiresIdentity:R}=de;if(pr.current=Re,cn(R===!0),G(Ze),Ze.data.session&&lt(Ze.data.session),Oe&&It(Oe),ze){dn.current+=1;let ge=dn.current;le(!0),ze.then(se=>{dn.current===ge&&(G(se),se.data.session&&lt(se.data.session),le(!1),cn(!1))},se=>{dn.current===ge&&(le(!1),cn(!1),Ln(se instanceof Ce.FloPayError?se:new Ce.FloPayError(se instanceof Error?se.message:"Failed to create session","api_error")))})}else dn.current+=1,le(!1),cn(!1);let{publishableKey:f,paypalPublishableKey:m}=Zo(Ze),{flopay:J,paypalFlopay:ke}=await Qo({publishableKey:f,paypalPublishableKey:m,billingApiUrl:ee,locale:d,telemetry:o});return Xe.current=J,Fe(J),D.current=ke,oe(ke),$t(!1),de}catch(de){throw En.current===je&&(En.current=null),de}finally{z||pe()}},[Rn,d,ee,o]),gn=(0,w.useRef)(Zt);gn.current=Zt;let Ne=(0,w.useRef)(fn);Ne.current=fn;let Gt=(0,w.useCallback)(async O=>{if(!Nl(O)||Jt)return{sessionId:ye,session:I};Qn(!0);try{let z=await fn(O);return{sessionId:z.sid,session:z.result.data.session??null}}finally{Qn(!1)}},[fn,Jt,ye,I]),Bt=(0,w.useCallback)(async O=>{let z=pr.current;if(!z)return;let Q=dn.current,F=await z(O);dn.current===Q&&(G(F),F.data.session&&lt(F.data.session))},[]);(0,w.useEffect)(()=>{let O=!1,z;if(Ln(null),pn){let je=st.current;return Kn(un),$t(!1),En.current===pn?()=>{O=!0}:(lt(Bi(je,x)),(async()=>{let ae=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),N=un==="auto"&&!In.current&&!ae;N&&(Ot(null),ot(null),tt("processing"));try{let h=await Ne.current(void 0,Ze=>{z=Ze}),pe=h.result.data.session??null;Rt.current=Zo(h.result);let de=$a(h.result),Oe=Ma(h.sid||pe?.id);if(!O&&N&&pe&&!de&&!Oe){In.current=!0,await Bl(pn,h.sdkGeneratedIdempotencyKey,()=>gn.current(pe,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:h.result.autoProcessingError,initialAutoProcessingPending:h.result.autoProcessingPending,autoProcessingAttempted:h.result.autoProcessingAttempted,sessionId:h.sid||pe.id}));return}!O&&N&&((de||Oe)&&(In.current=!0),tt(null),ot(null))}catch(h){if(O)return;let pe=h instanceof Ce.FloPayError||typeof h=="object"&&h!==null&&"code"in h?h.code:void 0;if(N&&pe==="session_auto_completed"){In.current=!0,tt("success"),await wo(1200),O||(at(()=>{fe.current?.({status:"succeeded"})}),tt(null),ot(null));return}N&&(tt(null),ot(null));let de=h instanceof Ce.FloPayError?h:new Ce.FloPayError(h instanceof Error?h.message:"Failed to create session","api_error");Ln(de)}finally{z?.(),z=void 0}})(),()=>{O=!0,z?.()})}$t(!0);async function Q(){let je=!1;try{let ae=new xr.PaymentAPI(ee,{telemetry:!1}),N=await ae.getUnifiedCheckoutSession(it,t);if(O)return;G(N);let h=N.data.session??null;if(lt(h),!h)throw new Ce.FloPayError("No session data returned","api_error");let pe=h.checkoutMode;if(pe==="setup")throw new Ce.FloPayError("This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.","validation_error",{code:"InvalidCardSetupSurface",param:"sessionId"});if(h.status==="authorized"){$t(!1),at(()=>{fe.current?.(Ir(h,it)),yr.current?.(h.successUrl??"")});return}if(h.status==="complete"){$t(!1),at(()=>{yr.current?.(h.successUrl??"")});return}if(h.status==="expired")throw qo(h);je=!0;let de=x??pe??"full";Kn(de),dn.current+=1;let Oe=h.clientSecret||t;pr.current=h.buyerIdentified===!1&&Oe?zr(ae,it,Oe,{...h.customer?.id?{userId:h.customer.id}:{}}):void 0,le(!1),cn(!1);let Ze=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),ze=$a(N);if(de==="auto"&&!In.current&&!Ze&&!ze){In.current=!0;let Re=F(N);try{if(await gn.current(h,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>Re,sessionId:it||h.id}),O)return;await Re,O||$t(!1);return}catch{if(O)return;await Re,O||$t(!1);return}}await F(N),O||$t(!1)}catch(ae){if(O)return;je&&Z({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"}),ae instanceof Ce.FloPayError?!je&&!Fl(ae)&&qa(ee,o,Et,"NETWORK_REQUEST_FAILED","session_read"):qa(ee,o,Et,"INTERNAL_SDK_ERROR","checkout_mount");let N=ae instanceof Ce.FloPayError?ae:new Ce.FloPayError(ae instanceof Error?ae.message:"Failed to initialize checkout","api_error");Ln(N),$t(!1)}}async function F(je){let{publishableKey:ae,paypalPublishableKey:N}=Zo(je);Rt.current={publishableKey:ae,paypalPublishableKey:N};let{flopay:h,paypalFlopay:pe}=await Qo({publishableKey:ae,paypalPublishableKey:N,billingApiUrl:ee,locale:d,telemetry:o});Xe.current=h,Fe(h),D.current=pe,oe(pe)}return Q(),()=>{O=!0}},[x,pn,un,Ye,t]);let fr=(0,w.useCallback)(async()=>{if(!(sn||!I)){Cn(!0),Ot(null);try{await Zt(I,{attempt3DS:!0,fallbackToFull:!0,sessionId:it||I.id})}finally{Cn(!1)}}},[it,sn,Zt,I]),On=Wa(te),gr=$a(te),zn=(0,w.useMemo)(()=>{if(!(!te||!I||!te.data.stripe?.publishableKey))return{billingApiUrl:ee}},[te,I,ee]),hn=!!(n&&!Se&&ce==="buttons"&&ne&&un==="full"),zt=(0,w.useMemo)(()=>({session:I,loading:Nt,error:Yt,checkoutMode:tn,inlineSessionDraft:At,applyInlineSessionPatch:hn?Gt:void 0,inlineSessionPatchProcessing:Jt,claimPending:Mt,claimRequiresIdentity:er,claimBuyerIdentity:Bt}),[I,Nt,Yt,tn,At,hn,Gt,Jt,Mt,er,Bt]),Mr=!!n&&ce==="buttons"&&!gr&&(!H||!zn),_n=Sn?(0,k.jsx)(Fn,{status:Sn,errorMessage:ur,authorized:Nn}):null;if(Nt){if(c)return(0,k.jsxs)(k.Fragment,{children:[c,_n]});if(ce==="buttons"){let O=Le?.buttonsLayout?.cardButton?.borderRadius??Le?.appearance.variables?.borderRadius??8,z=Q=>(0,k.jsx)("div",{style:{height:Q,borderRadius:O,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return(0,k.jsxs)(k.Fragment,{children:[(0,k.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[P&&z(Tr),he&&(S||ue)&&z(Tr),he&&z(Tr),(0,k.jsx)("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),_n]})}return(0,k.jsxs)(k.Fragment,{children:[(0,k.jsxs)("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[(0,k.jsx)("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),(0,k.jsx)("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),_n]})}return Yt?v?(0,k.jsx)($n.Provider,{value:zt,children:v(Yt)}):(0,k.jsx)($n.Provider,{value:zt,children:(0,k.jsx)("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:Yt.message})}):Mr?(0,k.jsxs)(k.Fragment,{children:[(0,k.jsx)($n.Provider,{value:zt,children:(0,k.jsx)($l,{onButtonClick:Te,showPayPal:P,showStripe:he,showApplePay:S,showGooglePay:ue,theme:W,buttonsTheme:be,buttonsStyles:He,cardButtonContent:we,cardBackButtonContent:vt,cardTitleContent:$e})}),_n]}):gr&&I&&On?(0,k.jsxs)(k.Fragment,{children:[(0,k.jsx)($n.Provider,{value:zt,children:(0,k.jsxs)("div",{className:X,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[nn&&(0,k.jsx)(Kr,{icon:!1,children:nn}),Hn==="retrying"&&(0,k.jsx)("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),Hn==="exhausted"&&(0,k.jsxs)("div",{role:"alert",children:[(0,k.jsx)("div",{children:"PayPal is temporarily unavailable. Please try again."}),(0,k.jsx)("button",{type:"button",onClick:Pr,children:"Retry PayPal"})]}),Mt?c??(0,k.jsx)("div",{role:"status","data-testid":"flopay-paypal-catalog-loading","aria-label":"Preparing PayPal",style:{height:Tr,borderRadius:8,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"},children:(0,k.jsx)("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})}):Hn!=="exhausted"?(0,k.jsx)("div",{"aria-hidden":Hn==="retrying"?!0:void 0,style:Hn==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:(0,k.jsx)(Hi,{sessionId:it,nonce:I.clientSecret||void 0,billingApiUrl:ee,email:I.customer?.email||At?.account?.email,billingName:[I.customer?.firstName,I.customer?.lastName].filter(Boolean).join(" ")||[At?.account?.firstName,At?.account?.lastName].filter(Boolean).join(" ")||void 0,onBuyerIdentityReady:Bt,clientId:On.clientId,environment:On.environment,currency:(I.currency??"usd").toUpperCase(),isSubscription:I.mode==="subscription",providerObjectType:On.providerObjectType,onComplete:y,onErrorChange:Ot,onDecline:B,onButtonClick:Te,onInitializationStateChange:nr,allowAutomaticRetry:Xt===0,session:I,telemetry:o,telemetryContext:Et,onInstrument:yt,debug:$},`${ie}:paypal-init-${Xt}`)}):null]})}),_n]}):!H||!zn?(0,k.jsx)(k.Fragment,{children:_n}):tn==="confirm"?(0,k.jsxs)(k.Fragment,{children:[(0,k.jsx)($n.Provider,{value:zt,children:(0,k.jsx)(bo,{flopay:H,paypalFlopay:M,options:zn,onInstrument:yt,children:(0,k.jsxs)("div",{className:X,children:[nn&&(0,k.jsx)("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:nn}),Be?Be({onConfirm:fr,isProcessing:sn}):(0,k.jsx)("button",{type:"button",onClick:fr,disabled:sn,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:sn?"not-allowed":"pointer",opacity:sn?.6:1},children:sn?"Processing...":U??"Confirm Purchase"})]})},ie)}),_n]}):(0,k.jsxs)(k.Fragment,{children:[(0,k.jsx)($n.Provider,{value:zt,children:(0,k.jsx)(bo,{flopay:H,paypalFlopay:M,options:zn,onInstrument:yt,children:Se?(0,k.jsxs)(k.Fragment,{children:[nn&&(0,k.jsx)("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:nn}),(0,k.jsx)(ql,{sessionId:it,nonce:I?.clientSecret||void 0,billingApiUrl:ee,session:I,children:Se})]}):(0,k.jsx)(oa,{sessionId:it,nonce:I?.clientSecret||void 0,email:I?.customer?.email||At?.account?.email,userId:I?.customer?.id||At?.account?.userId,firstName:I?.customer?.firstName||At?.account?.firstName,lastName:I?.customer?.lastName||At?.account?.lastName,totalAmount:I?Math.round((0,Ce.buildCheckoutDisplayData)(I).total*100):0,currency:I?.currency?.toLowerCase()??"usd",onComplete:y,onError:g,onDecline:B,error:nn,onErrorChange:Ot,showPayPal:P,showStripe:he,enabledPaymentMethods:q??te?.data.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:te?.data.stripe?.enabledPaymentMethodCountries,showApplePay:S,showGooglePay:ue,layout:ce,theme:W,buttonsTheme:be,buttonsStyles:He,appearance:rt,cardButtonContent:we,cardBackButtonContent:vt,cardTitleContent:$e,onButtonClick:Te,onBeforeButtonClick:ne,onBuyerIdentityReady:Bt,enableAVS:re,...L?{cardFieldOrder:L}:{},...Me?{cardPreFormSlot:Me}:{},avsLayout:Ae,country:I?.customer?.country,city:I?.customer?.city,state:I?.customer?.state,onCountryChange:T,onZipChange:p,avsCheck:!!re,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:Se?"custom_layout":ce==="buttons"?"buttons_layout":"default_layout",className:X,directPaypal:Wa(te),isSubscription:I?.mode==="subscription",session:I,dataAttachmentPending:Mt,dataAttachmentRequiresIdentity:er,debug:$})},ie)}),_n]})}function ql({sessionId:e,nonce:t,billingApiUrl:n,session:r,children:o}){return(0,k.jsx)(k.Fragment,{children:w.default.Children.map(o,i=>{if(!w.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:w.default.cloneElement(i,c)})})}function $l({onButtonClick:e,showPayPal:t,showStripe:n=!0,showApplePay:r,showGooglePay:o,theme:i,buttonsTheme:d,buttonsStyles:c,cardButtonContent:v,cardBackButtonContent:y,cardTitleContent:g}){let[b,B]=(0,w.useState)(!1),T=(0,w.useMemo)(()=>(0,Ce.resolveTheme)(i),[i]),p=(0,w.useMemo)(()=>{let S=T?.buttonsLayout??(0,Ce.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},[T,d,c]),P=T?.buttonsLayout?.cardButton?.borderRadius??T?.appearance.variables?.borderRadius??8,he=S=>(0,k.jsx)("div",{style:{height:S,borderRadius:P,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),q=v===void 0?{boxSizing:"border-box",height:Tr,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(b){let S=p.cardInputBorder??"#e5e7eb",ue=p.cardInputBackground??"white",$=Lr(y),ce=Lr(g);return(0,k.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,k.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,k.jsxs)("button",{type:"button",onClick:()=>B(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:$?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,k.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...p.backButtonIcon},children:(0,k.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,k.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,k.jsx)(Or,{content:y})]}),ce?(0,k.jsx)("div",{style:{flex:1}}):(0,k.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...p.title},children:(0,k.jsx)(uo,{content:g})})]}),(0,k.jsx)("div",{style:{backgroundColor:ue,border:`1px solid ${S}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:(0,k.jsx)("div",{style:{width:"60%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,k.jsxs)("div",{style:{display:"flex"},children:[(0,k.jsx)("div",{style:{flex:1,backgroundColor:ue,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${S}`,borderLeft:`1px solid ${S}`,borderBottomLeftRadius:8,padding:12,height:45},children:(0,k.jsx)("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,k.jsx)("div",{style:{flex:1,backgroundColor:ue,borderTop:"none",borderRight:`1px solid ${S}`,borderBottom:`1px solid ${S}`,borderLeft:`1px solid ${S}`,borderBottomRightRadius:8,padding:12,height:45},children:(0,k.jsx)("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),(0,k.jsx)("div",{style:{backgroundColor:ue,border:`1px solid ${S}`,borderRadius:8,marginTop:8,padding:12,height:45},children:(0,k.jsx)("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,k.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,k.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,I.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&ge(_r),n&&(r||o)&&ge(_r),n&&(0,I.jsx)("button",{type:"button",onClick:()=>{e?.("card"),N(!0)},style:{width:"100%",...$,backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:"8px",fontSize:f.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,...f.cardButton},onMouseDown:S=>{S.currentTarget.style.transform="scale(0.985)"},onMouseUp:S=>{S.currentTarget.style.transform="scale(1)"},children:(0,I.jsx)(Dr,{content:P})}),(0,I.jsx)("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}var On=require("react/jsx-runtime"),$l=44;function vs(e){return new Promise(t=>setTimeout(t,e))}function jl(e,t){return e instanceof ln.FloPayError?e:new ln.FloPayError(e instanceof Error?e.message:t,"api_error")}function Vl(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function Kl(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 Ps({sessionId:e,nonce:t,createSession:n,paymentMethodId:r,checkoutMethod:o,clientId:i,products:u,items:c,subscriptions:P,account:g,successUrl:b,cancelUrl:v,couponCodes:N,tagsData:B,utmMetadata:f,billingApiUrl:C,locale:ge,theme:$,appearance:S,buttonsTheme:ye,buttonsStyles:j,onSuccess:pe,onError:J,onDecline:he,children:ze,disabled:we=!1,type:yt="button",style:Me,...Ie}){let Re=(0,Oe.useMemo)(()=>(0,ln.resolveBillingApiUrl)(C),[C]),re=(0,Oe.useMemo)(()=>Kl({createSession:n,clientId:i,products:u,items:c,subscriptions:P,account:g,successUrl:b,cancelUrl:v,couponCodes:N,tagsData:B,utmMetadata:f}),[g,v,i,N,n,u,c,P,b,B,f]),[oe,O]=(0,Oe.useState)(!1),[Ee,_e]=(0,Oe.useState)(null),[X,ke]=(0,Oe.useState)(null),[Ce,x]=(0,Oe.useState)(!1),[q,xe]=(0,Oe.useState)(null),fe=(0,Oe.useRef)(!0),te=(0,Oe.useRef)(null),Fe=(0,Oe.useRef)(q),Qe=(0,Oe.useRef)(pe),ot=(0,Oe.useRef)(J),Le=(0,Oe.useRef)(he);(0,Oe.useEffect)(()=>{Fe.current=q},[q]),(0,Oe.useEffect)(()=>{Qe.current=pe},[pe]),(0,Oe.useEffect)(()=>{ot.current=J},[J]),(0,Oe.useEffect)(()=>{Le.current=he},[he]),(0,Oe.useEffect)(()=>(fe.current=!0,()=>{fe.current=!1,te.current?.abort()}),[]),(0,Oe.useEffect)(()=>{if(typeof window>"u")return;let w=se=>{se.key==="Escape"&&xe(null)};return window.addEventListener("keydown",w),()=>{window.removeEventListener("keydown",w)}},[]);let ae=(0,Oe.useCallback)((w,se=ho)=>{Le.current?.(Ft(se,w,{code:w.code,declineCode:w.declineCode}))},[]),Z=(0,Oe.useCallback)(async w=>{fe.current&&(ke(null),x(w.result.status==="authorized"),_e("success"),await vs(1200),fe.current&&Qe.current?.(w))},[]),H=(0,Oe.useCallback)(async(w,se)=>{fe.current&&(ot.current?.(w),se?.emitDecline&&ae(w,se.method),ke(w.message),x(!1),_e("error"),await vs(1500))},[ae]),Te=(0,Oe.useCallback)(async(w,se,de)=>{let at=w.data.session??null;if(!at)throw new ln.FloPayError("No session data returned","api_error");let Tt=at.clientSecret||t;if(Or(at)){await Z({result:wr(at,se),session:at,sessionId:at.id||se,autoCompleted:!1});return}if(at.status==="expired")throw No(at);try{if(w.autoProcessingPending){let jt=(await new ia.PaymentAPI(Re).waitForCheckoutSessionCompletion(w.autoProcessingPending.sessionId,{initialDelayMs:w.autoProcessingPending.retryAfterMs})).data.session;if(!Or(jt))throw Oo(jt);await Z({result:wr(jt,se),session:jt,sessionId:jt.id||se,autoCompleted:!1});return}if(w.autoProcessingError){if(w.autoProcessingError.type==="3ds_required"&&w.autoProcessingError.nextActionRedirectUrl&&se&&Tt){let Je=new AbortController;te.current=Je;let Ye;try{Ye=await Gi({billingApiUrl:Re,sessionId:se,nonce:Tt,nextActionRedirectUrl:w.autoProcessingError.nextActionRedirectUrl,signal:Je.signal})}finally{te.current===Je&&(te.current=null)}if(Ye.status==="declined")throw hr({type:Ye.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:Ye.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:w.autoProcessingError.checkoutMethod});let At=(await new ia.PaymentAPI(Re).waitForCheckoutSessionCompletion(se,{initialDelayMs:0,nonce:Tt})).data.session;if(!Or(At))throw hr({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:w.autoProcessingError.checkoutMethod});await Z({result:wr(At,se),session:At,sessionId:At.id||se,autoCompleted:!1});return}throw hr(w.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:w.autoProcessingError.checkoutMethod})}if(de?.fromCreateSession&&w.autoProcessingAttempted===!0)throw hr({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let Pt=await Hr({billingApiUrl:Re,sessionId:se??at.id,session:at,nonce:Tt});if(Pt.type!=="success")throw hr({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await Z({result:Pt.result,session:at,sessionId:at.id||se,autoCompleted:!1})}catch(Pt){let Je=Rr(Pt),Ye=at.id||se;await H(Je,{emitDecline:!0,method:Je.checkoutMethod??ho}),Vl(Je,Ye)&&Ye&&fe.current&&xe({sessionId:Ye,errorMessage:Je.message,nonce:Tt||void 0})}},[t,Re,H,Z]),He=(0,Oe.useCallback)(async w=>{if(Ie.onClick?.(w),!(w.defaultPrevented||we||oe)){if(xe(null),e&&re){let se=new ln.FloPayError("Provide either sessionId or create-session props, not both.","validation_error");await H(se),fe.current&&(_e(null),ke(null));return}if(!e&&!re){let se=new ln.FloPayError("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await H(se),fe.current&&(_e(null),ke(null));return}O(!0),ke(null),x(!1),_e("processing");try{let se=new ia.PaymentAPI(Re);if(e){let de=await se.getUnifiedCheckoutSession(e,t);await Te(de,e);return}try{let de=await se.createAndFetchSession({...re});await Te(de,de.data.session?.id??null,{fromCreateSession:!0})}catch(de){if(de instanceof ln.FloPayError&&de.code==="session_auto_completed"){await Z({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw de}}catch(se){await H(jl(se,"Automatic payment failed. Please try again."))}finally{fe.current&&(_e(null),ke(null),O(!1))}}},[Ie,re,we,oe,t,Te,Re,e,H,Z]),M=(0,Oe.useCallback)(w=>{let se=Fe.current;xe(null),Qe.current?.({result:w,session:null,sessionId:se?.sessionId??null,autoCompleted:!1})},[]),ie=(0,Oe.useCallback)(w=>{ot.current?.(w)},[]),L=(0,Oe.useCallback)(w=>{Le.current?.(w)},[]),E=(0,Oe.useMemo)(()=>(0,ln.resolveTheme)($),[$]),et=(0,Oe.useMemo)(()=>{let w=E?.buttonsLayout??(0,ln.resolveButtonsLayoutTheme)(ye);return j?{...w,...j,cardButton:{...w.cardButton,...j.cardButton}}:w},[E,ye,j]),ft=(0,Oe.useMemo)(()=>{let w=E?.appearance;return S?w?{...w,...S,variables:{...w.variables,...S.variables}}:S:w},[S,E]),ce=ft?.variables,tt=ce?.colorPrimary??"#4A49FF",Ge=ce?.colorPrimaryHover??Wr(tt,.12),gt=ce?.borderRadius??"8px";return(0,On.jsxs)(On.Fragment,{children:[(0,On.jsx)("button",{...Ie,type:yt,onClick:He,disabled:we||oe,"aria-busy":oe,style:{width:"100%",...ze===void 0?{boxSizing:"border-box",height:$l,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...et.cardButton,...za({themeBundle:E,resolvedPrimaryColor:tt,resolvedBorderRadius:gt,submitButtonStyle:et.submitButton,explicitPrimaryColor:ce?.colorPrimary}),fontSize:et.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:we||oe?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",transition:"background-color 0.15s, border-color 0.2s, box-shadow 0.2s, transform 0.1s",position:"relative",opacity:we||oe?.6:1,...Me},onMouseEnter:w=>{Ie.onMouseEnter?.(w),!w.defaultPrevented&&!we&&!oe&&(E||ce?.colorPrimary)&&(w.currentTarget.style.backgroundColor=Ge)},onMouseLeave:w=>{Ie.onMouseLeave?.(w),!w.defaultPrevented&&(E||ce?.colorPrimary)&&(w.currentTarget.style.backgroundColor=tt)},onMouseDown:w=>{Ie.onMouseDown?.(w),w.defaultPrevented||(w.currentTarget.style.transform="scale(0.985)")},onMouseUp:w=>{Ie.onMouseUp?.(w),w.defaultPrevented||(w.currentTarget.style.transform="scale(1)")},children:(0,On.jsx)(Dr,{content:ze})}),Ee&&(0,On.jsx)(Rn,{status:Ee,errorMessage:X,authorized:Ce}),q&&(0,On.jsx)("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:w=>{w.target===w.currentTarget&&xe(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,On.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,On.jsx)(aa,{sessionId:q.sessionId,nonce:q.nonce,checkoutMode:"full",billingApiUrl:Re,locale:ge,theme:$,...ft?{appearance:ft}:{},buttonsTheme:ye,buttonsStyles:j,initialErrorMessage:q.errorMessage,cardTitleContent:null,onComplete:M,onError:ie,onDecline:L})})})]})}var sa=require("@flopay/js/card-setup"),cn=require("@flopay/shared"),mt=require("react");var Yn=require("react/jsx-runtime"),So=class extends cn.FloPayError{constructor(t,n,r){super(t,n,r),this.name="FloPayCardSetupError",this.retryable=r.retryable}};function Cs(e,t={}){let n=e instanceof cn.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 So(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 Ss({sessionId:e,nonce:t,billingApiUrl:n,telemetry:r,theme:o="modern-light",containerStyle:i,loading:u=null,onReady:c,onComplete:P,onDecline:g,onCancel:b,onValidation:v,onError:N}){let[B,f]=(0,mt.useState)(null),[C,ge]=(0,mt.useState)(null),[$,S]=(0,mt.useState)(null),[ye,j]=(0,mt.useState)(null),[pe,J]=(0,mt.useState)(null),he=(0,mt.useRef)(!1),ze=(0,mt.useRef)(!1),we=(0,mt.useMemo)(()=>{if(typeof o=="object")return o;let X=(0,cn.resolveTheme)(o);if(X)return Xo({appearance:X.appearance,buttonsStyles:X.buttonsLayout,layout:"default"})},[o]),yt=(0,mt.useRef)(c),Me=(0,mt.useRef)(N),Ie=(0,mt.useRef)(P),Re=(0,mt.useRef)(g),re=(0,mt.useRef)(b),oe=(0,mt.useRef)(v),O=(0,mt.useRef)(!1),Ee=(0,mt.useRef)(!1),_e=(0,mt.useRef)(0);return yt.current=c,Me.current=N,Ie.current=P,Re.current=g,re.current=b,oe.current=v,(0,mt.useEffect)(()=>{let X=_e.current+1;return _e.current=X,()=>{queueMicrotask(()=>{_e.current===X&&(O.current||Ee.current||(Ee.current=!0,Ke(()=>{re.current?.({status:"cancelled",sessionId:e})})))})}},[e]),(0,mt.useEffect)(()=>{let X=!0,ke=new sa.PaymentAPI((0,cn.resolveBillingApiUrl)(n),{telemetry:r});return f(null),ge(null),S(null),O.current=!1,Ee.current=!1,(async()=>{try{if(!e.trim())throw new cn.FloPayError("FloPayCardSetup requires a sessionId.","validation_error",{code:"MissingCheckoutSessionId",param:"sessionId"});if(!t.trim())throw new cn.FloPayError("FloPayCardSetup requires a session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let Ce=await ke.getUnifiedCheckoutSession(e,t);if(!X)return;let x=Ce.data.session;if(!x||!(0,cn.isCardSetupCheckoutSession)(x))throw new cn.FloPayError("FloPayCardSetup only accepts a zero-amount, productless setup session.","validation_error",{code:"InvalidCardSetupSession",param:"sessionId"});let q=x.vault;if(q?.html?.trim()||(q=await ke.getVaultCapture(e,t)),!q.html?.trim())throw new cn.FloPayError("FloPay: this setup session has no vault card capability. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});if(!X)return;ge(q),f(new sa.PciVaultCardCapture({sessionId:e,operation:"card_setup",telemetry:r}))}catch(Ce){if(!X)return;let x=Cs(Ce);O.current=!0,S(x),Ke(()=>Me.current?.(x))}})(),()=>{X=!1,ke.destroy()}},[n,t,e,r]),(0,mt.useEffect)(()=>{if(!B)return;let X=!1;ze.current=!1,he.current=!1;let ke=B.on("submitting",()=>{he.current=!0,J(null),j("processing")}),Ce=B.on("complete",q=>{O.current=!0,he.current=!1,j("success"),(async()=>(await new Promise(xe=>setTimeout(xe,1200)),!ze.current&&(ze.current=!0,Ke(()=>{Ie.current?.({status:"succeeded",sessionId:e,...q.paymentMethod?{paymentMethod:q.paymentMethod}:{}})}),X||j(null))))()}),x=B.on("decline",q=>{O.current=!0,he.current=!1,J(q.message??null),j("error"),Ke(()=>{Re.current?.({status:"declined",sessionId:e,...q.declineReason?{reason:q.declineReason}:{},...q.message?{message:q.message}:{}})}),(async()=>(await new Promise(xe=>setTimeout(xe,1500)),X||j(null)))()});return()=>{X=!0,ke(),Ce(),x()}},[B,e]),$?(0,Yn.jsx)("div",{role:"alert",children:$.message}):!B||!C?.html?(0,Yn.jsx)(Yn.Fragment,{children:u}):(0,Yn.jsxs)(Yn.Fragment,{children:[ye&&(0,Yn.jsx)(Rn,{status:ye,errorMessage:pe,processingLabel:"SAVING CARD...",successLabel:"CARD SAVED",errorLabel:"CARD NOT SAVED",successNote:null}),(0,Yn.jsx)(Yr,{capture:B,html:C.html,messageToken:C.messageToken,expectedOrigin:C.expectedOrigin,theme:we,containerStyle:i,onReady:()=>{Ke(()=>yt.current?.())},onValidation:X=>{Ke(()=>oe.current?.(X))},onError:X=>{if(!X)return;he.current&&(he.current=!1,J(X),j("error"),setTimeout(()=>j(null),1500));let ke=Cs(new Error(X),{code:"card_setup_widget_failed",retryable:!0});Ke(()=>Me.current?.(ke))}})]})}0&&(module.exports={DirectPayPalButton,FloPayAutomaticPaymentButton,FloPayCardSetup,FloPayCardSetupError,FloPayCheckout,FloPayProvider,SplitCardForm,VaultCardFields,dropThirdPartyOnlyError,useCheckout,useFloPay,usePayPalFloPay});
47
+ `})]})}return(0,k.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&he(Tr),n&&(r||o)&&he(Tr),n&&(0,k.jsx)("button",{type:"button",onClick:()=>{e?.("card"),B(!0)},style:{width:"100%",...q,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,k.jsx)(Nr,{content:v})}),(0,k.jsx)("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}var Vn=require("react/jsx-runtime"),jl=44;function Ps(e){return new Promise(t=>setTimeout(t,e))}function Vl(e,t){return e instanceof vn.FloPayError?e:new vn.FloPayError(e instanceof Error?e.message:t,"api_error")}function Kl(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function Hl(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 Cs({sessionId:e,nonce:t,createSession:n,paymentMethodId:r,checkoutMethod:o,clientId:i,products:d,items:c,subscriptions:v,account:y,successUrl:g,cancelUrl:b,couponCodes:B,tagsData:T,utmMetadata:p,billingApiUrl:P,locale:he,theme:q,appearance:S,buttonsTheme:ue,buttonsStyles:$,onSuccess:ce,onError:W,onDecline:be,children:He,disabled:we=!1,type:vt="button",style:$e,...xe}){let Te=(0,Ke.useMemo)(()=>(0,vn.resolveBillingApiUrl)(P),[P]),ne=(0,Ke.useMemo)(()=>Hl({createSession:n,clientId:i,products:d,items:c,subscriptions:v,account:y,successUrl:g,cancelUrl:b,couponCodes:B,tagsData:T,utmMetadata:p}),[y,b,i,B,n,d,c,v,g,T,p]),[re,L]=(0,Ke.useState)(!1),[Me,Ae]=(0,Ke.useState)(null),[X,Ie]=(0,Ke.useState)(null),[Se,x]=(0,Ke.useState)(!1),[U,Be]=(0,Ke.useState)(null),me=(0,Ke.useRef)(!0),ee=(0,Ke.useRef)(null),Le=(0,Ke.useRef)(U),rt=(0,Ke.useRef)(ce),pt=(0,Ke.useRef)(W),qe=(0,Ke.useRef)(be);(0,Ke.useEffect)(()=>{Le.current=U},[U]),(0,Ke.useEffect)(()=>{rt.current=ce},[ce]),(0,Ke.useEffect)(()=>{pt.current=W},[W]),(0,Ke.useEffect)(()=>{qe.current=be},[be]),(0,Ke.useEffect)(()=>(me.current=!0,()=>{me.current=!1,ee.current?.abort()}),[]),(0,Ke.useEffect)(()=>{if(typeof window>"u")return;let C=Z=>{Z.key==="Escape"&&Be(null)};return window.addEventListener("keydown",C),()=>{window.removeEventListener("keydown",C)}},[]);let te=(0,Ke.useCallback)((C,Z=Po)=>{qe.current?.(Ut(Z,C,{code:C.code,declineCode:C.declineCode}))},[]),G=(0,Ke.useCallback)(async C=>{me.current&&(Ie(null),x(C.result.status==="authorized"),Ae("success"),await Ps(1200),me.current&&rt.current?.(C))},[]),H=(0,Ke.useCallback)(async(C,Z)=>{me.current&&(pt.current?.(C),Z?.emitDecline&&te(C,Z.method),Ie(C.message),x(!1),Ae("error"),await Ps(1500))},[te]),Fe=(0,Ke.useCallback)(async(C,Z,dt)=>{let yt=C.data.session??null;if(!yt)throw new vn.FloPayError("No session data returned","api_error");let ye=yt.clientSecret||t;if(Ur(yt)){await G({result:Ir(yt,Z),session:yt,sessionId:yt.id||Z,autoCompleted:!1});return}if(yt.status==="expired")throw qo(yt);try{if(C.autoProcessingPending){let Nt=(await new ca.PaymentAPI(Te).waitForCheckoutSessionCompletion(C.autoProcessingPending.sessionId,{initialDelayMs:C.autoProcessingPending.retryAfterMs})).data.session;if(!Ur(Nt))throw $o(Nt);await G({result:Ir(Nt,Z),session:Nt,sessionId:Nt.id||Z,autoCompleted:!1});return}if(C.autoProcessingError){if(C.autoProcessingError.type==="3ds_required"&&C.autoProcessingError.nextActionRedirectUrl&&Z&&ye){let it=new AbortController;ee.current=it;let Ye;try{Ye=await Ji({billingApiUrl:Te,sessionId:Z,nonce:ye,nextActionRedirectUrl:C.autoProcessingError.nextActionRedirectUrl,signal:it.signal})}finally{ee.current===it&&(ee.current=null)}if(Ye.status==="declined")throw vr({type:Ye.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:Ye.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:C.autoProcessingError.checkoutMethod});let Yt=(await new ca.PaymentAPI(Te).waitForCheckoutSessionCompletion(Z,{initialDelayMs:0,nonce:ye})).data.session;if(!Ur(Yt))throw vr({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:C.autoProcessingError.checkoutMethod});await G({result:Ir(Yt,Z),session:Yt,sessionId:Yt.id||Z,autoCompleted:!1});return}throw vr(C.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:C.autoProcessingError.checkoutMethod})}if(dt?.fromCreateSession&&C.autoProcessingAttempted===!0)throw vr({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let It=await Wr({billingApiUrl:Te,sessionId:Z??yt.id,session:yt,nonce:ye});if(It.type!=="success")throw vr({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await G({result:It.result,session:yt,sessionId:yt.id||Z,autoCompleted:!1})}catch(It){let it=Co(It),Ye=yt.id||Z;await H(it,{emitDecline:!0,method:it.checkoutMethod??Po}),Kl(it,Ye)&&Ye&&me.current&&Be({sessionId:Ye,errorMessage:it.message,nonce:ye||void 0})}},[t,Te,H,G]),Xe=(0,Ke.useCallback)(async C=>{if(xe.onClick?.(C),!(C.defaultPrevented||we||re)){if(Be(null),e&&ne){let Z=new vn.FloPayError("Provide either sessionId or create-session props, not both.","validation_error");await H(Z),me.current&&(Ae(null),Ie(null));return}if(!e&&!ne){let Z=new vn.FloPayError("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await H(Z),me.current&&(Ae(null),Ie(null));return}L(!0),Ie(null),x(!1),Ae("processing");try{let Z=new ca.PaymentAPI(Te);if(e){let dt=await Z.getUnifiedCheckoutSession(e,t);await Fe(dt,e);return}try{let dt=await Z.createAndFetchSession({...ne});await Fe(dt,dt.data.session?.id??null,{fromCreateSession:!0})}catch(dt){if(dt instanceof vn.FloPayError&&dt.code==="session_auto_completed"){await G({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw dt}}catch(Z){await H(Vl(Z,"Automatic payment failed. Please try again."))}finally{me.current&&(Ae(null),Ie(null),L(!1))}}},[xe.onClick,ne,we,re,t,Fe,Te,e,H,G]),M=(0,Ke.useCallback)(C=>{let Z=Le.current;Be(null),rt.current?.({result:C,session:null,sessionId:Z?.sessionId??null,autoCompleted:!1})},[]),oe=(0,Ke.useCallback)(C=>{pt.current?.(C)},[]),D=(0,Ke.useCallback)(C=>{qe.current?.(C)},[]),I=(0,Ke.useMemo)(()=>(0,vn.resolveTheme)(q),[q]),lt=(0,Ke.useMemo)(()=>{let C=I?.buttonsLayout??(0,vn.resolveButtonsLayoutTheme)(ue);return $?{...C,...$,cardButton:{...C.cardButton,...$.cardButton}}:C},[I,ue,$]),Pt=(0,Ke.useMemo)(()=>{let C=I?.appearance;return S?C?{...C,...S,variables:{...C.variables,...S.variables}}:S:C},[S,I]),ie=Pt?.variables,ct=ie?.colorPrimary??"#4A49FF",et=ie?.colorPrimaryHover??Jr(ct,.12),Ct=ie?.borderRadius??"8px";return(0,Vn.jsxs)(Vn.Fragment,{children:[(0,Vn.jsx)("button",{...xe,type:vt,onClick:Xe,disabled:we||re,"aria-busy":re,style:{width:"100%",...He===void 0?{boxSizing:"border-box",height:jl,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...lt.cardButton,...Ua({themeBundle:I,resolvedPrimaryColor:ct,resolvedBorderRadius:Ct,submitButtonStyle:lt.submitButton,explicitPrimaryColor:ie?.colorPrimary}),fontSize:lt.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:we||re?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",transition:"background-color 0.15s, border-color 0.2s, box-shadow 0.2s, transform 0.1s",position:"relative",opacity:we||re?.6:1,...$e},onMouseEnter:C=>{xe.onMouseEnter?.(C),!C.defaultPrevented&&!we&&!re&&(I||ie?.colorPrimary)&&(C.currentTarget.style.backgroundColor=et)},onMouseLeave:C=>{xe.onMouseLeave?.(C),!C.defaultPrevented&&(I||ie?.colorPrimary)&&(C.currentTarget.style.backgroundColor=ct)},onMouseDown:C=>{xe.onMouseDown?.(C),C.defaultPrevented||(C.currentTarget.style.transform="scale(0.985)")},onMouseUp:C=>{xe.onMouseUp?.(C),C.defaultPrevented||(C.currentTarget.style.transform="scale(1)")},children:(0,Vn.jsx)(Nr,{content:He})}),Me&&(0,Vn.jsx)(Fn,{status:Me,errorMessage:X,authorized:Se}),U&&(0,Vn.jsx)("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:C=>{C.target===C.currentTarget&&Be(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,Vn.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,Vn.jsx)(la,{sessionId:U.sessionId,nonce:U.nonce,checkoutMode:"full",billingApiUrl:Te,locale:he,theme:q,...Pt?{appearance:Pt}:{},buttonsTheme:ue,buttonsStyles:$,initialErrorMessage:U.errorMessage,cardTitleContent:null,onComplete:M,onError:oe,onDecline:D})})})]})}var da=require("@flopay/js/card-setup"),Pn=require("@flopay/shared"),bt=require("react");var Zn=require("react/jsx-runtime"),Ro=class extends Pn.FloPayError{constructor(t,n,r){super(t,n,r),this.name="FloPayCardSetupError",this.retryable=r.retryable}};function Ss(e,t={}){let n=e instanceof Pn.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 Ro(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 ws({sessionId:e,nonce:t,billingApiUrl:n,telemetry:r,theme:o="modern-light",containerStyle:i,loading:d=null,onReady:c,onComplete:v,onDecline:y,onCancel:g,onValidation:b,onError:B}){let[T,p]=(0,bt.useState)(null),[P,he]=(0,bt.useState)(null),[q,S]=(0,bt.useState)(null),[ue,$]=(0,bt.useState)(null),[ce,W]=(0,bt.useState)(null),be=(0,bt.useRef)(!1),He=(0,bt.useRef)(!1),we=(0,bt.useMemo)(()=>{if(typeof o=="object")return o;let X=(0,Pn.resolveTheme)(o);if(X)return ea({appearance:X.appearance,buttonsStyles:X.buttonsLayout,layout:"default"})},[o]),vt=(0,bt.useRef)(c),$e=(0,bt.useRef)(B),xe=(0,bt.useRef)(v),Te=(0,bt.useRef)(y),ne=(0,bt.useRef)(g),re=(0,bt.useRef)(b),L=(0,bt.useRef)(!1),Me=(0,bt.useRef)(!1),Ae=(0,bt.useRef)(0);return vt.current=c,$e.current=B,xe.current=v,Te.current=y,ne.current=g,re.current=b,(0,bt.useEffect)(()=>{let X=Ae.current+1;return Ae.current=X,()=>{queueMicrotask(()=>{Ae.current===X&&(L.current||Me.current||(Me.current=!0,at(()=>{ne.current?.({status:"cancelled",sessionId:e})})))})}},[e]),(0,bt.useEffect)(()=>{let X=!0,Ie=new da.PaymentAPI((0,Pn.resolveBillingApiUrl)(n),{telemetry:r});return p(null),he(null),S(null),L.current=!1,Me.current=!1,(async()=>{try{if(!e.trim())throw new Pn.FloPayError("FloPayCardSetup requires a sessionId.","validation_error",{code:"MissingCheckoutSessionId",param:"sessionId"});if(!t.trim())throw new Pn.FloPayError("FloPayCardSetup requires a session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let Se=await Ie.getUnifiedCheckoutSession(e,t);if(!X)return;let x=Se.data.session;if(!x||!(0,Pn.isCardSetupCheckoutSession)(x))throw new Pn.FloPayError("FloPayCardSetup only accepts a zero-amount, productless setup session.","validation_error",{code:"InvalidCardSetupSession",param:"sessionId"});let U=x.vault;if(U?.html?.trim()||(U=await Ie.getVaultCapture(e,t)),!U.html?.trim())throw new Pn.FloPayError("FloPay: this setup session has no vault card capability. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});if(!X)return;he(U),p(new da.PciVaultCardCapture({sessionId:e,operation:"card_setup",telemetry:r}))}catch(Se){if(!X)return;let x=Ss(Se);L.current=!0,S(x),at(()=>$e.current?.(x))}})(),()=>{X=!1,Ie.destroy()}},[n,t,e,r]),(0,bt.useEffect)(()=>{if(!T)return;let X=!1;He.current=!1,be.current=!1;let Ie=T.on("submitting",()=>{be.current=!0,W(null),$("processing")}),Se=T.on("complete",U=>{L.current=!0,be.current=!1,$("success"),(async()=>(await new Promise(Be=>setTimeout(Be,1200)),!He.current&&(He.current=!0,at(()=>{xe.current?.({status:"succeeded",sessionId:e,...U.paymentMethod?{paymentMethod:U.paymentMethod}:{}})}),X||$(null))))()}),x=T.on("decline",U=>{L.current=!0,be.current=!1,W(U.message??null),$("error"),at(()=>{Te.current?.({status:"declined",sessionId:e,...U.declineReason?{reason:U.declineReason}:{},...U.message?{message:U.message}:{}})}),(async()=>(await new Promise(Be=>setTimeout(Be,1500)),X||$(null)))()});return()=>{X=!0,Ie(),Se(),x()}},[T,e]),q?(0,Zn.jsx)("div",{role:"alert",children:q.message}):!T||!P?.html?(0,Zn.jsx)(Zn.Fragment,{children:d}):(0,Zn.jsxs)(Zn.Fragment,{children:[ue&&(0,Zn.jsx)(Fn,{status:ue,errorMessage:ce,processingLabel:"SAVING CARD...",successLabel:"CARD SAVED",errorLabel:"CARD NOT SAVED",successNote:null}),(0,Zn.jsx)(Gr,{capture:T,html:P.html,messageToken:P.messageToken,expectedOrigin:P.expectedOrigin,theme:we,containerStyle:i,onReady:()=>{at(()=>vt.current?.())},onValidation:X=>{at(()=>re.current?.(X))},onError:X=>{if(!X)return;be.current&&(be.current=!1,W(X),$("error"),setTimeout(()=>$(null),1500));let Ie=Ss(new Error(X),{code:"card_setup_widget_failed",retryable:!0});at(()=>$e.current?.(Ie))}})]})}0&&(module.exports={DirectPayPalButton,FloPayAutomaticPaymentButton,FloPayCardSetup,FloPayCardSetupError,FloPayCheckout,FloPayProvider,SplitCardForm,VaultCardFields,dropThirdPartyOnlyError,useCheckout,useFloPay,usePayPalFloPay});