@flopay/react 1.9.2 → 1.9.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,12 +1,12 @@
1
- "use strict";var rl=Object.create;var Ho=Object.defineProperty;var ol=Object.getOwnPropertyDescriptor;var al=Object.getOwnPropertyNames;var il=Object.getPrototypeOf,sl=Object.prototype.hasOwnProperty;var ll=(e,t)=>{for(var n in t)Ho(e,n,{get:t[n],enumerable:!0})},Oi=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of al(t))!sl.call(e,o)&&o!==n&&Ho(e,o,{get:()=>t[o],enumerable:!(r=ol(t,o))||r.enumerable});return e};var zi=(e,t,n)=>(n=e!=null?rl(il(e)):{},Oi(t||!e||!e.__esModule?Ho(n,"default",{value:e,enumerable:!0}):n,e)),cl=e=>Oi(Ho({},"__esModule",{value:!0}),e);var gc={};ll(gc,{DirectPayPalButton:()=>Io,FloPayAutomaticPaymentButton:()=>Ds,FloPayCardSetup:()=>Ns,FloPayCardSetupError:()=>Lo,FloPayCheckout:()=>fa,FloPayProvider:()=>Eo,SplitCardForm:()=>ua,VaultCardFields:()=>oo,dropThirdPartyOnlyError:()=>Os.dropThirdPartyOnlyError,useCheckout:()=>Wi,useFloPay:()=>fr,usePayPalFloPay:()=>Jo});module.exports=cl(gc);var Os=require("@flopay/shared");var ga=require("@flopay/js"),zn=require("@flopay/shared"),je=require("react");var It=require("react/jsx-runtime");function dl(){return(0,It.jsxs)(It.Fragment,{children:[(0,It.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,It.jsx)("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),(0,It.jsx)("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",(0,It.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,It.jsx)("path",{d:"M9 18l6-6-6-6"})})]})}function ul(){return(0,It.jsx)(It.Fragment,{children:"Go back"})}function pl(){return(0,It.jsx)(It.Fragment,{children:"Secure card checkout"})}function Kr(e){return e!==void 0&&(e===""||e===null||e===!1)}function Hr({content:e}){return(0,It.jsx)(It.Fragment,{children:e===void 0?(0,It.jsx)(dl,{}):e})}function Yr({content:e}){return(0,It.jsx)(It.Fragment,{children:e===void 0?(0,It.jsx)(ul,{}):e})}function vo({content:e}){return(0,It.jsx)(It.Fragment,{children:e===void 0?(0,It.jsx)(pl,{}):e})}var or=require("@flopay/shared");function Wr(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,or.isValidEmail)(d.email))return Promise.reject(new or.FloPayError("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}));let c={};for(let[h,y]of Object.entries(d)){if(typeof y!="string")continue;let f=y.trim();f&&(c[h]=f)}return o=e.claimCheckoutSession(t,n,{accountData:c}),o.catch(()=>{}),o}}function Ui(e,t){if(!t)return e;if(!e)return t;let n;return"checkoutMetadata"in t?n=t:"checkoutMetadata"in e&&(n=e),{account:{...e.account??{},...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,...n?{checkoutMetadata:n.checkoutMetadata}:{},tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}}function Fa(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 qi(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 Mr(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 Da(e,t){return t?{...e,...t}:e}function Vt(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 ml=[{match:/^paypal authorization required\.?$/i,replacement:"For your additional security, please re-authenticate this payment via PayPal."}];function Cr(e){if(typeof e!="string")return e??void 0;let t=e.trim();if(!t)return e;for(let{match:n,replacement:r}of ml)if(n.test(t))return r;return e}function Ar(e,t){return e.status!=="authorized"?{status:"succeeded"}:{status:"authorized",paymentId:e.paymentId,sessionId:e.id||t||void 0,authorizationExpiresAt:e.authorizationExpiresAt}}function Gr(e){return e?.status==="authorized"||e?.status==="complete"}function $i(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function Yo(e){let t=$i(e);return new or.FloPayError(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function Wo(e){return e instanceof or.FloPayError||typeof e=="object"&&e!==null&&"code"in e?e.code:void 0}function Go(e){let t=$i(e),n="checkout_processing_timeout";return t?n="authorization_expired":e?.status==="expired"&&(n="checkout_session_expired"),new or.FloPayError(t?"Authorization has expired.":"Automatic payment failed. Please try again.","api_error",{code:n})}function bo(e,t){return e==="processing"||(0,or.isMoneySettledOutcome)(e,t)}function ji(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}function Vi(e,t="automatic"){return{...typeof e=="number"&&Number.isFinite(e)&&e>0?{mode:"payment",amount:e,captureMethod:t==="manual"?"manual":"automatic_async"}:{mode:"setup"},paymentMethodTypes:["card"],setupFutureUsage:"off_session"}}function Ki(e){let t=e&&typeof e=="object"?e:null;return t?.name==="IntegrationError"||t?.code==="elements_intent_mismatch"||t?.type==="invalid_request_error"?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response"}:{errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime"}}function Po(e){let t=[e?.id,e?.originalPaymentMethodId];for(let n of t)if(typeof n=="string"&&n.startsWith("pm_"))return n}var Dr=require("@flopay/js"),Se=require("@flopay/shared"),C=zi(require("react"),1);var La=require("react"),Dn=(0,La.createContext)({flopay:null,paypalFlopay:null,billingApiUrl:""}),Jn=(0,La.createContext)({session:null,loading:!1,error:null});var Qo=require("@flopay/js"),Dt=require("@flopay/shared"),Qi=require("@paypal/paypal-js"),_=require("react");var Hi=require("@flopay/shared"),Xn=require("react"),mr=require("react/jsx-runtime");function vn(e){let{firstName:t,lastName:n,...r}=e,o=t?.trim(),i=n?.trim();return{...r,...o?{firstName:o}:{},...i?{lastName:i}:{}}}function Jr(){let[e,t]=(0,Xn.useState)(null),n=(0,Xn.useRef)(null),r=(0,Xn.useRef)(0),o=(0,Xn.useCallback)((d,c)=>(n.current?.(null),r.current+=1,t({id:r.current,methodLabel:d,identity:c}),new Promise(h=>{n.current=h})),[]),i=(0,Xn.useCallback)(d=>{let c=n.current;n.current=null,t(null),c?.(d)},[]);return(0,Xn.useEffect)(()=>()=>{n.current?.(null),n.current=null},[]),{request:e,collect:o,finish:i}}function Xr({identity:e,methodLabel:t,onComplete:n,onCancel:r,submitting:o=!1,testId:i="flopay-buyer-identity-pane"}){let[d,c]=(0,Xn.useState)(e.email?.trim()??""),h=(0,Hi.isValidEmail)(d.trim());return(0,mr.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,mr.jsxs)("div",{style:{fontWeight:700},children:["Continue with ",t]}),(0,mr.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",(0,mr.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,mr.jsxs)("div",{style:{display:"flex",gap:"0.5rem"},children:[r&&(0,mr.jsx)("button",{type:"button",onClick:r,style:{flex:1,minHeight:42},children:"Cancel"}),(0,mr.jsxs)("button",{type:"button",disabled:!h||o,onClick:()=>{n(vn({...e,email:d.trim()}))},style:{flex:2,minHeight:42},children:["Continue with ",t]})]})]})}function yl(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 Br(e){if(typeof e!="string")return;let t=e.trim();return/^[a-z0-9_.-]{1,64}$/i.test(t)?t:void 0}function yr(e){if(typeof e!="object"||e===null)return;let t=e;return Br(t.code)??Br(t.type)??Br(t.name)}function Zr(e){if(!(typeof e!="object"||e===null))return Br(e.decline_code)}function Co(e){return typeof e!="object"||e===null?!1:Br(e.type)?.toLowerCase()==="card_error"||Zr(e)!==void 0}function Sr(e){let t=yl(e)?.toLowerCase()??"",r=`${yr(e)?.toLowerCase()??""} ${t}`;return r.includes("popup")&&r.includes("block")}var Yi=require("@flopay/shared"),So=require("react");function fr(){return(0,So.useContext)(Dn).flopay}function Jo(){return(0,So.useContext)(Dn).paypalFlopay??null}function Wi(){return(0,So.useContext)(Jn)}function Gi(){return(0,So.useContext)(Dn).billingApiUrl||(0,Yi.resolveBillingApiUrl)()}var Ji=require("@flopay/shared"),Fr=require("react");function nt(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 Xo=require("react"),wo=typeof window>"u"?Xo.useEffect:Xo.useLayoutEffect;var fl={"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 gl(e){return e==="stripe"||e==="paypal"?e:void 0}function hl(e){let t=gl(e.provider),n={schemaVersion:Ji.FLO_INSTRUMENT_SCHEMA_VERSION,...t?{gateway:t}:{}};if(e.class==="lifecycle"){let r=fl[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 Na=new Set(["checkout_mount","sdk_loaded","form_rendered","card_expanded"]);function Qr(e,t){let n=(0,Fr.useRef)(e);n.current=e;let r=(0,Fr.useRef)(new Set),o=(0,Fr.useRef)(t),i=(0,Fr.useRef)(t);return wo(()=>{i.current=t,o.current!==t&&(o.current=t,r.current.clear())},[t]),(0,Fr.useCallback)(d=>{if(i.current!==t)return;let c=hl(d);if(c){if(Na.has(c.name)){if(r.current.has(c.name))return;r.current.add(c.name)}nt(()=>n.current?.(c))}},[t])}var vl=Symbol.for("@flopay/js.telemetry.bridge.v1"),bl=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function Pl(){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 Cl(e){let t=Pl(),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 Zo(e){let t=globalThis[bl];return Cl(t?.(e)??{})}function qt(e){if(e)return e[vl]}var un=require("react");function ko(e){let t=(0,un.useRef)(0),n=(0,un.useRef)(null),r=(0,un.useRef)(null),o=(0,un.useCallback)((p=r.current)=>{p?.timer&&(clearTimeout(p.timer),p.timer=null)},[]),i=(0,un.useCallback)(p=>{o();let w=t.current+1;return t.current=w,n.current=null,r.current={generation:w,method:p,timer:null,yieldedControl:!1},w},[o]),d=(0,un.useCallback)(p=>{let w=r.current;return p!==void 0&&w?.generation!==p?!1:(o(w),r.current=null,(p===void 0||n.current===p)&&(n.current=null),!0)},[o]),c=(0,un.useCallback)(p=>{let w=r.current,F=p??w?.generation??t.current;(p===void 0||w?.generation===p)&&(o(w),r.current=null),n.current=F},[o]),h=(0,un.useCallback)(p=>n.current===(p??t.current),[]),y=(0,un.useCallback)(p=>r.current?.generation===p&&n.current!==p,[]),f=(0,un.useCallback)(()=>{let p=r.current;p&&(p.yieldedControl=!0,o(p))},[o]),g=(0,un.useCallback)(()=>{let p=r.current;!p?.yieldedControl||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"}))},600))},[o,e]);return(0,un.useEffect)(()=>{let p=()=>{document.visibilityState==="visible"?g():f()};return document.addEventListener("visibilitychange",p),window.addEventListener("blur",f),window.addEventListener("focus",g),()=>{document.removeEventListener("visibilitychange",p),window.removeEventListener("blur",f),window.removeEventListener("focus",g),o()}},[o,f,g]),{startAttempt:i,finishAttempt:d,invalidateAttempt:c,isAttemptInvalidated:h,isAttemptCurrent:y,generationRef:t}}var Ln=require("react/jsx-runtime"),ea=45,Sl=1e3,wl=11e3,kl=["https://www.paypal.com","https://www.sandbox.paypal.com"],Xi="We couldn't open PayPal. Try again or choose another payment method.",Il={width:"100%",minHeight:ea,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 Zi(e){return e.includes("No ack for postMessage init()")&&kl.some(t=>e.includes(t))&&e.includes("10000ms")}function Rl(e){return e?`${Xi} Allow pop-ups for this site, then try again.`:Xi}function El(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 _l(e){return e>=500?"5xx":e>=400?"4xx":e>=300?"3xx":"unknown"}function es({sessionId:e,nonce:t,billingApiUrl:n,email:r,billingName:o,onBuyerIdentityReady:i,clientId:d,environment:c,currency:h,isSubscription:y,providerObjectType:f,onTokenizedBody:g,onComplete:p,onErrorChange:w,onDecline:F,onTechnicalFailure:L,isProcessing:he=!1,onLoadStateChange:q,onInitializationStateChange:P,allowAutomaticRetry:ie=!0,onButtonClick:O,runBeforeButtonClick:de,session:G,existingOrderId:ve,telemetry:Ve,telemetryContext:we,onInstrument:wt,debug:qe=!1}){let Me=fr(),Ae=Qr(wt,e),se=(0,_.useMemo)(()=>{if(Me)return null;let W=Zo({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:Dt.SDK_VERSION,enabled:Ve!==!1});return W.setCheckoutContext(we??{}),W.beginCheckout(we??{}),W},[n,Me,Ve,we?.checkoutMode,we?.layout]),re=(0,_.useMemo)(()=>qt(Me),[Me]);(0,_.useEffect)(()=>()=>{se&&se.flush().catch(()=>{}).finally(()=>se.destroy())},[se]);let D=(0,_.useMemo)(()=>({error:W=>{re?re.error(W):se?.error(W),Ae({class:"technical_error",errorCode:W.requestCategory==="intent_create"?"PAYMENT_PROCESSING_FAILED":W.errorCode,requestCategory:W.requestCategory,provider:W.provider})},log:W=>{re?re.log(W):se?.log(W),Ae({class:"lifecycle",name:W.name,provider:W.provider})},performance:W=>{re?re.performance(W):se?.performance(W)},terminal:W=>{re?re.terminal(W):se?.terminal(W)},startTiming:()=>re?.now()??se?.now()??0,elapsed:W=>re?.elapsed(W)??Math.max(0,(se?.now()??W)-W)}),[Ae,re,se]),Be=(0,_.useRef)(null),Fe=(0,_.useRef)(0),Q=(0,_.useRef)(null),Ee=(0,_.useRef)(!1),[be,x]=(0,_.useState)(!1),[Y,ke]=(0,_.useState)(!1),[ge,ne]=(0,_.useState)(0),Ne=(0,_.useRef)(0),[ot,ft]=(0,_.useState)(!1),Ye=(0,_.useRef)(!1),oe=(0,_.useRef)(!1),[$,z]=(0,_.useState)(!1),[We,Je]=(0,_.useState)(!1),{request:ye,collect:at,finish:k}=Jr(),E=(0,_.useRef)({sessionId:e,required:!(0,Dt.isValidEmail)(r?.trim()||G?.customer?.email?.trim())});E.current.sessionId!==e&&(E.current={sessionId:e,required:!(0,Dt.isValidEmail)(r?.trim()||G?.customer?.email?.trim())});let Oe=E.current.required,pe=(0,_.useMemo)(()=>n.replace(/\/+$/,""),[n]),rt=G?.gateways?.paypal?.providerObjectType??f,ze=rt??(y?"subscription":"order"),Xe=rt==="order"||rt==="setup_token",At=(0,_.useMemo)(()=>JSON.stringify([pe,d,h,c??"",ze,Xe,e,ve??""]),[pe,d,h,c,ve,ze,Xe,e]),I=(0,_.useRef)(At),ee=I.current!==At,vt=(0,_.useRef)(qe),Ze=(0,_.useRef)(null),[Jt,Kt]=(0,_.useState)([]),M=(0,_.useCallback)(W=>{vt.current&&Kt(Ie=>[...Ie,`${new Date().toISOString().slice(11,23)} ${W}`])},[]);(0,_.useEffect)(()=>{vt.current=qe,qe&&M("debug:enabled"),Ze.current?.setEnabled(qe)},[M,qe]);let pt=(0,_.useRef)(g),Rt=(0,_.useRef)(p),it=(0,_.useRef)(w),kt=(0,_.useRef)(F),pn=(0,_.useRef)(L),en=(0,_.useRef)(O),mn=(0,_.useRef)(q),Nt=(0,_.useRef)(P),bn=(0,_.useRef)(i),Ht=(0,_.useRef)(de),mt=(0,_.useRef)(G),Qe=(0,_.useRef)(r),yt=(0,_.useRef)(o),tn=(0,_.useRef)(t),tt=(0,_.useRef)(null),Xt=(0,_.useRef)(new Map),Zt=(0,_.useRef)(new Map),nn=(0,_.useRef)(!1);(0,_.useEffect)(()=>(nn.current=!0,()=>{nn.current=!1}),[]),(0,_.useEffect)(()=>{pt.current=g},[g]),(0,_.useEffect)(()=>{bn.current=i},[i]),(0,_.useEffect)(()=>{Rt.current=p},[p]),(0,_.useEffect)(()=>{it.current=w},[w]),(0,_.useEffect)(()=>{kt.current=F},[F]),(0,_.useEffect)(()=>{pn.current=L},[L]),(0,_.useEffect)(()=>{en.current=O},[O]),(0,_.useEffect)(()=>{mn.current=q},[q]),(0,_.useEffect)(()=>{Nt.current=P},[P]),(0,_.useEffect)(()=>{Ht.current=de},[de]),(0,_.useEffect)(()=>{mt.current=G},[G]),(0,_.useEffect)(()=>{Qe.current=r},[r]),(0,_.useEffect)(()=>{yt.current=o},[o]),(0,_.useEffect)(()=>{tn.current=t},[t]),(0,_.useEffect)(()=>{Ne.current=ge},[ge]),(0,_.useEffect)(()=>{ot&&Q.current?.focus()},[ot,ge]);let zt=(0,_.useCallback)(()=>{window.setTimeout(()=>{Q.current?.focus()},0)},[]),$t=(0,_.useCallback)(()=>{x(!1),ne(W=>W+1)},[]),Pn=(0,_.useCallback)(()=>{ft(!1),(Be.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??Be.current)?.focus?.()},[]);(0,_.useEffect)(()=>{!be||!Ee.current||(Ee.current=!1,Pn())},[Pn,be,ge]);let rn=(0,_.useCallback)((W,Ie)=>{let Yt=pn.current;if(Yt){Yt("paypal",W,Ie);return}it.current?.(Rl(Ie?.popupBlocked??Sr(W)))},[]),Un=(0,_.useCallback)((W,Ie,Yt)=>{rn(Ie,Yt),ft(!0),$t(),zt()},[zt,rn,$t]),{finishAttempt:on,invalidateAttempt:_n,isAttemptCurrent:an,isAttemptInvalidated:ce,startAttempt:Cn}=ko(Un),Qn=(0,_.useCallback)(()=>(ft(!1),Cn("paypal")),[Cn]),er=(0,_.useCallback)(W=>{_n(W?.generation),W?.showRetry&&ft(!0),W?.remount&&$t(),W?.focus!==!1&&zt()},[zt,_n,$t]),Pr=W=>{let Ie=tt.current;return Ie&&Zt.current.set(W,Ie),W};(0,_.useEffect)(()=>{I.current!==At&&(I.current=At,Ye.current=!1,oe.current=!1,x(!1),ke(!1),z(!1),Nt.current?.("loading"))},[At]),(0,_.useEffect)(()=>{nt(()=>mn.current?.(be&&!$))},[be,$]);let kr=(0,Dt.normalizeGatewayEnvironment)(c);(0,_.useEffect)(()=>{let W=d?`${d.slice(0,6)}\u2026(len ${d.length})`:"(empty)",Ie=typeof navigator>"u"?"(no navigator)":navigator.userAgent;if(M(`mount clientId=${W} env=${c??"(unset)"}\u2192${kr??"live"} ccy=${h} sub=${y}`),M(`ua=${Ie.slice(0,80)}${Ie.length>80?"\u2026":""}`),!d){M("FAIL: clientId empty \u2014 gateway misconfigured"),z(!0),D.error({errorCode:"CONFIGURATION_INVALID",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),console.error("[FloPay] DirectPayPal: clientId empty \u2014 gateway misconfigured");return}if(!Be.current){M("FAIL: containerRef not attached");return}Fe.current=D.startTiming(),D.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let Yt=!1,sn=!1,Te=()=>Yt||sn,qn,Tn=!1,Bt=()=>{qn=(0,Dt.generateIdempotencyKey)(),qn||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),Tn=!0},ln=null,Rr=!1,Er=null,Sn=!1,lr=()=>{!Er||Sn||(Sn=!0,Er.close().catch(()=>{}))},$n=null,xn=()=>{$n!==null&&(D.log({name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal"}),D.performance({stage:"overlay_return",durationMs:D.elapsed($n),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal"}),$n=null)},bt=!1,tr=!1,wn=Be.current,jn=null,yn=null,Vn=[],Kn=null,dt=!1,kn=!1,Mn=null,In=T=>{if(!T||typeof T.getBoundingClientRect!="function")return"(no rect)";let m=T.getBoundingClientRect();return`${Math.round(m.width)}\xD7${Math.round(m.height)}`},Hn=T=>{if(!T)return"(empty)";try{let m=new URL(T,typeof window>"u"?"https://localhost":window.location.href),A=m.pathname.toLowerCase();return A.includes("checkcaptcha")||A.includes("captcha")?`CAPTCHA(${m.host}${A})`:A.includes("risk")||A.includes("challenge")?`RISK(${m.host}${A})`:A.includes("smart/buttons")?`smart-buttons(${m.host})`:`${m.host}${A}`.slice(0,100)}catch{return T.slice(0,80)}},Ue=T=>{let m=T.getAttribute("src"),A=T.getAttribute("srcdoc"),j=T.getAttribute("name"),v=T.getAttribute("sandbox"),V=[];return m&&V.push(`src=${Hn(m)}`),A&&V.push(`srcdoc[${A.length}ch]`),!m&&!A&&V.push("src=(empty) srcdoc=(empty)"),j&&V.push(`name=${j.slice(0,40)}`),v!==null&&V.push(`sandbox="${v.slice(0,40)}"`),V.join(" ")},cn=T=>{if(!(T instanceof HTMLIFrameElement))return"";try{let m=T.contentDocument;if(!m)return"cd=null";let A=m.body?.children.length??0,j=m.body?.innerHTML.length??0,v=m.head?.innerHTML.length??0;return`cd=same-origin readyState=${m.readyState} body[${A}children,${j}ch] head[${v}ch]`}catch(m){return`cd=cross-origin(${m.message.slice(0,30)})`}},Et=[],cr=T=>{if(Te())return;let m=T.message??String(T.error??"(no message)");m&&(m.toLowerCase().includes("paypal")||m.toLowerCase().includes("zoid")||m.toLowerCase().includes("postrobot")||m.toLowerCase().includes("storage"))&&(M(`window:error ${m.slice(0,140)}`),Et.push(m))},dr=T=>{if(Te())return;let m=T.reason instanceof Error?T.reason.message:String(T.reason??"(no reason)");m&&(m.toLowerCase().includes("paypal")||m.toLowerCase().includes("zoid")||m.toLowerCase().includes("postrobot")||m.toLowerCase().includes("storage"))&&(M(`window:rejection ${m.slice(0,140)}`),Et.push(m))},ur={value:0},Rn=()=>{jn?.disconnect(),jn=null,yn?.disconnect(),yn=null;for(let T of Vn.splice(0))clearTimeout(T);kn=!1,dt&&typeof window<"u"&&(window.removeEventListener("error",cr),window.removeEventListener("unhandledrejection",dr)),dt=!1},Yn=()=>{if(!(dt||Te()||bt)){if(dt=!0,Et.length=0,ur.value=0,typeof window<"u"&&(window.addEventListener("error",cr),window.addEventListener("unhandledrejection",dr)),typeof PerformanceObserver<"u")try{yn=new PerformanceObserver(T=>{if(!Te())for(let m of T.getEntries()){if(!m.name.toLowerCase().includes("paypal"))continue;ur.value+=1;let A=Math.round(m.duration);M(`net ${A}ms ${m.name.slice(0,90)}`)}}),yn.observe({type:"resource",buffered:!0})}catch{}Mn?.()}},Ut=()=>{Kn&&(clearTimeout(Kn),Kn=null)},N=()=>{Rn(),Ut()},U={setEnabled:T=>{T?Yn():Rn()}};Ze.current=U,vt.current&&Yn();let te=T=>{if(!T)return!1;let m=T.toLowerCase();return m.includes("zoid destroyed")||m.includes("destroyed all components")||m.includes("window closed")||m.includes("detected container element removed")},ae=T=>{if(Te()||te(T))return;let m=Cr(T)??T;nt(()=>it.current?.(m))},Ke=T=>{T!==null&&D.error({errorCode:T?"PROVIDER_RUNTIME_FAILED":"PROVIDER_LOAD_FAILED",stage:T?"provider_ready":"provider_load",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime"})},Z=(T,m=!1,A=!1)=>{if(Yt)return;let j=Ye.current||!ie;if(Rr)return;Rr=!0,sn=!0,N(),lr();let v=m||Zi(T);if(v&&ie&&!Ye.current){Ye.current=!0,x(!1),Je(!1),ke(!0),Nt.current?.("retrying"),ln=setTimeout(()=>{Yt||ne(V=>V+1)},Sl);return}if(v||j){if(x(!1),Je(!1),ke(!1),z(!0),(!v||A===!0)&&Ke(A),Nt.current?.("exhausted"),!oe.current){oe.current=!0;let V="paypal_init_failure";Zi(T)?V="paypal_init_timeout":m&&(V="paypal_render_timeout"),console.error("[FloPay] Direct PayPal initialization failed:",V)}return}z(!0),Ke(A),console.error("[FloPay] DirectPayPal load/render failure:",T)};z(!1);let J=async(T,m=tt.current)=>{if(Te())return;let A=m?.sessionId??e;if(pt.current){await pt.current(T,{sessionId:A,accountPatch:m?.accountPatch,nonce:m?.nonce});return}let j=D.startTiming();D.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let v=()=>{D.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),D.performance({stage:"processing",durationMs:D.elapsed(j),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})};try{let V=mt.current,He=m?.accountPatch?.email??Qe.current,Qt=m?.accountPatch?.userId??V?.customer?.id??V?.accountData?.userId??"",lt=m?.accountPatch?.firstName??V?.customer?.firstName??V?.accountData?.firstName,ct=m?.accountPatch?.lastName??V?.customer?.lastName??V?.accountData?.lastName,Pe=await new Qo.PaymentAPI(pe,{telemetry:!1}).processPayment(Qt,{sessionId:A,nonce:m?.nonce??tn.current,paymentMethodCategory:"paypal",tokenizedData:T,accountData:{userId:Qt,email:He??V?.customer?.email??"",...lt?{firstName:lt}:{},...ct?{lastName:ct}:{},country:m?.accountPatch?.country??V?.customer?.country??V?.accountData?.country??void 0,zip:m?.accountPatch?.zip??V?.customer?.zip??V?.accountData?.zip??void 0}});if(Pe.ok){if(sn||Yt&&nn.current)return;v(),D.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),nt(()=>Rt.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(Te())return;let Ge=await Pe.json().catch(()=>null),De=Ge?.message??"PayPal payment failed.",_e=Cr(De)??De;v(),Pe.status===400&&(typeof Ge?.declineCode=="string"||!Array.isArray(Ge?.fields))?D.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):Pe.status===400||Pe.status===422?D.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx"}):D.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:_l(Pe.status),failureCategory:Pe.status>=500?"server_error":void 0}),ae(_e),nt(()=>kt.current?.(Vt("paypal",_e,{code:Ge?.code,declineCode:Ge?.declineCode})));return}catch(V){if(Te())return;v(),D.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let He=V instanceof Error?V.message:"PayPal payment failed.",Qt=Cr(He)??He;ae(Qt),nt(()=>kt.current?.(Vt("paypal",Qt)));return}},R=()=>new Dt.FloPayError("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),B=T=>Te()?Promise.reject(R()):Promise.resolve(T),X=async T=>{if(Te())throw R();Tn||Bt();let m=tt.current,A=m?.sessionId??e,j=m?.nonce??tn.current;D.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let v;try{v=await new Qo.PaymentAPI(pe,{telemetry:!1}).createSessionIntent(A,j??"",Xe?{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:Dt.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE,paymentMethodId:null,intentKind:ze==="setup_token"?"setup":"payment"}:{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"},{idempotencyKey:qn})}catch(V){throw D.error({...(0,Dt.classifyTelemetryFailure)(V,"PAYMENT_PROCESSING_FAILED","unknown"),stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"}),V}if(Te())throw R();if(v.provider!=="paypal"||v.providerObjectType!==ze)throw new Error(T);return D.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),v.providerObjectId},gt=(T,m)=>{let A=m?.nonce??tn.current;if(!A)return;let j=m?.sessionId??e,v=Zr(T)??yr(T)??"provider_declined";new Qo.PaymentAPI(pe,{telemetry:!1}).reportSessionIntentDecline(j,A,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:v}).catch(()=>{})},et=ge;M("loadScript:scheduled (deferred 1 tick)");let ue=null,st=setTimeout(()=>{if(Yt){M("loadScript:skipped (cancelled before defer ran)");return}M("loadScript:start");let T=kr==="live"?"production":kr,m={};ze==="subscription"?m={intent:"subscription",vault:!0}:ze==="order"&&(m={intent:"capture"}),ue=(0,Qi.loadScript)({clientId:d,currency:h,...m,...T?{environment:T}:{},...T==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}});let A=!1;ue.then(j=>{if(A=!0,M(`loadScript:resolved inactive=${Te()} ns=${!!j} buttons=${!!j?.Buttons}`),Te())return;if(!j?.Buttons){M("FAIL: namespace missing Buttons factory"),Z("PayPal SDK did not expose the Buttons factory.");return}D.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),D.performance({stage:"provider_ready",durationMs:D.elapsed(Fe.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),D.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let v=async(Pe,Ge)=>{if(Te()||Ne.current!==et)return;let De=Pe.vaultSetupToken??Pe.subscriptionID??Pe.orderID??"",_e=De?Zt.current.get(De):Xt.current.get(et);if(!(!_e||!an(_e.generation))&&on(_e.generation)){Zt.current.delete(De),Xt.current.delete(_e.surfaceKey),xn();try{if(Je(!0),nt(()=>it.current?.(null)),!De)throw new Dt.FloPayError("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});let ht=mt.current,Wt=Mr(yt.current??[ht?.customer?.firstName,ht?.customer?.lastName].filter(Boolean).join(" ")),xe=vn({email:_e.accountPatch?.email?.trim()||Qe.current?.trim()||ht?.customer?.email?.trim(),firstName:_e.accountPatch?.firstName?.trim()||Wt.firstName,lastName:_e.accountPatch?.lastName?.trim()||Wt.lastName});if(!(0,Dt.isValidEmail)(xe.email)||!(xe.firstName||xe.lastName))try{let An=El(await Ge?.order?.get?.());xe=vn({email:An.email||xe.email,firstName:An.firstName||xe.firstName,lastName:An.lastName||xe.lastName})}catch{}if((bn.current||Oe)&&!(0,Dt.isValidEmail)(xe.email)){let An=await at("PayPal",xe);if(!An)return;xe=An}(0,Dt.isValidEmail)(xe.email)&&(_e.accountPatch=vn({..._e.accountPatch,...xe}),await bn.current?.(xe));let fn;ze==="setup_token"?fn={id:De,type:"paypal_setup_token",isPaypal:!0,gateway:"paypal",paymentMethodType:Dt.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE}:Xe?fn={id:De,isPaypal:!0,gateway:"paypal",paymentMethodType:Dt.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE}:fn={id:De,isPaypal:!0},await J(fn,_e)}catch(ht){ae(ht instanceof Error?ht.message:"PayPal capture failed.")}finally{Te()||Je(!1)}}},V=Pe=>{let Ge=ve?()=>B(ve):()=>X(Pe);return async()=>Pr(await Ge())},He=j.Buttons({style:{layout:"horizontal",height:ea,tagline:!1},onClick:async(Pe,Ge)=>{if(Te()){await Ge.reject();return}Bt();let De=Ht.current,_e={};if(De)try{let xe=await De("paypal");if(Te()){await Ge.reject();return}if(!xe.proceed){tt.current=null,Xt.current.delete(et),await Ge.reject();return}_e={sessionId:xe.sessionId,accountPatch:xe.accountPatch,nonce:xe.nonce}}catch(xe){M(`onClick:runBeforeButtonClick rejected msg=${(xe instanceof Error?xe.message:String(xe)).slice(0,120)}`),tt.current=null,Xt.current.delete(et),await Ge.reject();return}nt(()=>en.current?.("paypal"));let Wt={generation:Qn(),surfaceKey:et,..._e};tt.current=Wt,Xt.current.set(et,Wt),await Ge.resolve(),D.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),D.log({name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),D.log({name:"provider.overlay.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),$n=D.startTiming()},createOrder:ze==="order"?V("Failed to create PayPal order."):void 0,createSubscription:ze==="subscription"?V("Failed to create PayPal subscription."):void 0,createVaultSetupToken:ze==="setup_token"?async()=>Pr(await X("Failed to create PayPal setup token.")):void 0,onApprove:v,onCancel:()=>{if(Te())return;let Pe=Xt.current.get(et)??tt.current;Pe&&Xt.current.delete(Pe.surfaceKey),tt.current=null,xn(),D.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),Ee.current=!0,er({generation:Pe?.generation,remount:!0,focus:!1})},onError:Pe=>{if(Te()||Ne.current!==et)return;let Ge=Pe instanceof Error?Pe.message:"PayPal failed to render.";if(M(`onError rendered=${bt} msg=${Ge.slice(0,120)}`),bt){let De=Xt.current.get(et)??tt.current;if(De&&!an(De.generation)||!De&&ce())return;if(te(Ge)){on(De?.generation);return}if(xn(),Co(Pe)){D.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),gt(Pe,De),nt(()=>kt.current?.(Vt("paypal",Ge))),De&&Xt.current.delete(De.surfaceKey),tt.current=null,on(De?.generation);return}let _e=Ge.toLowerCase();D.error({errorCode:_e.includes("popup")&&_e.includes("block")?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),De&&Xt.current.delete(De.surfaceKey),tt.current=null,er({generation:De?.generation,remount:!0,showRetry:!0,focus:!0}),rn(Pe,{code:"paypal_runtime_failed"});return}Z(Ge,!1,te(Ge)?null:tr)}}),Qt=He.isEligible();if(M(`isEligible=${Qt}`),D.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!Qt){x(!1),Z("PayPal buttons are not eligible to render in this context (paypal_ineligible).",!1,null);return}tr=!0,Er=He,Mn=()=>{if(!dt||kn||Te()||bt)return;kn=!0,M(`container:dims ${In(wn)} visibility=${typeof document>"u"?"(no document)":document.visibilityState}`),typeof MutationObserver<"u"&&(jn=new MutationObserver(Ge=>{if(!Te()){for(let De of Ge)if(De.type==="childList")De.addedNodes.forEach(_e=>{if(!(_e instanceof Element))return;let ht=_e.tagName.toLowerCase(),Wt=(_e.getAttribute("title")??"").slice(0,40),xe=ht==="iframe"?` ${Ue(_e)}`:"";M(`child+ ${ht}${Wt?` title="${Wt}"`:""}${xe} dims=${In(_e)}`)});else if(De.type==="attributes"&&De.target instanceof Element){let _e=De.target;if(_e.tagName.toLowerCase()!=="iframe")continue;let ht=De.attributeName;(ht==="src"||ht==="srcdoc")&&M(`attr~ iframe ${ht}=${ht==="srcdoc"?`[${(_e.getAttribute("srcdoc")??"").length}ch]`:Hn(_e.getAttribute("src"))} dims=${In(_e)}`)}}}),jn.observe(wn,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let Pe=Ge=>{if(Te()||bt)return;let De=wn.querySelectorAll("iframe"),_e=typeof document<"u"&&"hasStorageAccess"in document;M(`watchdog:${Ge} container=${In(wn)} children=${wn.childElementCount} iframes=${De.length} visibility=${typeof document>"u"?"(no document)":document.visibilityState} cookies=${typeof navigator>"u"?"?":navigator.cookieEnabled} hasStorageAccessApi=${_e} paypalNetRequests=${ur.value}`),De.forEach((ht,Wt)=>{let xe=(ht.getAttribute("title")??"").slice(0,40);M(` iframe[${Wt}] ${In(ht)}${xe?` title="${xe}"`:""} ${Ue(ht)}`);let fn=cn(ht);fn&&M(` ${fn}`)}),Et.length===0&&M(" (no PayPal/zoid window errors captured)")};Vn.push(setTimeout(()=>Pe("3s"),3e3)),Vn.push(setTimeout(()=>Pe("8s"),8e3)),Vn.push(setTimeout(()=>Pe("15s"),15e3))},Mn(),M("render:start");let ct=D.startTiming();Kn=setTimeout(()=>{Te()||bt||(M("watchdog:11s retryable render timeout"),Z("PayPal Buttons render did not settle within 11000ms.",!0,!0))},wl);let me=He.render(wn);(async()=>{try{if(await me,M(`render:resolved inactive=${Te()}`),N(),Te()){lr();return}bt=!0,x(!0),ke(!1),Nt.current?.("ready"),D.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),D.performance({stage:"checkout_render",durationMs:D.elapsed(ct),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}catch(Pe){let Ge=Pe instanceof Error?Pe.message:"PayPal failed to render.";M(`render:rejected msg=${Ge.slice(0,120)}`),N(),Z(Ge,!1,te(Ge)?null:!0)}})()}).catch(j=>{let v=j instanceof Error?j.message:"PayPal operation failed.";M(`provider:failed msg=${v.slice(0,120)}`),Z(v,!1,A&&te(v)?null:tr)})},0);return()=>{Yt=!0,clearTimeout(st),ln&&clearTimeout(ln),N(),Ze.current===U&&(Ze.current=null),lr()}},[ie,pe,d,h,c,ze,Xe,e,ve,ge,D,at,Oe,M]);let Ir=qe?(0,Ln.jsxs)("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:$?"#fef2f2":"#f3f4f6",border:`1px solid ${$?"#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=${be} failed=${$})`,Jt.length===0?`
1
+ "use strict";var ol=Object.create;var Ho=Object.defineProperty;var al=Object.getOwnPropertyDescriptor;var il=Object.getOwnPropertyNames;var sl=Object.getPrototypeOf,ll=Object.prototype.hasOwnProperty;var cl=(e,t)=>{for(var n in t)Ho(e,n,{get:t[n],enumerable:!0})},Ui=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of il(t))!ll.call(e,o)&&o!==n&&Ho(e,o,{get:()=>t[o],enumerable:!(r=al(t,o))||r.enumerable});return e};var qi=(e,t,n)=>(n=e!=null?ol(sl(e)):{},Ui(t||!e||!e.__esModule?Ho(n,"default",{value:e,enumerable:!0}):n,e)),dl=e=>Ui(Ho({},"__esModule",{value:!0}),e);var vc={};cl(vc,{DirectPayPalButton:()=>Io,FloPayAutomaticPaymentButton:()=>Ls,FloPayCardSetup:()=>Os,FloPayCardSetupError:()=>Lo,FloPayCheckout:()=>ya,FloPayProvider:()=>Eo,SplitCardForm:()=>da,VaultCardFields:()=>oo,dropThirdPartyOnlyError:()=>zs.dropThirdPartyOnlyError,useCheckout:()=>Gi,useFloPay:()=>vr,usePayPalFloPay:()=>Jo});module.exports=dl(vc);var zs=require("@flopay/shared");var fa=require("@flopay/js"),Kn=require("@flopay/shared"),Ve=require("react");var Tt=require("react/jsx-runtime");function ul(){return(0,Tt.jsxs)(Tt.Fragment,{children:[(0,Tt.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,Tt.jsx)("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),(0,Tt.jsx)("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",(0,Tt.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,Tt.jsx)("path",{d:"M9 18l6-6-6-6"})})]})}function pl(){return(0,Tt.jsx)(Tt.Fragment,{children:"Go back"})}function ml(){return(0,Tt.jsx)(Tt.Fragment,{children:"Secure card checkout"})}function Kr(e){return e!==void 0&&(e===""||e===null||e===!1)}function Hr({content:e}){return(0,Tt.jsx)(Tt.Fragment,{children:e===void 0?(0,Tt.jsx)(ul,{}):e})}function Wr({content:e}){return(0,Tt.jsx)(Tt.Fragment,{children:e===void 0?(0,Tt.jsx)(pl,{}):e})}function vo({content:e}){return(0,Tt.jsx)(Tt.Fragment,{children:e===void 0?(0,Tt.jsx)(ml,{}):e})}var An=require("@flopay/shared");function Yr(e,t,n,r={}){let o;return(i={})=>{if(o)return o;let d={...r,...i,email:i.email?.trim()||r.email?.trim()},c=(0,An.isCardHolderNamePlaceholder)(d.firstName,d.lastName);if(!(0,An.isValidEmail)(d.email))return Promise.reject(new An.FloPayError("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}));let v={};for(let[y,f]of Object.entries(d)){if(c&&y.endsWith("Name")||typeof f!="string")continue;let g=f.trim();g&&(v[y]=g)}return o=e.claimCheckoutSession(t,n,{accountData:v}),o.catch(()=>{}),o}}function $i(e,t){if(!t)return e;if(!e)return t;let n;return"checkoutMetadata"in t?n=t:"checkoutMetadata"in e&&(n=e),{account:{...e.account??{},...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,...n?{checkoutMetadata:n.checkoutMetadata}:{},tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}}function Ba(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 ji(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 Mr(e){if((0,An.isCardHolderNamePlaceholder)(e))return{};let[t,...n]=e?.trim().split(/\s+/)??[];return t?{firstName:t,lastName:n.join(" ")||void 0}:{}}function Fa(e,t){return t?{...e,...t}:e}function Qt(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 yl=[{match:/^paypal authorization required\.?$/i,replacement:"For your additional security, please re-authenticate this payment via PayPal."}];function wr(e){if(typeof e!="string")return e??void 0;let t=e.trim();if(!t)return e;for(let{match:n,replacement:r}of yl)if(n.test(t))return r;return e}function Ar(e,t){return e.status!=="authorized"?{status:"succeeded"}:{status:"authorized",paymentId:e.paymentId,sessionId:e.id||t||void 0,authorizationExpiresAt:e.authorizationExpiresAt}}function Gr(e){return e?.status==="authorized"||e?.status==="complete"}function Vi(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function Wo(e){let t=Vi(e);return new An.FloPayError(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function Yo(e){return e instanceof An.FloPayError||typeof e=="object"&&e!==null&&"code"in e?e.code:void 0}function Go(e){let t=Vi(e),n="checkout_processing_timeout";return t?n="authorization_expired":e?.status==="expired"&&(n="checkout_session_expired"),new An.FloPayError(t?"Authorization has expired.":"Automatic payment failed. Please try again.","api_error",{code:n})}function bo(e,t){return e==="processing"||(0,An.isMoneySettledOutcome)(e,t)}function Ki(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}function Hi(e,t="automatic"){return{...typeof e=="number"&&Number.isFinite(e)&&e>0?{mode:"payment",amount:e,captureMethod:t==="manual"?"manual":"automatic_async"}:{mode:"setup"},paymentMethodTypes:["card"],setupFutureUsage:"off_session"}}function Da(e){let t=e&&typeof e=="object"?e:null;return t?.name==="IntegrationError"||t?.code==="elements_intent_mismatch"||t?.type==="invalid_request_error"?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response"}:{errorCode:"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime"}}function Co(e){let t=[e?.id,e?.originalPaymentMethodId];for(let n of t)if(typeof n=="string"&&n.startsWith("pm_"))return n}var Dr=require("@flopay/js"),Pe=require("@flopay/shared"),w=qi(require("react"),1);var La=require("react"),qn=(0,La.createContext)({flopay:null,paypalFlopay:null,billingApiUrl:""}),tr=(0,La.createContext)({session:null,loading:!1,error:null});var Qo=require("@flopay/js"),qt=require("@flopay/shared"),es=require("@paypal/paypal-js"),_=require("react");var Wi=require("@flopay/shared"),nr=require("react"),gr=require("react/jsx-runtime");function kn(e,t=!1){let{firstName:n,lastName:r,...o}=e,i=n?.trim(),d=r?.trim();return{...o,...i||t?{firstName:i??""}:{},...d||t?{lastName:d??""}:{}}}function Jr(){let[e,t]=(0,nr.useState)(null),n=(0,nr.useRef)(null),r=(0,nr.useRef)(0),o=(0,nr.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,nr.useCallback)(d=>{let c=n.current;n.current=null,t(null),c?.(d)},[]);return(0,nr.useEffect)(()=>()=>{n.current?.(null),n.current=null},[]),{request:e,collect:o,finish:i}}function Xr({identity:e,methodLabel:t,onComplete:n,onCancel:r,submitting:o=!1,testId:i="flopay-buyer-identity-pane"}){let[d,c]=(0,nr.useState)(e.email?.trim()??""),v=(0,Wi.isValidEmail)(d.trim());return(0,gr.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,gr.jsxs)("div",{style:{fontWeight:700},children:["Continue with ",t]}),(0,gr.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",(0,gr.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,gr.jsxs)("div",{style:{display:"flex",gap:"0.5rem"},children:[r&&(0,gr.jsx)("button",{type:"button",onClick:r,style:{flex:1,minHeight:42},children:"Cancel"}),(0,gr.jsxs)("button",{type:"button",disabled:!v||o,onClick:()=>{n(kn({...e,email:d.trim()}))},style:{flex:2,minHeight:42},children:["Continue with ",t]})]})]})}function fl(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 Br(e){if(typeof e!="string")return;let t=e.trim();return/^[a-z0-9_.-]{1,64}$/i.test(t)?t:void 0}function hr(e){if(typeof e!="object"||e===null)return;let t=e;return Br(t.code)??Br(t.type)??Br(t.name)}function Zr(e){if(!(typeof e!="object"||e===null))return Br(e.decline_code)}function Po(e){return typeof e!="object"||e===null?!1:Br(e.type)?.toLowerCase()==="card_error"||Zr(e)!==void 0}function kr(e){let t=fl(e)?.toLowerCase()??"",r=`${hr(e)?.toLowerCase()??""} ${t}`;return r.includes("popup")&&r.includes("block")}var Yi=require("@flopay/shared"),So=require("react");function vr(){return(0,So.useContext)(qn).flopay}function Jo(){return(0,So.useContext)(qn).paypalFlopay??null}function Gi(){return(0,So.useContext)(tr)}function Ji(){return(0,So.useContext)(qn).billingApiUrl||(0,Yi.resolveBillingApiUrl)()}var Xi=require("@flopay/shared"),Fr=require("react");function nt(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 Xo=require("react"),wo=typeof window>"u"?Xo.useEffect:Xo.useLayoutEffect;var gl={"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 hl(e){return e==="stripe"||e==="paypal"?e:void 0}function vl(e){let t=hl(e.provider),n={schemaVersion:Xi.FLO_INSTRUMENT_SCHEMA_VERSION,...t?{gateway:t}:{}};if(e.class==="lifecycle"){let r=gl[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 Na=new Set(["checkout_mount","sdk_loaded","form_rendered","card_expanded"]);function Qr(e,t){let n=(0,Fr.useRef)(e);n.current=e;let r=(0,Fr.useRef)(new Set),o=(0,Fr.useRef)(t),i=(0,Fr.useRef)(t);return wo(()=>{i.current=t,o.current!==t&&(o.current=t,r.current.clear())},[t]),(0,Fr.useCallback)(d=>{if(i.current!==t)return;let c=vl(d);if(c){if(Na.has(c.name)){if(r.current.has(c.name))return;r.current.add(c.name)}nt(()=>n.current?.(c))}},[t])}var bl=Symbol.for("@flopay/js.telemetry.bridge.v1"),Cl=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function Pl(){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=Pl(),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 Zo(e){let t=globalThis[Cl];return Sl(t?.(e)??{})}function Wt(e){if(e)return e[bl]}var yn=require("react");function ko(e){let t=(0,yn.useRef)(0),n=(0,yn.useRef)(null),r=(0,yn.useRef)(null),o=(0,yn.useCallback)((p=r.current)=>{p?.timer&&(clearTimeout(p.timer),p.timer=null)},[]),i=(0,yn.useCallback)(p=>{o();let I=t.current+1;return t.current=I,n.current=null,r.current={generation:I,method:p,timer:null,yieldedControl:!1},I},[o]),d=(0,yn.useCallback)(p=>{let I=r.current;return p!==void 0&&I?.generation!==p?!1:(o(I),r.current=null,(p===void 0||n.current===p)&&(n.current=null),!0)},[o]),c=(0,yn.useCallback)(p=>{let I=r.current,F=p??I?.generation??t.current;(p===void 0||I?.generation===p)&&(o(I),r.current=null),n.current=F},[o]),v=(0,yn.useCallback)(p=>n.current===(p??t.current),[]),y=(0,yn.useCallback)(p=>r.current?.generation===p&&n.current!==p,[]),f=(0,yn.useCallback)(()=>{let p=r.current;p&&(p.yieldedControl=!0,o(p))},[o]),g=(0,yn.useCallback)(()=>{let p=r.current;!p?.yieldedControl||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"}))},600))},[o,e]);return(0,yn.useEffect)(()=>{let p=()=>{document.visibilityState==="visible"?g():f()};return document.addEventListener("visibilitychange",p),window.addEventListener("blur",f),window.addEventListener("focus",g),()=>{document.removeEventListener("visibilitychange",p),window.removeEventListener("blur",f),window.removeEventListener("focus",g),o()}},[o,f,g]),{startAttempt:i,finishAttempt:d,invalidateAttempt:c,isAttemptInvalidated:v,isAttemptCurrent:y,generationRef:t}}var $n=require("react/jsx-runtime"),ea=45,wl=1e3,kl=11e3,Il=["https://www.paypal.com","https://www.sandbox.paypal.com"],Zi="We couldn't open PayPal. Try again or choose another payment method.",Rl={width:"100%",minHeight:ea,margin:"0 0 0.5rem",padding:"0.75rem 0.875rem",border:"1px solid #2563eb",borderRadius:8,background:"#eff6ff",color:"#1d4ed8",fontSize:"0.95rem",fontWeight:700,cursor:"pointer"};function Qi(e){return e.includes("No ack for postMessage init()")&&Il.some(t=>e.includes(t))&&e.includes("10000ms")}function El(e){return e?`${Zi} Allow pop-ups for this site, then try again.`:Zi}function _l(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 Tl(e){return e>=500?"5xx":e>=400?"4xx":e>=300?"3xx":"unknown"}function ts({sessionId:e,nonce:t,billingApiUrl:n,email:r,billingName:o,onBuyerIdentityReady:i,clientId:d,environment:c,currency:v,isSubscription:y,providerObjectType:f,onTokenizedBody:g,onComplete:p,onErrorChange:I,onDecline:F,onTechnicalFailure:N,isProcessing:ge=!1,onLoadStateChange:V,onInitializationStateChange:S,allowAutomaticRetry:se=!0,onButtonClick:q,runBeforeButtonClick:de,session:G,existingOrderId:he,telemetry:Ke,telemetryContext:Se,onInstrument:Rt,debug:$e=!1}){let Ae=vr(),Be=Qr(Rt,e),le=(0,_.useMemo)(()=>{if(Ae)return null;let z=Zo({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:qt.SDK_VERSION,enabled:Ke!==!1});return z.setCheckoutContext(Se??{}),z.beginCheckout(Se??{}),z},[n,Ae,Ke,Se?.checkoutMode,Se?.layout]),ae=(0,_.useMemo)(()=>Wt(Ae),[Ae]);(0,_.useEffect)(()=>()=>{le&&le.flush().catch(()=>{}).finally(()=>le.destroy())},[le]);let D=(0,_.useMemo)(()=>({error:z=>{ae?ae.error(z):le?.error(z),Be({class:"technical_error",errorCode:z.requestCategory==="intent_create"?"PAYMENT_PROCESSING_FAILED":z.errorCode,requestCategory:z.requestCategory,provider:z.provider})},log:z=>{ae?ae.log(z):le?.log(z),Be({class:"lifecycle",name:z.name,provider:z.provider})},performance:z=>{ae?ae.performance(z):le?.performance(z)},terminal:z=>{ae?ae.terminal(z):le?.terminal(z)},startTiming:()=>ae?.now()??le?.now()??0,elapsed:z=>ae?.elapsed(z)??Math.max(0,(le?.now()??z)-z)}),[Be,ae,le]),Fe=(0,_.useRef)(null),De=(0,_.useRef)(0),te=(0,_.useRef)(null),Re=(0,_.useRef)(!1),[ve,x]=(0,_.useState)(!1),[Q,we]=(0,_.useState)(!1),[ue,ce]=(0,_.useState)(0),ze=(0,_.useRef)(0),[rt,gt]=(0,_.useState)(!1),Ge=(0,_.useRef)(!1),ie=(0,_.useRef)(!1),[Y,$]=(0,_.useState)(!1),[Ue,Qe]=(0,_.useState)(!1),{request:ye,collect:ot,finish:ne}=Jr(),h=(0,_.useRef)({sessionId:e,required:!(0,qt.isValidEmail)(r?.trim()||G?.customer?.email?.trim())});h.current.sessionId!==e&&(h.current={sessionId:e,required:!(0,qt.isValidEmail)(r?.trim()||G?.customer?.email?.trim())});let tt=h.current.required,Ee=(0,_.useMemo)(()=>n.replace(/\/+$/,""),[n]),Le=G?.gateways?.paypal?.providerObjectType??f,xe=Le??(y?"subscription":"order"),pt=Le==="order"||Le==="setup_token",mt=(0,_.useMemo)(()=>JSON.stringify([Ee,d,v,c??"",xe,pt,e,he??""]),[Ee,d,v,c,he,xe,pt,e]),R=(0,_.useRef)(mt),A=R.current!==mt,ht=(0,_.useRef)($e),Je=(0,_.useRef)(null),[Yt,fn]=(0,_.useState)([]),L=(0,_.useCallback)(z=>{ht.current&&fn(ke=>[...ke,`${new Date().toISOString().slice(11,23)} ${z}`])},[]);(0,_.useEffect)(()=>{ht.current=$e,$e&&L("debug:enabled"),Je.current?.setEnabled($e)},[L,$e]);let jt=(0,_.useRef)(g),Gt=(0,_.useRef)(p),lt=(0,_.useRef)(I),Lt=(0,_.useRef)(F),gn=(0,_.useRef)(N),In=(0,_.useRef)(q),hn=(0,_.useRef)(V),Nt=(0,_.useRef)(S),He=(0,_.useRef)(i),yt=(0,_.useRef)(de),Ct=(0,_.useRef)(G),on=(0,_.useRef)(r),ct=(0,_.useRef)(o),vn=(0,_.useRef)(t),Xe=(0,_.useRef)(null),Jt=(0,_.useRef)(new Map),bn=(0,_.useRef)(new Map),an=(0,_.useRef)(!1);(0,_.useEffect)(()=>(an.current=!0,()=>{an.current=!1}),[]),(0,_.useEffect)(()=>{jt.current=g},[g]),(0,_.useEffect)(()=>{He.current=i},[i]),(0,_.useEffect)(()=>{Gt.current=p},[p]),(0,_.useEffect)(()=>{lt.current=I},[I]),(0,_.useEffect)(()=>{Lt.current=F},[F]),(0,_.useEffect)(()=>{gn.current=N},[N]),(0,_.useEffect)(()=>{In.current=q},[q]),(0,_.useEffect)(()=>{hn.current=V},[V]),(0,_.useEffect)(()=>{Nt.current=S},[S]),(0,_.useEffect)(()=>{yt.current=de},[de]),(0,_.useEffect)(()=>{Ct.current=G},[G]),(0,_.useEffect)(()=>{on.current=r},[r]),(0,_.useEffect)(()=>{ct.current=o},[o]),(0,_.useEffect)(()=>{vn.current=t},[t]),(0,_.useEffect)(()=>{ze.current=ue},[ue]),(0,_.useEffect)(()=>{rt&&te.current?.focus()},[rt,ue]);let Kt=(0,_.useCallback)(()=>{window.setTimeout(()=>{te.current?.focus()},0)},[]),Ot=(0,_.useCallback)(()=>{x(!1),ce(z=>z+1)},[]),en=(0,_.useCallback)(()=>{gt(!1),(Fe.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??Fe.current)?.focus?.()},[]);(0,_.useEffect)(()=>{!ve||!Re.current||(Re.current=!1,en())},[en,ve,ue]);let Xt=(0,_.useCallback)((z,ke)=>{let tn=gn.current;if(tn){tn("paypal",z,ke);return}lt.current?.(El(ke?.popupBlocked??kr(z)))},[]),Rn=(0,_.useCallback)((z,ke,tn)=>{Xt(ke,tn),gt(!0),Ot(),Kt()},[Kt,Xt,Ot]),{finishAttempt:xt,invalidateAttempt:sn,isAttemptCurrent:Pt,isAttemptInvalidated:P,startAttempt:ft}=ko(Rn),Et=(0,_.useCallback)(()=>(gt(!1),ft("paypal")),[ft]),_t=(0,_.useCallback)(z=>{sn(z?.generation),z?.showRetry&&gt(!0),z?.remount&&Ot(),z?.focus!==!1&&Kt()},[Kt,sn,Ot]),cn=z=>{let ke=Xe.current;return ke&&bn.current.set(z,ke),z};(0,_.useEffect)(()=>{R.current!==mt&&(R.current=mt,Ge.current=!1,ie.current=!1,x(!1),we(!1),$(!1),Nt.current?.("loading"))},[mt]),(0,_.useEffect)(()=>{nt(()=>hn.current?.(ve&&!Y))},[ve,Y]);let dr=(0,qt.normalizeGatewayEnvironment)(c);(0,_.useEffect)(()=>{let z=d?`${d.slice(0,6)}\u2026(len ${d.length})`:"(empty)",ke=typeof navigator>"u"?"(no navigator)":navigator.userAgent;if(L(`mount clientId=${z} env=${c??"(unset)"}\u2192${dr??"live"} ccy=${v} sub=${y}`),L(`ua=${ke.slice(0,80)}${ke.length>80?"\u2026":""}`),!d){L("FAIL: clientId empty \u2014 gateway misconfigured"),$(!0),D.error({errorCode:"CONFIGURATION_INVALID",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),console.error("[FloPay] DirectPayPal: clientId empty \u2014 gateway misconfigured");return}if(!Fe.current){L("FAIL: containerRef not attached");return}De.current=D.startTiming(),D.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let tn=!1,dn=!1,_e=()=>tn||dn,Hn,Dn=!1,zt=()=>{Hn=(0,qt.generateIdempotencyKey)(),Hn||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),Dn=!0},un=null,Rr=!1,Er=null,En=!1,ur=()=>{!Er||En||(En=!0,Er.close().catch(()=>{}))},Wn=null,Ln=()=>{Wn!==null&&(D.log({name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal"}),D.performance({stage:"overlay_return",durationMs:D.elapsed(Wn),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal"}),Wn=null)},St=!1,or=!1,_n=Fe.current,Yn=null,Cn=null,Gn=[],Jn=null,dt=!1,Tn=!1,Nn=null,xn=T=>{if(!T||typeof T.getBoundingClientRect!="function")return"(no rect)";let m=T.getBoundingClientRect();return`${Math.round(m.width)}\xD7${Math.round(m.height)}`},Xn=T=>{if(!T)return"(empty)";try{let m=new URL(T,typeof window>"u"?"https://localhost":window.location.href),M=m.pathname.toLowerCase();return M.includes("checkcaptcha")||M.includes("captcha")?`CAPTCHA(${m.host}${M})`:M.includes("risk")||M.includes("challenge")?`RISK(${m.host}${M})`:M.includes("smart/buttons")?`smart-buttons(${m.host})`:`${m.host}${M}`.slice(0,100)}catch{return T.slice(0,80)}},qe=T=>{let m=T.getAttribute("src"),M=T.getAttribute("srcdoc"),K=T.getAttribute("name"),b=T.getAttribute("sandbox"),H=[];return m&&H.push(`src=${Xn(m)}`),M&&H.push(`srcdoc[${M.length}ch]`),!m&&!M&&H.push("src=(empty) srcdoc=(empty)"),K&&H.push(`name=${K.slice(0,40)}`),b!==null&&H.push(`sandbox="${b.slice(0,40)}"`),H.join(" ")},pn=T=>{if(!(T instanceof HTMLIFrameElement))return"";try{let m=T.contentDocument;if(!m)return"cd=null";let M=m.body?.children.length??0,K=m.body?.innerHTML.length??0,b=m.head?.innerHTML.length??0;return`cd=same-origin readyState=${m.readyState} body[${M}children,${K}ch] head[${b}ch]`}catch(m){return`cd=cross-origin(${m.message.slice(0,30)})`}},Mt=[],pr=T=>{if(_e())return;let m=T.message??String(T.error??"(no message)");m&&(m.toLowerCase().includes("paypal")||m.toLowerCase().includes("zoid")||m.toLowerCase().includes("postrobot")||m.toLowerCase().includes("storage"))&&(L(`window:error ${m.slice(0,140)}`),Mt.push(m))},mr=T=>{if(_e())return;let m=T.reason instanceof Error?T.reason.message:String(T.reason??"(no reason)");m&&(m.toLowerCase().includes("paypal")||m.toLowerCase().includes("zoid")||m.toLowerCase().includes("postrobot")||m.toLowerCase().includes("storage"))&&(L(`window:rejection ${m.slice(0,140)}`),Mt.push(m))},yr={value:0},Mn=()=>{Yn?.disconnect(),Yn=null,Cn?.disconnect(),Cn=null;for(let T of Gn.splice(0))clearTimeout(T);Tn=!1,dt&&typeof window<"u"&&(window.removeEventListener("error",pr),window.removeEventListener("unhandledrejection",mr)),dt=!1},Zn=()=>{if(!(dt||_e()||St)){if(dt=!0,Mt.length=0,yr.value=0,typeof window<"u"&&(window.addEventListener("error",pr),window.addEventListener("unhandledrejection",mr)),typeof PerformanceObserver<"u")try{Cn=new PerformanceObserver(T=>{if(!_e())for(let m of T.getEntries()){if(!m.name.toLowerCase().includes("paypal"))continue;yr.value+=1;let M=Math.round(m.duration);L(`net ${M}ms ${m.name.slice(0,90)}`)}}),Cn.observe({type:"resource",buffered:!0})}catch{}Nn?.()}},Ht=()=>{Jn&&(clearTimeout(Jn),Jn=null)},U=()=>{Mn(),Ht()},j={setEnabled:T=>{T?Zn():Mn()}};Je.current=j,ht.current&&Zn();let re=T=>{if(!T)return!1;let m=T.toLowerCase();return m.includes("zoid destroyed")||m.includes("destroyed all components")||m.includes("window closed")||m.includes("detected container element removed")},oe=T=>{if(_e()||re(T))return;let m=wr(T)??T;nt(()=>lt.current?.(m))},We=T=>{T!==null&&D.error({errorCode:T?"PROVIDER_RUNTIME_FAILED":"PROVIDER_LOAD_FAILED",stage:T?"provider_ready":"provider_load",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime"})},ee=(T,m=!1,M=!1)=>{if(tn)return;let K=Ge.current||!se;if(Rr)return;Rr=!0,dn=!0,U(),ur();let b=m||Qi(T);if(b&&se&&!Ge.current){Ge.current=!0,x(!1),Qe(!1),we(!0),Nt.current?.("retrying"),un=setTimeout(()=>{tn||ce(H=>H+1)},wl);return}if(b||K){if(x(!1),Qe(!1),we(!1),$(!0),(!b||M===!0)&&We(M),Nt.current?.("exhausted"),!ie.current){ie.current=!0;let H="paypal_init_failure";Qi(T)?H="paypal_init_timeout":m&&(H="paypal_render_timeout"),console.error("[FloPay] Direct PayPal initialization failed:",H)}return}$(!0),We(M),console.error("[FloPay] DirectPayPal load/render failure:",T)};$(!1);let J=async(T,m=Xe.current)=>{if(_e())return;let M=m?.sessionId??e;if(jt.current){await jt.current(T,{sessionId:M,accountPatch:m?.accountPatch,nonce:m?.nonce});return}let K=D.startTiming();D.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let b=()=>{D.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),D.performance({stage:"processing",durationMs:D.elapsed(K),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})};try{let H=Ct.current,Ye=m?.accountPatch?.email??on.current,ln=m?.accountPatch?.userId??H?.customer?.id??H?.accountData?.userId??"",it=m?.accountPatch?.firstName??H?.customer?.firstName??H?.accountData?.firstName,st=m?.accountPatch?.lastName??H?.customer?.lastName??H?.accountData?.lastName,be=await new Qo.PaymentAPI(Ee,{telemetry:!1}).processPayment(ln,{sessionId:M,nonce:m?.nonce??vn.current,paymentMethodCategory:"paypal",tokenizedData:T,accountData:{userId:ln,email:Ye??H?.customer?.email??"",...it?{firstName:it}:{},...st?{lastName:st}:{},country:m?.accountPatch?.country??H?.customer?.country??H?.accountData?.country??void 0,zip:m?.accountPatch?.zip??H?.customer?.zip??H?.accountData?.zip??void 0}});if(be.ok){if(dn||tn&&an.current)return;b(),D.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),nt(()=>Gt.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(_e())return;let Ze=await be.json().catch(()=>null),Ne=Ze?.message??"PayPal payment failed.",Te=wr(Ne)??Ne;b(),be.status===400&&(typeof Ze?.declineCode=="string"||!Array.isArray(Ze?.fields))?D.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):be.status===400||be.status===422?D.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx"}):D.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:Tl(be.status),failureCategory:be.status>=500?"server_error":void 0}),oe(Te),nt(()=>Lt.current?.(Qt("paypal",Te,{code:Ze?.code,declineCode:Ze?.declineCode})));return}catch(H){if(_e())return;b(),D.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let Ye=H instanceof Error?H.message:"PayPal payment failed.",ln=wr(Ye)??Ye;oe(ln),nt(()=>Lt.current?.(Qt("paypal",ln)));return}},E=()=>new qt.FloPayError("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),B=T=>_e()?Promise.reject(E()):Promise.resolve(T),X=async T=>{if(_e())throw E();Dn||zt();let m=Xe.current,M=m?.sessionId??e,K=m?.nonce??vn.current;D.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let b;try{b=await new Qo.PaymentAPI(Ee,{telemetry:!1}).createSessionIntent(M,K??"",pt?{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:qt.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE,paymentMethodId:null,intentKind:xe==="setup_token"?"setup":"payment"}:{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"},{idempotencyKey:Hn})}catch(H){throw D.error({...(0,qt.classifyTelemetryFailure)(H,"PAYMENT_PROCESSING_FAILED","unknown"),stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"}),H}if(_e())throw E();if(b.provider!=="paypal"||b.providerObjectType!==xe)throw new Error(T);return D.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),b.providerObjectId},vt=(T,m)=>{let M=m?.nonce??vn.current;if(!M)return;let K=m?.sessionId??e,b=Zr(T)??hr(T)??"provider_declined";new Qo.PaymentAPI(Ee,{telemetry:!1}).reportSessionIntentDecline(K,M,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:b}).catch(()=>{})},et=ue;L("loadScript:scheduled (deferred 1 tick)");let pe=null,at=setTimeout(()=>{if(tn){L("loadScript:skipped (cancelled before defer ran)");return}L("loadScript:start");let T=dr==="live"?"production":dr,m={};xe==="subscription"?m={intent:"subscription",vault:!0}:xe==="order"&&(m={intent:"capture"}),pe=(0,es.loadScript)({clientId:d,currency:v,...m,...T?{environment:T}:{},...T==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}});let M=!1;pe.then(K=>{if(M=!0,L(`loadScript:resolved inactive=${_e()} ns=${!!K} buttons=${!!K?.Buttons}`),_e())return;if(!K?.Buttons){L("FAIL: namespace missing Buttons factory"),ee("PayPal SDK did not expose the Buttons factory.");return}D.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),D.performance({stage:"provider_ready",durationMs:D.elapsed(De.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),D.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let b=async(be,Ze)=>{if(_e()||ze.current!==et)return;let Ne=be.vaultSetupToken??be.subscriptionID??be.orderID??"",Te=Ne?bn.current.get(Ne):Jt.current.get(et);if(!(!Te||!Pt(Te.generation))&&xt(Te.generation)){bn.current.delete(Ne),Jt.current.delete(Te.surfaceKey),Ln();try{if(Qe(!0),nt(()=>lt.current?.(null)),!Ne)throw new qt.FloPayError("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});let bt=Ct.current,nn=Mr(ct.current??[bt?.customer?.firstName,bt?.customer?.lastName].filter(Boolean).join(" ")),Me=kn({email:Te.accountPatch?.email?.trim()||on.current?.trim()||bt?.customer?.email?.trim(),firstName:Te.accountPatch?.firstName?.trim()||nn.firstName,lastName:Te.accountPatch?.lastName?.trim()||nn.lastName});if(!(0,qt.isValidEmail)(Me.email)||!(Me.firstName||Me.lastName))try{let On=_l(await Ze?.order?.get?.());Me=kn({email:On.email||Me.email,firstName:On.firstName||Me.firstName,lastName:On.lastName||Me.lastName})}catch{}if((He.current||tt)&&!(0,qt.isValidEmail)(Me.email)){let On=await ot("PayPal",Me);if(!On)return;Me=On}(0,qt.isValidEmail)(Me.email)&&(Te.accountPatch=kn({...Te.accountPatch,...Me}),await He.current?.(Me));let Pn;xe==="setup_token"?Pn={id:Ne,type:"paypal_setup_token",isPaypal:!0,gateway:"paypal",paymentMethodType:qt.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE}:pt?Pn={id:Ne,isPaypal:!0,gateway:"paypal",paymentMethodType:qt.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE}:Pn={id:Ne,isPaypal:!0},await J(Pn,Te)}catch(bt){oe(bt instanceof Error?bt.message:"PayPal capture failed.")}finally{_e()||Qe(!1)}}},H=be=>{let Ze=he?()=>B(he):()=>X(be);return async()=>cn(await Ze())},Ye=K.Buttons({style:{layout:"horizontal",height:ea,tagline:!1},onClick:async(be,Ze)=>{if(_e()){await Ze.reject();return}zt();let Ne=yt.current,Te={};if(Ne)try{let Me=await Ne("paypal");if(_e()){await Ze.reject();return}if(!Me.proceed){Xe.current=null,Jt.current.delete(et),await Ze.reject();return}Te={sessionId:Me.sessionId,accountPatch:Me.accountPatch,nonce:Me.nonce}}catch(Me){L(`onClick:runBeforeButtonClick rejected msg=${(Me instanceof Error?Me.message:String(Me)).slice(0,120)}`),Xe.current=null,Jt.current.delete(et),await Ze.reject();return}nt(()=>In.current?.("paypal"));let nn={generation:Et(),surfaceKey:et,...Te};Xe.current=nn,Jt.current.set(et,nn),await Ze.resolve(),D.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),D.log({name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),D.log({name:"provider.overlay.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),Wn=D.startTiming()},createOrder:xe==="order"?H("Failed to create PayPal order."):void 0,createSubscription:xe==="subscription"?H("Failed to create PayPal subscription."):void 0,createVaultSetupToken:xe==="setup_token"?async()=>cn(await X("Failed to create PayPal setup token.")):void 0,onApprove:b,onCancel:()=>{if(_e())return;let be=Jt.current.get(et)??Xe.current;be&&Jt.current.delete(be.surfaceKey),Xe.current=null,Ln(),D.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),Re.current=!0,_t({generation:be?.generation,remount:!0,focus:!1})},onError:be=>{if(_e()||ze.current!==et)return;let Ze=be instanceof Error?be.message:"PayPal failed to render.";if(L(`onError rendered=${St} msg=${Ze.slice(0,120)}`),St){let Ne=Jt.current.get(et)??Xe.current;if(Ne&&!Pt(Ne.generation)||!Ne&&P())return;if(re(Ze)){xt(Ne?.generation);return}if(Ln(),Po(be)){D.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),vt(be,Ne),nt(()=>Lt.current?.(Qt("paypal",Ze))),Ne&&Jt.current.delete(Ne.surfaceKey),Xe.current=null,xt(Ne?.generation);return}let Te=Ze.toLowerCase();D.error({errorCode:Te.includes("popup")&&Te.includes("block")?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),Ne&&Jt.current.delete(Ne.surfaceKey),Xe.current=null,_t({generation:Ne?.generation,remount:!0,showRetry:!0,focus:!0}),Xt(be,{code:"paypal_runtime_failed"});return}ee(Ze,!1,re(Ze)?null:or)}}),ln=Ye.isEligible();if(L(`isEligible=${ln}`),D.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!ln){x(!1),ee("PayPal buttons are not eligible to render in this context (paypal_ineligible).",!1,null);return}or=!0,Er=Ye,Nn=()=>{if(!dt||Tn||_e()||St)return;Tn=!0,L(`container:dims ${xn(_n)} visibility=${typeof document>"u"?"(no document)":document.visibilityState}`),typeof MutationObserver<"u"&&(Yn=new MutationObserver(Ze=>{if(!_e()){for(let Ne of Ze)if(Ne.type==="childList")Ne.addedNodes.forEach(Te=>{if(!(Te instanceof Element))return;let bt=Te.tagName.toLowerCase(),nn=(Te.getAttribute("title")??"").slice(0,40),Me=bt==="iframe"?` ${qe(Te)}`:"";L(`child+ ${bt}${nn?` title="${nn}"`:""}${Me} dims=${xn(Te)}`)});else if(Ne.type==="attributes"&&Ne.target instanceof Element){let Te=Ne.target;if(Te.tagName.toLowerCase()!=="iframe")continue;let bt=Ne.attributeName;(bt==="src"||bt==="srcdoc")&&L(`attr~ iframe ${bt}=${bt==="srcdoc"?`[${(Te.getAttribute("srcdoc")??"").length}ch]`:Xn(Te.getAttribute("src"))} dims=${xn(Te)}`)}}}),Yn.observe(_n,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let be=Ze=>{if(_e()||St)return;let Ne=_n.querySelectorAll("iframe"),Te=typeof document<"u"&&"hasStorageAccess"in document;L(`watchdog:${Ze} container=${xn(_n)} children=${_n.childElementCount} iframes=${Ne.length} visibility=${typeof document>"u"?"(no document)":document.visibilityState} cookies=${typeof navigator>"u"?"?":navigator.cookieEnabled} hasStorageAccessApi=${Te} paypalNetRequests=${yr.value}`),Ne.forEach((bt,nn)=>{let Me=(bt.getAttribute("title")??"").slice(0,40);L(` iframe[${nn}] ${xn(bt)}${Me?` title="${Me}"`:""} ${qe(bt)}`);let Pn=pn(bt);Pn&&L(` ${Pn}`)}),Mt.length===0&&L(" (no PayPal/zoid window errors captured)")};Gn.push(setTimeout(()=>be("3s"),3e3)),Gn.push(setTimeout(()=>be("8s"),8e3)),Gn.push(setTimeout(()=>be("15s"),15e3))},Nn(),L("render:start");let st=D.startTiming();Jn=setTimeout(()=>{_e()||St||(L("watchdog:11s retryable render timeout"),ee("PayPal Buttons render did not settle within 11000ms.",!0,!0))},kl);let me=Ye.render(_n);(async()=>{try{if(await me,L(`render:resolved inactive=${_e()}`),U(),_e()){ur();return}St=!0,x(!0),we(!1),Nt.current?.("ready"),D.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),D.performance({stage:"checkout_render",durationMs:D.elapsed(st),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}catch(be){let Ze=be instanceof Error?be.message:"PayPal failed to render.";L(`render:rejected msg=${Ze.slice(0,120)}`),U(),ee(Ze,!1,re(Ze)?null:!0)}})()}).catch(K=>{let b=K instanceof Error?K.message:"PayPal operation failed.";L(`provider:failed msg=${b.slice(0,120)}`),ee(b,!1,M&&re(b)?null:or)})},0);return()=>{tn=!0,clearTimeout(at),un&&clearTimeout(un),U(),Je.current===j&&(Je.current=null),ur()}},[se,Ee,d,v,c,xe,pt,e,he,ue,D,ot,tt,L]);let Fn=$e?(0,$n.jsxs)("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:Y?"#fef2f2":"#f3f4f6",border:`1px solid ${Y?"#fca5a5":"#d1d5db"}`,borderRadius:6,color:"#111827",font:"11px/1.35 ui-monospace, SFMono-Regular, Menlo, monospace",whiteSpace:"pre-wrap",wordBreak:"break-word",maxHeight:220,overflowY:"auto"},children:[`FloPay/DirectPayPal-debug (ready=${ve} failed=${Y})`,Yt.length===0?`
2
2
  (waiting for first lifecycle event\u2026)`:`
3
- ${Jt.join(`
4
- `)}`]}):null;return $&&!ee?qe?(0,Ln.jsx)("div",{children:Ir}):null:(0,Ln.jsxs)("div",{children:[Ir,ye&&(0,Ln.jsx)(Xr,{identity:ye.identity,methodLabel:ye.methodLabel,testId:"flopay-direct-paypal-identity-pane",onComplete:k,onCancel:()=>k(null)}),(0,Ln.jsxs)("div",{"aria-hidden":Y||ye?!0:void 0,style:Y||ye?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:ea},children:[!be&&!Y&&(0,Ln.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,Ln.jsx)("div",{ref:Be,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,role:"group","aria-label":"PayPal payment method",style:{minHeight:ea,display:"flex",opacity:be?1:0},"aria-busy":We||he},ge)]},ge),ot&&(0,Ln.jsx)("button",{ref:Q,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:Pn,style:Il,children:"Try PayPal again"})]})}function Io(e){return(0,Ln.jsx)(es,{...e})}function ts(e){return(0,Ln.jsx)(es,{...e})}var Ro=require("react/jsx-runtime");function eo({children:e,margin:t,icon:n=!0,styleOverride:r}){return(0,Ro.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,Ro.jsx)("svg",{"aria-hidden":"true",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:(0,Ro.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 Ot=require("react/jsx-runtime");var Tl={processing:"#374151",success:"#16a34a",error:"#dc2626"};function Nn({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,Ot.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,Ot.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,Ot.jsxs)("div",{style:{width:48,height:48,position:"relative"},children:[e==="processing"&&(0,Ot.jsxs)("svg",{"aria-hidden":"true",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,Ot.jsx)("circle",{cx:"12",cy:"12",r:"10",stroke:"#e5e7eb",strokeWidth:"3"}),(0,Ot.jsx)("path",{d:"M4 12a8 8 0 018-8v3a5 5 0 00-5 5H4z",fill:"#4A49FF"})]}),e==="success"&&(0,Ot.jsx)("div",{style:{animation:"flopay-pop 0.4s cubic-bezier(0.34,1.56,0.64,1)"},children:(0,Ot.jsxs)("svg",{"aria-hidden":"true",width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[(0,Ot.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#22c55e"}),(0,Ot.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,Ot.jsx)("div",{style:{animation:"flopay-shake 0.4s ease"},children:(0,Ot.jsxs)("svg",{"aria-hidden":"true",width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[(0,Ot.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#ef4444"}),(0,Ot.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,Ot.jsxs)("span",{style:{fontSize:14,fontWeight:600,letterSpacing:"0.05em",color:Tl[e]},children:[e==="processing"&&r,e==="success"&&(o??(n?"PAYMENT AUTHORISED":"PAYMENT SUCCESSFUL")),e==="error"&&i]}),e==="success"&&d!==null&&(0,Ot.jsx)("p",{style:{fontSize:13,color:"#6b7280",fontWeight:400,maxWidth:260,lineHeight:1.4,margin:0},children:d}),e==="error"&&t&&(0,Ot.jsx)("p",{style:{fontSize:13,color:"#6b7280",fontWeight:400,maxWidth:260,lineHeight:1.4,margin:0},children:t}),(0,Ot.jsx)("style",{children:`
3
+ ${Yt.join(`
4
+ `)}`]}):null;return Y&&!A?$e?(0,$n.jsx)("div",{children:Fn}):null:(0,$n.jsxs)("div",{children:[Fn,ye&&(0,$n.jsx)(Xr,{identity:ye.identity,methodLabel:ye.methodLabel,testId:"flopay-direct-paypal-identity-pane",onComplete:ne,onCancel:()=>ne(null)}),(0,$n.jsxs)("div",{"aria-hidden":Q||ye?!0:void 0,style:Q||ye?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:ea},children:[!ve&&!Q&&(0,$n.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,$n.jsx)("div",{ref:Fe,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,role:"group","aria-label":"PayPal payment method",style:{minHeight:ea,display:"flex",opacity:ve?1:0},"aria-busy":Ue||ge},ue)]},ue),rt&&(0,$n.jsx)("button",{ref:te,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:en,style:Rl,children:"Try PayPal again"})]})}function Io(e){return(0,$n.jsx)(ts,{...e})}function ns(e){return(0,$n.jsx)(ts,{...e})}var Ro=require("react/jsx-runtime");function eo({children:e,margin:t,icon:n=!0,styleOverride:r}){return(0,Ro.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,Ro.jsx)("svg",{"aria-hidden":"true",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:(0,Ro.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 Vt=require("react/jsx-runtime");var xl={processing:"#374151",success:"#16a34a",error:"#dc2626"};function jn({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,Vt.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,Vt.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,Vt.jsxs)("div",{style:{width:48,height:48,position:"relative"},children:[e==="processing"&&(0,Vt.jsxs)("svg",{"aria-hidden":"true",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,Vt.jsx)("circle",{cx:"12",cy:"12",r:"10",stroke:"#e5e7eb",strokeWidth:"3"}),(0,Vt.jsx)("path",{d:"M4 12a8 8 0 018-8v3a5 5 0 00-5 5H4z",fill:"#4A49FF"})]}),e==="success"&&(0,Vt.jsx)("div",{style:{animation:"flopay-pop 0.4s cubic-bezier(0.34,1.56,0.64,1)"},children:(0,Vt.jsxs)("svg",{"aria-hidden":"true",width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[(0,Vt.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#22c55e"}),(0,Vt.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,Vt.jsx)("div",{style:{animation:"flopay-shake 0.4s ease"},children:(0,Vt.jsxs)("svg",{"aria-hidden":"true",width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[(0,Vt.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#ef4444"}),(0,Vt.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,Vt.jsxs)("span",{style:{fontSize:14,fontWeight:600,letterSpacing:"0.05em",color:xl[e]},children:[e==="processing"&&r,e==="success"&&(o??(n?"PAYMENT AUTHORISED":"PAYMENT SUCCESSFUL")),e==="error"&&i]}),e==="success"&&d!==null&&(0,Vt.jsx)("p",{style:{fontSize:13,color:"#6b7280",fontWeight:400,maxWidth:260,lineHeight:1.4,margin:0},children:d}),e==="error"&&t&&(0,Vt.jsx)("p",{style:{fontSize:13,color:"#6b7280",fontWeight:400,maxWidth:260,lineHeight:1.4,margin:0},children:t}),(0,Vt.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 ns=require("@flopay/shared"),Gt=require("react");var rs=require("react/jsx-runtime");function Eo({flopay:e,paypalFlopay:t,options:n,onInstrument:r,children:o}){let[i,d]=(0,Gt.useState)(e instanceof Promise?null:e),[c,h]=(0,Gt.useState)(t instanceof Promise||!t?null:t),y=(0,Gt.useRef)(null),f=(0,Gt.useRef)(null),g=Qr(r);(0,Gt.useEffect)(()=>{g({class:"lifecycle",name:"checkout.mount"})},[g]),(0,Gt.useEffect)(()=>{i&&g({class:"lifecycle",name:"sdk.initialize.ready"})},[g,i]),(0,Gt.useEffect)(()=>{if(i)return qt(i)?.subscribe?.(g)},[g,i]),(0,Gt.useEffect)(()=>{if(!(!c||c===i))return qt(c)?.subscribe?.(g)},[g,i,c]),(0,Gt.useEffect)(()=>{if(!i)return;let F=qt(i);return y.current=F?.beginCheckout()??F?.now()??0,F?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{F?.log({name:"checkout.unmount",stage:"unmount"})}},[i]),(0,Gt.useEffect)(()=>{let F=!1;return e instanceof Promise?e.then(L=>{F||d(L)},()=>{F||g({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"})}):d(e),()=>{F=!0}},[g,e]),(0,Gt.useEffect)(()=>{let F=!1;if(!t){h(null);return}return t instanceof Promise?t.then(L=>{F||h(L)},()=>{F||g({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED",provider:"paypal"})}):h(t),()=>{F=!0}},[g,t]),(0,Gt.useEffect)(()=>{if(!i||f.current===i)return;f.current=i;let F=qt(i);F?.log({name:"checkout.rendered",stage:"checkout_render"}),g({class:"lifecycle",name:"checkout.rendered"}),F?.performance({stage:"checkout_render",durationMs:F.elapsed(y.current??0),durationMode:"machine"})},[g,i]);let p=(0,ns.resolveBillingApiUrl)(n?.billingApiUrl),w=(0,Gt.useMemo)(()=>({flopay:i,paypalFlopay:c,billingApiUrl:p,emitInstrument:g}),[i,c,p,g]);return(0,rs.jsx)(Dn.Provider,{value:w,children:o})}var ta="flopay_recent_completion_";function to(e){if(!(!e||typeof window>"u"))try{let t={expiresAt:Date.now()+6e4};window.sessionStorage.setItem(ta+e,JSON.stringify(t))}catch{}}function Oa(e){if(!e||typeof window>"u")return!1;try{let t=window.sessionStorage.getItem(ta+e);if(!t)return!1;let n=JSON.parse(t);return typeof n?.expiresAt!="number"||n.expiresAt<=Date.now()?(window.sessionStorage.removeItem(ta+e),!1):!0}catch{return!1}}var no=require("@flopay/js"),$e=require("@flopay/shared");var To="card";async function xl(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 Ml(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 Ua(e,t){return Object.assign(e,{checkoutMethod:t})}function gr(e,t){let n=e instanceof $e.FloPayError?e:new $e.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 _o(e,t){try{return await e()}catch(n){throw gr(n,t)}}function as(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 Al(e){return e.status==="succeeded"||e.status==="declined"}async function is(e){if(typeof document>"u"||typeof window>"u")throw new $e.FloPayError("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});if(e.signal?.aborted)throw new $e.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 f=new AbortController,g=()=>f.abort();e.signal?.aborted?f.abort():e.signal?.addEventListener("abort",g);let p=window.setTimeout(()=>f.abort(),r);try{let w=await fetch(o,{method:"POST",headers:{"x-checkout-session-token":e.nonce,"content-type":"application/json"},body:"{}",signal:f.signal});if(!w.ok)return{status:"unknown"};let F=await w.json().catch(()=>null);return Bl(F)}catch{return{status:"unknown"}}finally{window.clearTimeout(p),e.signal?.removeEventListener("abort",g)}},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 h=document.createElement("iframe");h.setAttribute("title","Card authentication"),h.setAttribute("allow","payment"),h.tabIndex=0,h.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(";"),h.src=e.nextActionRedirectUrl,c.appendChild(h),document.body.appendChild(c),h.focus();let y=null;try{y=new URL(e.billingApiUrl,window.location.href).origin}catch{y=null}try{let f=await new Promise((g,p)=>{let w=!1,F=0,L=0,he=0,q=!1,P=()=>{window.clearTimeout(F),window.clearInterval(L),window.clearTimeout(he),window.removeEventListener("message",G),h.removeEventListener("load",O),e.signal?.removeEventListener("abort",de)},ie=async()=>{if(!(w||q)){q=!0;try{let ve=await i();if(w||!Al(ve))return;w=!0,P(),g(ve)}finally{q=!1}}},O=()=>{window.clearTimeout(he),he=window.setTimeout(()=>{ie()},250)},de=()=>{w||(w=!0,P(),p(new $e.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"})))},G=ve=>{if(ve.source!==h.contentWindow||y&&ve.origin!==y)return;let Ve=ve.data;!Ve||typeof Ve!="object"||Ve.source!=="flopay-vault-3ds-return"||w||(w=!0,P(),g(null))};F=window.setTimeout(()=>{w||(w=!0,P(),p(new $e.FloPayError("Card authentication timed out.","api_error",{code:"three_ds_timeout"})))},t),L=window.setInterval(()=>{ie()},n),h.addEventListener("load",O),window.addEventListener("message",G),e.signal?.addEventListener("abort",de),e.signal?.aborted&&de()});return f||await i()}finally{c.parentNode?.removeChild(c),d?.isConnected&&d.focus()}}function Bl(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 wr(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=Cr(o)??o;return Ua(new $e.FloPayError(i,"api_error",{code:(0,$e.normalizeCheckoutFailureOutcome)(e?.outcome)??(0,$e.normalizeCheckoutFailureOutcome)(e?.type)??e?.gatewayErrorCode}),r)}function za(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function na(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}function ss(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let o of n)if(typeof o=="string"&&o.length>0&&(!t?.requirePaymentIntentClientSecret||na(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||na(c)))return c;let d=o.gateways;if(d&&typeof d=="object"){let c=d.stripe;if(c&&typeof c=="object"){let h=c,y=[h.stripeClientSecret,h.clientSecret];for(let f of y)if(typeof f=="string"&&f.length>0&&(!t?.requirePaymentIntentClientSecret||na(f)))return f}}}}async function Fl({billingApiUrl:e,sessionId:t,nonce:n,responseJson:r}){let o=ss(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 no.PaymentAPI(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(na(c))return{type:"3ds_required",threeDSecureToken:c}}catch{}return null}async function ro({billingApiUrl:e,sessionId:t,session:n,nonce:r,tokenizedData:o,returnUrl:i,telemetry:d}){let c=e.replace(/\/+$/,""),h=t??n.id,y=r??n.clientSecret,f=n.customer?.id??n.accountData?.userId??"",g=n.customer?.email??n.accountData?.email??"",p=n.customer?.firstName??n.accountData?.firstName??"",w=n.customer?.lastName??n.accountData?.lastName??"",F=n.customer?.country??n.accountData?.country??void 0,L=n.customer?.zip??n.accountData?.zip??void 0,q=await new no.PaymentAPI(c,d===!1?{telemetry:!1}:void 0).processPayment(f,{sessionId:h,nonce:y,paymentMethodCategory:"saved",tokenizedData:o,accountData:{userId:f,email:g,firstName:p,lastName:w,country:F,zip:L},returnUrl:i??za(n)});if(q.ok){let O=typeof q.json=="function"?await q.json().catch(()=>null):null;return(0,$e.isAuthorizationOnlySession)(n)||O?.status==="authorized"?{type:"success",result:{status:"authorized",paymentId:typeof O?.paymentId=="string"?O.paymentId:n.paymentId,sessionId:typeof O?.sessionId=="string"?O.sessionId:h,authorizationExpiresAt:typeof O?.authorizationExpiresAt=="string"?O.authorizationExpiresAt:n.authorizationExpiresAt,paymentMethodId:Po(o),checkoutMethod:os(o)}}:{type:"success",result:{status:"succeeded",paymentIntentId:o?.threeDSecureActionResultTokenId,paymentMethodId:Po(o),checkoutMethod:os(o)}}}let P;try{P=await q.json()}catch(O){throw new $e.FloPayError("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:q.status,cause:O})}if(P?.type==="paypal_redirect_required"||P?.type==="3ds_required"){let O=ss(P);if(!O)throw new $e.FloPayError("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:q.status});return{type:P.type,threeDSecureToken:O,paymentMethodId:P.paymentMethodId}}if(P?.gatewayErrorCode==="authentication_required"){let O=await Fl({billingApiUrl:c,sessionId:h,nonce:y,responseJson:P});if(O)return O;throw Ua(new $e.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}let ie=new $e.FloPayError(P?.message??"Payment failed. Please try again.","api_error",{code:P?.code??P?.gatewayErrorCode,declineCode:P?.declineCode??P?.gatewayDeclineReason,statusCode:q.status});throw Object.assign(ie,{telemetryOutcome:(0,$e.classifyPaymentRejection)(q.status,P)})}async function ra(e,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:i,session:d,returnUrl:c,telemetry:h}){let y=t?.getRawProvider();if(!y)throw gr(new $e.FloPayError("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!r||!e.threeDSecureToken)throw Ua(new $e.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let f=(0,$e.isSetupIntentClientSecret)(e.threeDSecureToken),g=null,p=e.paymentMethodId,w=await _o(()=>xl(y,e.threeDSecureToken,f),"card");if(w){if(w.error)throw gr(new $e.FloPayError(w.error.message??`Failed to retrieve 3DS ${f?"setup":"payment"} status.`,"api_error",{code:w.error.code}),"card");let L=w.intent;!p&&L?.payment_method&&(typeof L.payment_method=="string"?p=L.payment_method:"id"in L.payment_method&&(p=L.payment_method.id??void 0))}let F=p?await _o(()=>Ml(y,e.threeDSecureToken,{payment_method:p,return_url:c??za(d)??window.location.href},f),"card"):null;if(F){if(F.error)throw gr(new $e.FloPayError(F.error.message??"3DS authentication failed.","api_error",{code:F.error.code}),"card");g=F.intent}else{let L=await _o(()=>y.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(L.error)throw gr(new $e.FloPayError(L.error.message??"3DS authentication failed.","api_error",{code:L.error.code}),"card");g=(f?L.setupIntent:L.paymentIntent)??null}if(g&&(g.status==="requires_capture"||g.status==="succeeded"||g.status==="processing")){let L=await ro({billingApiUrl:o,sessionId:i,session:d,telemetry:h,tokenizedData:{id:g.id,type:"card",threeDSecureActionResultTokenId:g.id},returnUrl:c});return L.type==="success"?{...L.result,paymentIntentId:L.result.paymentIntentId??g.id,paymentMethodId:L.result.paymentMethodId??p}:ra(L,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:i,session:d,returnUrl:c,telemetry:h})}throw gr(new $e.FloPayError("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let f=(n??t)?.getRawProvider();if(!f)throw gr(new $e.FloPayError("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:p}=await _o(()=>f.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(p)throw gr(new $e.FloPayError(p.message??"PayPal authorization failed.","api_error",{code:p.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:g}=await _o(()=>f.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:c??za(d)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(g)throw gr(new $e.FloPayError(g.message??"PayPal authorization failed.","api_error",{code:g.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new $e.FloPayError("Unsupported payment redirect state.","api_error")}function xo(e){if(e instanceof $e.FloPayError){let r=Cr(e.message);return r&&r!==e.message?Object.assign(new $e.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=Cr(t)??t;return new $e.FloPayError(n,"api_error")}function oa(e){let t=e.data.stripe?.publishableKey,n=!!e.data.paypal?.publishableKey;if(!t&&!n)throw new $e.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}:{}}function os(e){if(e)return e.isPaypal?"paypal":"card"}async function aa({publishableKey:e,paypalPublishableKey:t,billingApiUrl:n,locale:r,telemetry:o}){if(!e)return{flopay:null,paypalFlopay:null};let i=t&&t!==e?t:void 0,[d,c]=await Promise.all([(0,no.loadFloPay)(e,{billingApiUrl:n,locale:r,telemetry:o}),i?(0,no.loadFloPay)(i,{billingApiUrl:n,locale:r,telemetry:o}).catch(y=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",y),null)):Promise.resolve(null)]),h=null;return i?h=c:t&&(h=d),{flopay:d,paypalFlopay:h}}var vr=require("@flopay/js"),u=require("@flopay/shared"),Lt=require("@stripe/react-stripe-js"),s=zi(require("react"),1);function ls(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 cs={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 hr=require("react"),ds=require("react/jsx-runtime");function oo({capture:e,html:t,messageToken:n,expectedOrigin:r,theme:o,containerStyle:i,onReady:d,onError:c,onValidation:h}){let y=(0,hr.useRef)(null),f=(0,hr.useRef)(d),g=(0,hr.useRef)(c),p=(0,hr.useRef)(h);f.current=d,g.current=c,p.current=h;let w=(0,hr.useRef)(o);return w.current=o,(0,hr.useEffect)(()=>{let F=y.current;if(!F)return;let L=!0,he=!1,q=()=>{!L||he||(he=!0,f.current?.())},P=e.on("ready",()=>{q()}),ie=e.on("error",G=>{g.current?.(G.message??"There was a problem loading the secure card form.")}),O=e.on("validation",G=>{p.current?.(G.message??null)}),de={html:t,...n?{messageToken:n}:{},...r?{expectedOrigin:r}:{},...w.current?{theme:w.current}:{}};return e.mount(F,de).then(()=>{q()}).catch(G=>{L&&g.current?.(G instanceof Error?G.message:"Failed to load the secure card form.")}),()=>{L=!1,P(),ie(),O(),e.unmount()}},[e,t,n,r]),(0,hr.useEffect)(()=>{o&&e.applyTheme?.(o)},[e,o]),(0,ds.jsx)("div",{ref:y,"data-testid":"flopay-vault-card-fields",style:i})}function ao(e,t=.12){let n=/^#?([0-9a-fA-F]{6})$/.exec(e.trim());if(!n)return e;let r=Number.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 qa(e){if(typeof e=="number"||typeof e=="string")return e}function ia({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",h=t.nameInput;return{primaryColor:d,primaryHoverColor:o(r?.colorPrimaryHover)??ao(d,.12),inputBackgroundColor:o(t.cardInputBackground)??o(r?.colorBackground)??"#ffffff",textColor:o(t.cardInputColor)??o(h?.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(h?.fontFamily)??o(r?.fontFamily)??"Poppins, sans-serif",fontSize:o(t.cardInputFontSize)??o(r?.fontSizeBase)??"16px",fontWeight:String(qa(h?.fontWeight)??400),borderRadius:o(r?.borderRadius)??"8px"}}var l=require("react/jsx-runtime"),ar="flopay_stripe_resume",us="flopay_wallet_resume",Cs="fw1",Dl=300*1e3,Ll=900,Nl=25e3,sa={};function Ss(e){return e instanceof u.FloPayError&&(e.type==="validation_error"||e.statusCode===400||e.statusCode===422)}async function ca(e,t,...n){let r=n[2].provider;t?.({class:"lifecycle",name:"payment.intent.started",provider:r});try{return await new vr.PaymentAPI(e).createSessionIntent(...n)}catch(o){throw Ss(o)||t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"intent_create",provider:r}),o}}var Mo="flopay_paypal_resume",Ol=250,ps="Just a moment \u2014 we are finalizing your order. Please press pay again.";function Ha(e,t,n){e?.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:"provider_runtime",stage:"provider_load",provider:t,paymentMethodCategory:n,requestCategory:"provider_sdk"})}async function da({billingApiUrl:e,sessionId:t,nonce:n,request:r}){if(!(!t||!n))try{await new vr.PaymentAPI(e,{telemetry:!1}).reportSessionIntentDecline(t,n,r)}catch{}}function zl(e){return e instanceof u.FloPayError&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function $a(e){return e?.html?{html:e.html,...e.messageToken?{messageToken:e.messageToken}:{},...e.expectedOrigin?{expectedOrigin:e.expectedOrigin}:{}}:null}function ws({event:e,fallbackEmail:t,fallbackName:n}){let r=e.billingDetails,o=Mr(r?.name),i=Mr(n);return vn({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 Ul({event:e,prepared:t,email:n,billingName:r,methodLabel:o,collect:i}){let d=ws({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 ql=`
9
+ `})]})})}var rs=require("@flopay/shared"),rn=require("react");var os=require("react/jsx-runtime");function Eo({flopay:e,paypalFlopay:t,options:n,onInstrument:r,children:o}){let[i,d]=(0,rn.useState)(e instanceof Promise?null:e),[c,v]=(0,rn.useState)(t instanceof Promise||!t?null:t),y=(0,rn.useRef)(null),f=(0,rn.useRef)(null),g=Qr(r);(0,rn.useEffect)(()=>{g({class:"lifecycle",name:"checkout.mount"})},[g]),(0,rn.useEffect)(()=>{i&&g({class:"lifecycle",name:"sdk.initialize.ready"})},[g,i]),(0,rn.useEffect)(()=>{if(i)return Wt(i)?.subscribe?.(g)},[g,i]),(0,rn.useEffect)(()=>{if(!(!c||c===i))return Wt(c)?.subscribe?.(g)},[g,i,c]),(0,rn.useEffect)(()=>{if(!i)return;let F=Wt(i);return y.current=F?.beginCheckout()??F?.now()??0,F?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{F?.log({name:"checkout.unmount",stage:"unmount"})}},[i]),(0,rn.useEffect)(()=>{let F=!1;return e instanceof Promise?e.then(N=>{F||d(N)},()=>{F||g({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"})}):d(e),()=>{F=!0}},[g,e]),(0,rn.useEffect)(()=>{let F=!1;if(!t){v(null);return}return t instanceof Promise?t.then(N=>{F||v(N)},()=>{F||g({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED",provider:"paypal"})}):v(t),()=>{F=!0}},[g,t]),(0,rn.useEffect)(()=>{if(!i||f.current===i)return;f.current=i;let F=Wt(i);F?.log({name:"checkout.rendered",stage:"checkout_render"}),g({class:"lifecycle",name:"checkout.rendered"}),F?.performance({stage:"checkout_render",durationMs:F.elapsed(y.current??0),durationMode:"machine"})},[g,i]);let p=(0,rs.resolveBillingApiUrl)(n?.billingApiUrl),I=(0,rn.useMemo)(()=>({flopay:i,paypalFlopay:c,billingApiUrl:p,emitInstrument:g}),[i,c,p,g]);return(0,os.jsx)(qn.Provider,{value:I,children:o})}var ta="flopay_recent_completion_";function to(e){if(!(!e||typeof window>"u"))try{let t={expiresAt:Date.now()+6e4};window.sessionStorage.setItem(ta+e,JSON.stringify(t))}catch{}}function Oa(e){if(!e||typeof window>"u")return!1;try{let t=window.sessionStorage.getItem(ta+e);if(!t)return!1;let n=JSON.parse(t);return typeof n?.expiresAt!="number"||n.expiresAt<=Date.now()?(window.sessionStorage.removeItem(ta+e),!1):!0}catch{return!1}}var no=require("@flopay/js"),je=require("@flopay/shared");var To="card";async function Ml(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 Al(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 Ua(e,t){return Object.assign(e,{checkoutMethod:t})}function br(e,t){let n=e instanceof je.FloPayError?e:new je.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 _o(e,t){try{return await e()}catch(n){throw br(n,t)}}function is(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 Bl(e){return e.status==="succeeded"||e.status==="declined"}async function ss(e){if(typeof document>"u"||typeof window>"u")throw new je.FloPayError("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});if(e.signal?.aborted)throw new je.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 f=new AbortController,g=()=>f.abort();e.signal?.aborted?f.abort():e.signal?.addEventListener("abort",g);let p=window.setTimeout(()=>f.abort(),r);try{let I=await fetch(o,{method:"POST",headers:{"x-checkout-session-token":e.nonce,"content-type":"application/json"},body:"{}",signal:f.signal});if(!I.ok)return{status:"unknown"};let F=await I.json().catch(()=>null);return Fl(F)}catch{return{status:"unknown"}}finally{window.clearTimeout(p),e.signal?.removeEventListener("abort",g)}},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 f=await new Promise((g,p)=>{let I=!1,F=0,N=0,ge=0,V=!1,S=()=>{window.clearTimeout(F),window.clearInterval(N),window.clearTimeout(ge),window.removeEventListener("message",G),v.removeEventListener("load",q),e.signal?.removeEventListener("abort",de)},se=async()=>{if(!(I||V)){V=!0;try{let he=await i();if(I||!Bl(he))return;I=!0,S(),g(he)}finally{V=!1}}},q=()=>{window.clearTimeout(ge),ge=window.setTimeout(()=>{se()},250)},de=()=>{I||(I=!0,S(),p(new je.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"})))},G=he=>{if(he.source!==v.contentWindow||y&&he.origin!==y)return;let Ke=he.data;!Ke||typeof Ke!="object"||Ke.source!=="flopay-vault-3ds-return"||I||(I=!0,S(),g(null))};F=window.setTimeout(()=>{I||(I=!0,S(),p(new je.FloPayError("Card authentication timed out.","api_error",{code:"three_ds_timeout"})))},t),N=window.setInterval(()=>{se()},n),v.addEventListener("load",q),window.addEventListener("message",G),e.signal?.addEventListener("abort",de),e.signal?.aborted&&de()});return f||await i()}finally{c.parentNode?.removeChild(c),d?.isConnected&&d.focus()}}function Fl(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 Ir(e,t="Payment failed. Please try again.",n){let r=n?.checkoutMethod??e?.checkoutMethod??(e?.type==="paypal_redirect_required"?"paypal":"card"),o=e?.message??t,i=wr(o)??o;return Ua(new je.FloPayError(i,"api_error",{code:(0,je.normalizeCheckoutFailureOutcome)(e?.outcome)??(0,je.normalizeCheckoutFailureOutcome)(e?.type)??e?.gatewayErrorCode}),r)}function za(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function na(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}function ls(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let o of n)if(typeof o=="string"&&o.length>0&&(!t?.requirePaymentIntentClientSecret||na(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||na(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 f of y)if(typeof f=="string"&&f.length>0&&(!t?.requirePaymentIntentClientSecret||na(f)))return f}}}}async function Dl({billingApiUrl:e,sessionId:t,nonce:n,responseJson:r}){let o=ls(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 no.PaymentAPI(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(na(c))return{type:"3ds_required",threeDSecureToken:c}}catch{}return null}async function ro({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,f=n.customer?.id??n.accountData?.userId??"",g=n.customer?.email??n.accountData?.email??"",p=n.customer?.firstName??n.accountData?.firstName??"",I=n.customer?.lastName??n.accountData?.lastName??"",F=n.customer?.country??n.accountData?.country??void 0,N=n.customer?.zip??n.accountData?.zip??void 0,V=await new no.PaymentAPI(c,d===!1?{telemetry:!1}:void 0).processPayment(f,{sessionId:v,nonce:y,paymentMethodCategory:"saved",tokenizedData:o,accountData:{userId:f,email:g,firstName:p,lastName:I,country:F,zip:N},returnUrl:i??za(n)});if(V.ok){let q=typeof V.json=="function"?await V.json().catch(()=>null):null;return(0,je.isAuthorizationOnlySession)(n)||q?.status==="authorized"?{type:"success",result:{status:"authorized",paymentId:typeof q?.paymentId=="string"?q.paymentId:n.paymentId,sessionId:typeof q?.sessionId=="string"?q.sessionId:v,authorizationExpiresAt:typeof q?.authorizationExpiresAt=="string"?q.authorizationExpiresAt:n.authorizationExpiresAt,paymentMethodId:Co(o),checkoutMethod:as(o)}}:{type:"success",result:{status:"succeeded",paymentIntentId:o?.threeDSecureActionResultTokenId,paymentMethodId:Co(o),checkoutMethod:as(o)}}}let S;try{S=await V.json()}catch(q){throw new je.FloPayError("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:V.status,cause:q})}if(S?.type==="paypal_redirect_required"||S?.type==="3ds_required"){let q=ls(S);if(!q)throw new je.FloPayError("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:V.status});return{type:S.type,threeDSecureToken:q,paymentMethodId:S.paymentMethodId}}if(S?.gatewayErrorCode==="authentication_required"){let q=await Dl({billingApiUrl:c,sessionId:v,nonce:y,responseJson:S});if(q)return q;throw Ua(new je.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}let se=new je.FloPayError(S?.message??"Payment failed. Please try again.","api_error",{code:S?.code??S?.gatewayErrorCode,declineCode:S?.declineCode??S?.gatewayDeclineReason,statusCode:V.status});throw Object.assign(se,{telemetryOutcome:(0,je.classifyPaymentRejection)(V.status,S)})}async function ra(e,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:i,session:d,returnUrl:c,telemetry:v}){let y=t?.getRawProvider();if(!y)throw br(new je.FloPayError("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!r||!e.threeDSecureToken)throw Ua(new je.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let f=(0,je.isSetupIntentClientSecret)(e.threeDSecureToken),g=null,p=e.paymentMethodId,I=await _o(()=>Ml(y,e.threeDSecureToken,f),"card");if(I){if(I.error)throw br(new je.FloPayError(I.error.message??`Failed to retrieve 3DS ${f?"setup":"payment"} status.`,"api_error",{code:I.error.code}),"card");let N=I.intent;!p&&N?.payment_method&&(typeof N.payment_method=="string"?p=N.payment_method:"id"in N.payment_method&&(p=N.payment_method.id??void 0))}let F=p?await _o(()=>Al(y,e.threeDSecureToken,{payment_method:p,return_url:c??za(d)??window.location.href},f),"card"):null;if(F){if(F.error)throw br(new je.FloPayError(F.error.message??"3DS authentication failed.","api_error",{code:F.error.code}),"card");g=F.intent}else{let N=await _o(()=>y.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(N.error)throw br(new je.FloPayError(N.error.message??"3DS authentication failed.","api_error",{code:N.error.code}),"card");g=(f?N.setupIntent:N.paymentIntent)??null}if(g&&(g.status==="requires_capture"||g.status==="succeeded"||g.status==="processing")){let N=await ro({billingApiUrl:o,sessionId:i,session:d,telemetry:v,tokenizedData:{id:g.id,type:"card",threeDSecureActionResultTokenId:g.id},returnUrl:c});return N.type==="success"?{...N.result,paymentIntentId:N.result.paymentIntentId??g.id,paymentMethodId:N.result.paymentMethodId??p}:ra(N,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:i,session:d,returnUrl:c,telemetry:v})}throw br(new je.FloPayError("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let f=(n??t)?.getRawProvider();if(!f)throw br(new je.FloPayError("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:p}=await _o(()=>f.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(p)throw br(new je.FloPayError(p.message??"PayPal authorization failed.","api_error",{code:p.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:g}=await _o(()=>f.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:c??za(d)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(g)throw br(new je.FloPayError(g.message??"PayPal authorization failed.","api_error",{code:g.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new je.FloPayError("Unsupported payment redirect state.","api_error")}function xo(e){if(e instanceof je.FloPayError){let r=wr(e.message);return r&&r!==e.message?Object.assign(new je.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=wr(t)??t;return new je.FloPayError(n,"api_error")}function oa(e){let t=e.data.stripe?.publishableKey,n=!!e.data.paypal?.publishableKey;if(!t&&!n)throw new je.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}:{}}function as(e){if(e)return e.isPaypal?"paypal":"card"}async function aa({publishableKey:e,paypalPublishableKey:t,billingApiUrl:n,locale:r,telemetry:o}){if(!e)return{flopay:null,paypalFlopay:null};let i=t&&t!==e?t:void 0,[d,c]=await Promise.all([(0,no.loadFloPay)(e,{billingApiUrl:n,locale:r,telemetry:o}),i?(0,no.loadFloPay)(i,{billingApiUrl:n,locale:r,telemetry:o}).catch(y=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",y),null)):Promise.resolve(null)]),v=null;return i?v=c:t&&(v=d),{flopay:d,paypalFlopay:v}}var Pr=require("@flopay/js"),u=require("@flopay/shared"),$t=require("@stripe/react-stripe-js"),s=qi(require("react"),1);function cs(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 ds={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 Cr=require("react"),us=require("react/jsx-runtime");function oo({capture:e,html:t,messageToken:n,expectedOrigin:r,theme:o,containerStyle:i,onReady:d,onError:c,onValidation:v}){let y=(0,Cr.useRef)(null),f=(0,Cr.useRef)(d),g=(0,Cr.useRef)(c),p=(0,Cr.useRef)(v);f.current=d,g.current=c,p.current=v;let I=(0,Cr.useRef)(o);return I.current=o,(0,Cr.useEffect)(()=>{let F=y.current;if(!F)return;let N=!0,ge=!1,V=()=>{!N||ge||(ge=!0,f.current?.())},S=e.on("ready",()=>{V()}),se=e.on("error",G=>{g.current?.(G.message??"There was a problem loading the secure card form.")}),q=e.on("validation",G=>{p.current?.(G.message??null)}),de={html:t,...n?{messageToken:n}:{},...r?{expectedOrigin:r}:{},...I.current?{theme:I.current}:{}};return e.mount(F,de).then(()=>{V()}).catch(G=>{N&&g.current?.(G instanceof Error?G.message:"Failed to load the secure card form.")}),()=>{N=!1,S(),se(),q(),e.unmount()}},[e,t,n,r]),(0,Cr.useEffect)(()=>{o&&e.applyTheme?.(o)},[e,o]),(0,us.jsx)("div",{ref:y,"data-testid":"flopay-vault-card-fields",style:i})}function ao(e,t=.12){let n=/^#?([0-9a-fA-F]{6})$/.exec(e.trim());if(!n)return e;let r=Number.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 qa(e){if(typeof e=="number"||typeof e=="string")return e}function ia({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)??ao(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(qa(v?.fontWeight)??400),borderRadius:o(r?.borderRadius)??"8px"}}var l=require("react/jsx-runtime"),sr="flopay_stripe_resume",ps="flopay_wallet_resume",Ss="fw1",Ll=300*1e3,Nl=900,Ol=25e3,zl=25e3,$a={},ja={};function ws(e){return e instanceof u.FloPayError&&(e.type==="validation_error"||e.statusCode===400||e.statusCode===422)}async function la(e,t,...n){let r=n[2].provider;t?.({class:"lifecycle",name:"payment.intent.started",provider:r});try{return await new Pr.PaymentAPI(e,{telemetry:!1}).createSessionIntent(...n)}catch(o){throw ws(o)||t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"intent_create",provider:r}),o}}var Mo="flopay_paypal_resume",Ul=250,ms="Just a moment \u2014 we are finalizing your order. Please press pay again.";function Ya(e,t,n){e?.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:"provider_runtime",stage:"provider_load",provider:t,paymentMethodCategory:n,requestCategory:"provider_sdk"})}async function ca({billingApiUrl:e,sessionId:t,nonce:n,request:r}){if(!(!t||!n))try{await new Pr.PaymentAPI(e,{telemetry:!1}).reportSessionIntentDecline(t,n,r)}catch{}}function ql(e){return e instanceof u.FloPayError&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function Va(e){return e?.html?{html:e.html,...e.messageToken?{messageToken:e.messageToken}:{},...e.expectedOrigin?{expectedOrigin:e.expectedOrigin}:{}}:null}function ks({event:e,fallbackEmail:t,fallbackName:n}){let r=e.billingDetails,o=t?.trim(),i=Mr(n),d=i.firstName?i:Mr(r?.name);return kn({email:(0,u.isValidEmail)(o)?o:r?.email?.trim(),firstName:d.firstName,lastName:d.lastName})}async function $l({event:e,prepared:t,email:n,billingName:r,methodLabel:o,collect:i}){let d=ks({event:e,fallbackEmail:t?.accountPatch?.email??n,fallbackName:[t?.accountPatch?.firstName,t?.accountPatch?.lastName].join(" ").trim()||r});return(0,u.isValidEmail)(d.email)?d:i(o,d)}var jl=`
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 @@ ${Jt.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
- `,la=44,Ao=280,ms=`flopay-card-enter ${Ao}ms cubic-bezier(0, 0, 0.2, 1) both`,ys=`flopay-card-exit ${Ao}ms cubic-bezier(0.4, 0, 0.2, 1) both`,$l=`flopay-buttons-enter ${Ao}ms cubic-bezier(0, 0, 0.2, 1) both`,jl=`flopay-buttons-exit ${Ao}ms cubic-bezier(0.4, 0, 0.2, 1) both`;function Vl(e){return e.gateway==="stripe"?"stripe":e.gateway==="paypal"||e.isPaypal?"paypal":void 0}function Ya(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"};function Hl(e){return e.isPaypal||e.gateway==="paypal"||e.paymentMethodType==="paypal"?"paypal":e.paymentMethodType==="apple_pay"||e.paymentMethodType==="google_pay"?"wallet":e.paymentMethodType&&e.paymentMethodType!=="card"?"apm":"card"}var ks={width:"100%",minHeight:la,margin:"0 0 0.5rem",padding:"0.75rem 0.875rem",border:"1px solid #2563eb",borderRadius:8,background:"#eff6ff",color:"#1d4ed8",fontSize:"0.95rem",fontWeight:700,cursor:"pointer"};function Yl(e){switch(e){case"paypal":return"PayPal";case"apple_pay":return"Apple Pay";case"google_pay":return"Google Pay";default:return"Card"}}function fs(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function Va(e){return e==="paypal"?"PayPal":(0,u.getStripeMethodDisplayName)(e)}function Wl(e,t){let n=`We couldn't open ${Va(e)}. Try again or choose another payment method.`;return t?`${n} Allow pop-ups for this site, then try again.`:n}function Gl(e){let t=(0,u.getPostalCodeExample)(e);return`Enter a valid ${(0,u.getPostalCodeLabel)(e)}${t?` (e.g. ${t})`:""}`}function Jl(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 gs(e,t){return t instanceof u.FloPayError?t:new u.FloPayError(t instanceof Error?t.message:`${Yl(e)} before-click hook failed.`,"validation_error")}function ja(){return(0,l.jsx)("style",{children:ql})}function Zl(e){return typeof e=="number"?`${e}px`:e}function Is(e,t){let n=e.availablePaymentMethods;return n&&t.some(r=>n[r])?"ready":"unavailable"}function Rs({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 hs(e){return e!=="unavailable"&&e!=="load_error"}function ua(e){return(0,l.jsx)(ec,{...e})}function vs({sessionId:e,nonce:t,email:n,billingApiUrl:r,onTokenizedBody:o,onErrorChange:i,isProcessing:d=!1,onButtonClick:c,onDecline:h,onTechnicalFailure:y,runBeforeButtonClick:f,billingName:g,onBuyerIdentityReady:p,onLoadStateChange:w,placeholderBorderRadius:F}){let L=fr(),{emitInstrument:he}=(0,s.useContext)(Dn),q=(0,Lt.useStripe)(),P=(0,Lt.useElements)(),[ie,O]=(0,s.useState)("loading");(0,s.useEffect)(()=>{w?.(ie)},[ie,w]);let[de,G]=(0,s.useState)(!1),ve=!(0,u.isValidEmail)(n?.trim())||!g?.trim(),{request:Ve,collect:we,finish:wt}=Jr(),qe=(0,s.useRef)(!1),Me=(0,s.useRef)(null),Ae=(0,s.useRef)(null),[se,re]=(0,s.useState)(0),[D,Be]=(0,s.useState)(!1),Fe=(0,s.useRef)(!1),Q=(0,s.useRef)(new Map),{startAttempt:Ee,finishAttempt:be,invalidateAttempt:x,isAttemptInvalidated:Y,isAttemptCurrent:ke}=ko((oe,$,z)=>{y?.(oe,$,{...z,popupBlocked:z?.popupBlocked??Sr($)}),Be(!0),re(We=>We+1)});(0,s.useEffect)(()=>{D&&Ae.current?.focus()},[D,se]);let ge=(0,s.useCallback)(()=>{re(oe=>oe+1)},[]),ne=(0,s.useCallback)((oe,$,z)=>{x(z),y?.("paypal",oe,{code:$,popupBlocked:Sr(oe)}),Be(!0),ge()},[x,y,ge]),Ne=(0,s.useCallback)(()=>{window.setTimeout(()=>{(Me.current?.querySelector("iframe")??Me.current)?.focus()},0)},[]);(0,s.useEffect)(()=>{Fe.current&&(Fe.current=!1,Ne())},[Ne,se]);let ot=(0,s.useCallback)(()=>{Be(!1),i?.(null),Ne()},[Ne,i]);(0,s.useEffect)(()=>{if(!q||qe.current)return;let oe=new URLSearchParams(window.location.search),$=oe.get("payment_intent"),z=oe.get("payment_intent_client_secret"),We=oe.get("redirect_status");if(!$||!z)return;qe.current=!0;let Je;try{let at=localStorage.getItem(Mo);if(at){let k=JSON.parse(at);k.clientSecret===z&&(Je={...k.accountPatch?{accountPatch:k.accountPatch}:{},...k.sessionId?{sessionId:k.sessionId}:{},...k.nonce?{nonce:k.nonce}:{}})}}catch{}try{localStorage.removeItem(Mo)}catch{}let ye=new URL(window.location.href);ye.searchParams.delete("payment_intent"),ye.searchParams.delete("payment_intent_client_secret"),ye.searchParams.delete("redirect_status"),window.history.replaceState({},"",ye.toString()),(async()=>{try{if(G(!0),We==="failed"){let E="PayPal payment was declined. Please try again.";i?.(E),h?.(Vt("paypal",E));return}let{paymentIntent:at,error:k}=await q.retrievePaymentIntent(z);if(k){i?.(k.message??"Failed to retrieve PayPal payment status.");return}if(at&&(at.status==="requires_capture"||at.status==="succeeded")){let E=typeof at.payment_method=="string"?at.payment_method:at.payment_method?.id;o({id:E??at.id,type:"card",threeDSecureActionResultTokenId:at.id,isPaypal:!0},Je)}else{let E="PayPal payment was not completed. Please try again.";i?.(E),h?.(Vt("paypal",E))}}catch(at){i?.(at instanceof Error?at.message:"Failed to complete PayPal payment.")}finally{G(!1)}})()},[q,o,i,h]);let ft=(0,s.useCallback)(async oe=>{if(d||de){oe.reject();return}let $=f?await f("paypal"):{proceed:!0};if(!$.proceed){Q.current.delete(se),oe.reject();return}let z=Ee("paypal");Q.current.set(se,{generation:z,accountPatch:$.accountPatch,sessionId:$.sessionId,nonce:$.nonce}),Be(!1),c?.("paypal"),oe.resolve()},[d,c,f,Ee,de,se]),Ye=(0,s.useCallback)(async oe=>{if(!q||!P)return;let $=Q.current.get(se);if($&&!ke($.generation)){Q.current.delete(se);return}if(!$&&Y()||$&&!be($.generation))return;$||be();let z=$??null;if(Q.current.delete(se),!z&&f){let E=await f("paypal");if(!E.proceed){oe.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}z={accountPatch:E.accountPatch,sessionId:E.sessionId,nonce:E.nonce}}let We=z?.sessionId??e,Je=z?.nonce??t,ye=await Ul({event:oe,prepared:z,email:n,billingName:g,methodLabel:"PayPal",collect:we});if(!ye){oe.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let at=ye.email,k=vn({...z?.accountPatch,...ye});try{if(G(!0),i?.(null),!We||!(0,u.isValidEmail)(at))throw new Error("Missing sessionId or email for PayPal payment");await p?.(ye);let E=q.createPaymentMethod,{error:Oe,paymentMethod:pe}=await E({type:"paypal"});if(Oe){ne(Oe,"stripe_paypal_create_payment_method_failed",$?.generation),oe.paymentFailed({reason:"fail"});return}let le=await ca(r,he,We,Je??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:pe?.id??null,intentKind:"payment"});if(le.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let rt=le.clientSecret,ze={return_url:window.location.href};if(pe?.id&&(ze.payment_method=pe.id),typeof window<"u")try{localStorage.setItem(Mo,JSON.stringify({clientSecret:rt,sessionId:We,nonce:Je,accountPatch:k}))}catch{}let{error:Xe,paymentIntent:At}=await q.confirmPayment({clientSecret:rt,confirmParams:ze,redirect:"if_required"});if(Xe){if(typeof window<"u")try{localStorage.removeItem(Mo)}catch{}if(Co(Xe)){let ee=Xe.message??"Your payment was declined.";i?.(ee),h?.(Vt("paypal",ee,{code:yr(Xe),declineCode:Zr(Xe)})),await da({billingApiUrl:r,sessionId:We,nonce:Je,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:yr(Xe)??"provider_declined"}})}else ne(Xe,"stripe_paypal_confirm_failed",$?.generation);return}if(typeof window<"u")try{localStorage.removeItem(Mo)}catch{}let I=typeof At?.payment_method=="string"?At.payment_method:At?.payment_method?.id;o({id:I??At?.id,type:"card",threeDSecureActionResultTokenId:At?.id,isPaypal:!0},{accountPatch:k,paymentMethodCategory:"paypal",sessionId:We,nonce:Je});return}catch(E){ne(E,"stripe_paypal_failed",$?.generation)}finally{G(!1)}},[q,P,e,t,n,g,we,p,r,he,o,i,h,f,ne,be,ke,Y,se]);return(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(Rs,{state:ie,placeholderTestId:"flopay-paypal-placeholder",borderRadius:F,children:(0,l.jsxs)("div",{ref:Me,tabIndex:-1,"data-testid":"flopay-paypal-focus-target",role:"group","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[D&&(0,l.jsx)("button",{ref:Ae,type:"button","data-testid":"flopay-paypal-retry-button",onClick:ot,style:ks,children:"Try PayPal again"}),Ve&&(0,l.jsx)(Xr,{identity:Ve.identity,methodLabel:Ve.methodLabel,onComplete:wt,onCancel:()=>wt(null)},Ve.id),(0,l.jsx)("div",{style:{display:Ve?"none":void 0},children:(0,l.jsx)(Lt.ExpressCheckoutElement,{onReady:oe=>O(Is(oe,["paypal"])),onLoadError:()=>{O("load_error"),Ha(qt(L),"paypal","paypal")},onClick:ft,onConfirm:Ye,onCancel:()=>{let oe=Q.current.get(se);Q.current.delete(se),qt(L)?.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),x(oe?.generation),Be(!1),Fe.current=!0,ge()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:ve,emailRequired:ve,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},se)})]})}),de&&(0,l.jsx)(Nn,{status:"processing"})]})}function bs({sessionId:e,nonce:t,email:n,billingApiUrl:r,intentKind:o,expressMethods:i,onTokenizedBody:d,onErrorChange:c,onButtonClick:h,onDecline:y,onTechnicalFailure:f,runBeforeButtonClick:g,billingName:p,onBuyerIdentityReady:w,onLoadStateChange:F,placeholderBorderRadius:L}){let he=fr(),{emitInstrument:q}=(0,s.useContext)(Dn),P=(0,Lt.useStripe)(),ie=(0,Lt.useElements)(),[O,de]=(0,s.useState)("loading");(0,s.useEffect)(()=>{F?.(O)},[O,F]);let[G,ve]=(0,s.useState)(!1),Ve=(0,s.useRef)(!(0,u.isValidEmail)(n?.trim())||!p?.trim()).current,{request:we,collect:wt,finish:qe}=Jr(),Me=(0,s.useRef)(null),Ae=(0,s.useRef)(null),[se,re]=(0,s.useState)(0),[D,Be]=(0,s.useState)(!1),[Fe,Q]=(0,s.useState)("google_pay"),Ee=(0,s.useRef)(!1),be=(0,s.useRef)("google_pay"),x=(0,s.useRef)("google_pay"),Y=(0,s.useRef)(null),ke=(0,s.useRef)(new Map),{startAttempt:ge,finishAttempt:ne,invalidateAttempt:Ne,isAttemptInvalidated:ot,isAttemptCurrent:ft,generationRef:Ye}=ko((k,E,Oe)=>{f?.(k,E,{...Oe,popupBlocked:Oe?.popupBlocked??Sr(E)}),Q(k),Be(!0),re(pe=>pe+1)});(0,s.useEffect)(()=>{D&&Ae.current?.focus()},[D,se]);let oe=(0,s.useCallback)(()=>{re(k=>k+1)},[]),$=(0,s.useCallback)((k,E,Oe,pe)=>{Ne(pe),f?.(k,E,{code:Oe,popupBlocked:Sr(E)}),Q(k),Be(!0),oe()},[Ne,f,oe]),z=(0,s.useCallback)(()=>{window.setTimeout(()=>{(Me.current?.querySelector("iframe")??Me.current)?.focus()},0)},[]);(0,s.useEffect)(()=>{Ee.current&&(Ee.current=!1,z())},[z,se]);let We=(0,s.useCallback)(()=>{Be(!1),c?.(null),z()},[z,c]),Je=(0,s.useCallback)(async k=>{let E=!1,Oe=M=>{E||(E=!0,k.paymentFailed({reason:"fail",...M?{message:M}:{}}))};if(!P||!ie){Oe();return}let pe=ke.current.get(se);if(pe&&!ft(pe.generation)){ke.current.delete(se),Oe();return}if(!pe&&ot()){Oe();return}if(pe&&!ne(pe.generation)){Oe();return}pe||ne();let le=k.expressPaymentType??pe?.method??be.current,rt=pe??null,ze=fs(le),Xe=qt(he),At=Xe?.now()??globalThis.performance?.now()??Date.now(),I=new AbortController,ee=!1,vt,Ze=new Promise((M,pt)=>{vt=pt}),Jt=window.setTimeout(()=>{ee=!0,I.abort(),vt(sa)},Nl),Kt=async(M,pt,Rt)=>{let it=Xe?.now()??globalThis.performance?.now()??Date.now();try{return await Promise.race([Rt,Ze])}finally{let kt=Xe?.now()??globalThis.performance?.now()??Date.now();Xe?.performance({stage:M,durationMs:Math.max(0,kt-it),durationMode:"machine",requestCategory:pt,paymentMethodCategory:"wallet",provider:"stripe",...ee?{statusClass:"timeout"}:{}})}};try{if(ve(!0),c?.(null),!rt&&g){let Qe=await Kt("processing","other",g(ze));if(!Qe.proceed){Oe();return}rt={accountPatch:Qe.accountPatch,sessionId:Qe.sessionId,nonce:Qe.nonce}}let M=rt?.sessionId??e,pt=rt?.nonce??t,Rt=ws({event:k,fallbackEmail:Y.current?.email??rt?.accountPatch?.email??n,fallbackName:[Y.current?.firstName??rt?.accountPatch?.firstName,Y.current?.lastName??rt?.accountPatch?.lastName].filter(Boolean).join(" ")||p});if(!(0,u.isValidEmail)(Rt.email)){Oe("Buyer details are required."),wt(Va(le),Rt).then(Qe=>{Qe&&(Y.current=Qe)});return}Y.current=null;let it=vn({...rt?.accountPatch,...Rt});await Kt("processing","provider_sdk",Promise.resolve(w?.(Rt)));let{error:kt}=await Kt("tokenization","provider_sdk",ie.submit());if(kt){Oe(),$(le,kt,"stripe_wallet_submit_failed",pe?.generation);return}if(!M)throw new Error("Missing sessionId or email for payment.");let pn=await Kt("processing","intent_create",ca(r,q,M,pt??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:le,paymentMethodId:null,intentKind:o},{signal:I.signal}));if(pn.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let en=pn.clientSecret,mn=(0,u.isSetupIntentClientSecret)(en)?P.confirmSetup({elements:ie,clientSecret:en,redirect:"if_required"}):P.confirmPayment({elements:ie,clientSecret:en,redirect:"if_required"}),Nt=!1,bn=Qe=>{if(Nt||Qe.error||pe&&Ye.current!==pe.generation)return;let yt=Qe.setupIntent??Qe.paymentIntent,tn=yt?.id,tt=yt?.status,Xt=Qe.setupIntent?tt==="succeeded":bo(typeof tt=="string"?tt:void 0),Zt=yt?.payment_method,nn=null;if(typeof Zt=="string"?nn=Zt:typeof Zt?.id=="string"&&(nn=Zt.id),!Xt||typeof tn!="string"||!nn)return;Nt=!0;let zt=`${Cs}:${M}`;if(typeof window<"u")try{localStorage.setItem(zt,JSON.stringify({createdAt:Date.now(),sessionId:M,nonce:pt,accountPatch:it,paymentMethodId:nn,providerIntentId:tn,paymentMethodType:le}))}catch{}try{d({id:nn,type:"card",threeDSecureActionResultTokenId:tn},{accountPatch:it,paymentMethodCategory:"wallet",sessionId:M,nonce:pt})}finally{if(typeof window<"u")try{localStorage.removeItem(zt)}catch{}}};mn.then(Qe=>{ee&&bn(Qe)},()=>{});let Ht;try{Ht=await Kt("three_ds_handoff","provider_sdk",mn)}catch(Qe){throw Qe!==sa&&Xe?.error({...Ki(Qe),stage:"three_ds_handoff",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe",statusClass:"unknown"}),Qe}let mt=Ht.error;if(mt){if(Co(mt)){let Qe=mt.message??"Your payment was declined.";Oe(Qe),c?.(Qe),y?.(Vt(ze,Qe,{code:yr(mt),declineCode:Zr(mt)})),da({billingApiUrl:r,sessionId:M,nonce:pt,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:le,providerDeclineReason:yr(mt)??"provider_declined"}})}else Oe(),$(le,mt,"stripe_wallet_confirm_failed",pe?.generation);return}if(bn(Ht),!Nt)throw new Error("Invalid provider returned for APM intent")}catch(M){M===sa&&Xe?.error({errorCode:"REQUEST_TIMEOUT",stage:"callback",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe",statusClass:"timeout",failureCategory:"provider_runtime"}),Oe(),$(le,M,M===sa?"stripe_wallet_authorization_timeout":"stripe_wallet_failed",pe?.generation)}finally{window.clearTimeout(Jt);let M=Xe?.now()??globalThis.performance?.now()??Date.now();Xe?.performance({stage:"callback",durationMs:Math.max(0,M-At),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe",...ee?{statusClass:"timeout"}:{}}),ve(!1)}},[P,ie,e,t,n,p,wt,w,r,q,o,d,c,y,g,$,ne,ft,ot,Ye,he,se]),ye=(0,s.useMemo)(()=>{let k=["applePay","googlePay","paypal","link","amazonPay","klarna"],E=new Set(["applePay","googlePay"]),Oe=new Set(i.map(u.stripeExpressMethodToOptionKey)),pe={};for(let le of k)Oe.has(le)?pe[le]=E.has(le)?"always":"auto":pe[le]="never";return pe},[i]),at=(0,s.useMemo)(()=>i.map(u.stripeExpressMethodToOptionKey),[i]);return(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(Rs,{state:O,placeholderTestId:"flopay-wallet-placeholder",borderRadius:L,children:(0,l.jsxs)("div",{ref:Me,tabIndex:-1,"data-testid":"flopay-wallet-focus-target",role:"group","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[D&&(0,l.jsxs)("button",{ref:Ae,type:"button","data-testid":"flopay-wallet-retry-button",onClick:We,style:ks,children:["Try ",Va(Fe)," again"]}),we&&(0,l.jsx)(Xr,{identity:we.identity,methodLabel:we.methodLabel,onComplete:qe,onCancel:()=>qe(null)},we.id),(0,l.jsx)("div",{style:{display:we?"none":void 0},children:(0,l.jsx)(Lt.ExpressCheckoutElement,{onReady:k=>{de(Is(k,at))},onLoadError:k=>{de("load_error"),Ha(qt(he),"stripe","wallet")},onClick:async k=>{be.current=k.expressPaymentType,x.current=fs(k.expressPaymentType);let E=!0,Oe=window.setTimeout(()=>{E=!1,k.reject()},Ll),pe=g?await g(x.current):{proceed:!0};if(window.clearTimeout(Oe),!E)return;if(!pe.proceed){ke.current.delete(se),k.reject();return}let le=ge(k.expressPaymentType);ke.current.set(se,{generation:le,method:k.expressPaymentType,accountPatch:pe.accountPatch,sessionId:pe.sessionId,nonce:pe.nonce}),Be(!1),h?.(x.current),k.resolve()},onConfirm:Je,onCancel:()=>{let k=ke.current.get(se);ke.current.delete(se),qt(he)?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet"}),Ne(k?.generation),Be(!1),Ee.current=!0,oe()},options:{buttonType:{applePay:"plain",googlePay:"plain"},paymentMethods:ye,emailRequired:Ve,billingAddressRequired:Ve,layout:{maxColumns:1,overflow:"never"}}},se)})]})}),G&&(0,l.jsx)(Nn,{status:"processing"})]})}function Es(e,t){return{...e,paymentMethodTypes:[t],...t==="revolut_pay"||t==="sepa_debit"||t==="us_bank_account"?{setupFutureUsage:"off_session"}:null}}function Ql({method:e,themeId:t,submitting:n=!1,disabled:r=!1,highlighted:o=!1,hasNextStep:i=!1,onClick:d,backgroundColor:c,borderColor:h,textColor:y,borderRadius:f,fontFamily:g}){let p=(0,u.resolveStripeMethodBrandVariant)(e,t),w=cs[e],[F,L]=(0,s.useState)(!1),he=!!w&&!F,q=p?.backgroundColor??c??"#ffffff",P=p?.borderColor??h??"#d1d5db",ie=p?.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:la,padding:"0 1rem",backgroundColor:q,color:ie,border:`1px solid ${P}`,borderRadius:f??8,fontSize:"0.95rem",fontWeight:600,fontFamily:g,cursor:n||r?"not-allowed":"pointer",opacity:r&&!n?.55:1,animation:n?"flopay-pulse 1.5s ease-in-out infinite":void 0,display:"flex",alignItems:"center",justifyContent:"center",gap:8,transition:"transform 0.1s, opacity 140ms ease-out, border-color 140ms ease-out",boxShadow:o?"0 0 0 2px rgba(74, 73, 255, 0.15)":void 0},children:n?(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:[he?(0,l.jsx)("img",{src:w,alt:"","aria-hidden":"true",onError:()=>L(!0),loading:"lazy",decoding:"async",width:30,height:20,style:{width:30,height:20,flexShrink:0,borderRadius:3,objectFit:"contain",display:"inline-flex"}}):null,!he&&p?.logoSvg?(0,l.jsx)("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:p.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:ie,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 Ka({method:e,sessionId:t,nonce:n,email:r,billingName:o,onBuyerIdentityReady:i,billingApiUrl:d,onTokenizedBody:c,onErrorChange:h,onDecline:y,onCancel:f,runBeforeButtonClick:g,onButtonClick:p,isProcessing:w,submitButtonColor:F,submitButtonBorderRadius:L,submitButtonStyle:he,errorText:q}){let P=fr(),{emitInstrument:ie}=(0,s.useContext)(Dn),O=(0,Lt.useStripe)(),de=(0,Lt.useElements)(),[G,ve]=(0,s.useState)(!1),Ve=(0,s.useRef)(!1),[we,wt]=(0,s.useState)(!1),[qe,Me]=(0,s.useState)("loading"),[Ae,se]=(0,s.useState)(""),re=!(0,u.isValidEmail)(r?.trim()),D=!re||(0,u.isValidEmail)(Ae.trim()),Be=(0,s.useCallback)(async()=>{if(!O||!de||w||Ve.current||!we)return;Ve.current=!0,ve(!0);let Fe=g?await g("card"):{proceed:!0};if(!Fe.proceed){Ve.current=!1,ve(!1);return}p?.("card");let Q=Fe.sessionId??t,Ee=Fe.nonce??n,be=Mr(o?.trim()),x=vn({email:Fe.accountPatch?.email?.trim()||r?.trim()||Ae.trim(),firstName:Fe.accountPatch?.firstName?.trim()||be.firstName,lastName:Fe.accountPatch?.lastName?.trim()||be.lastName}),Y=x.email,ke=vn({...Fe.accountPatch,...x});try{if(h?.(null),!(0,u.isValidEmail)(Y))throw new Error("A valid email address is required for payment.");await i?.(x);let ge=await de.submit();if(ge.error){h?.(ge.error.message??"Payment failed.");return}let ne=[x.firstName,x.lastName].filter(Boolean).join(" "),Ne=await O.createPaymentMethod({elements:de,params:{billing_details:{email:Y,...ne?{name:ne}:{}}}});if(Ne.error||!Ne.paymentMethod){h?.(Ne.error?.message??"Failed to create payment method.");return}let ot=Ne.paymentMethod;if(!Q||!Y)throw new Error("Missing sessionId or email for payment.");let ft=ot.type||e,Ye=await ca(d,ie,Q,Ee??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:ft,paymentMethodId:null,intentKind:"payment"});if(Ye.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let oe=Ye.clientSecret;if(typeof window<"u")try{localStorage.setItem(ar,JSON.stringify({clientSecret:oe,sessionId:Q,nonce:Ee,accountPatch:ke,paymentMethodId:ot.id,paymentMethodType:ot.type??e,gateway:"stripe"}))}catch{}let{error:$,paymentIntent:z}=await O.confirmPayment({clientSecret:oe,confirmParams:{return_url:window.location.href,payment_method:ot.id},redirect:"if_required"});if($){if(typeof window<"u")try{localStorage.removeItem(ar)}catch{}let ye=$.message??"Payment failed.";h?.(ye),y?.(Vt("card",ye,{code:$.code})),await da({billingApiUrl:d,sessionId:Q,nonce:Ee,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:$.code??"provider_declined"}});return}let We=z?.status;if(!bo(We)){if(typeof window<"u")try{localStorage.removeItem(ar)}catch{}let ye=We==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";h?.(ye),y?.(Vt("card",ye,{code:We??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(ar)}catch{}let Je=typeof z?.payment_method=="string"?z.payment_method:z?.payment_method?.id;c({id:Je??ot.id,type:"card",threeDSecureActionResultTokenId:z?.id,gateway:"stripe",paymentMethodType:ot.type??e},{accountPatch:ke,paymentMethodCategory:"apm",sessionId:Q,nonce:Ee})}catch(ge){h?.(ge instanceof Error?ge.message:"Payment failed. Please try again.")}finally{Ve.current=!1,ve(!1)}},[O,de,w,we,g,p,t,n,r,o,Ae,i,d,ie,e,c,h,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:Ae,onChange:Fe=>se(Fe.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]})}),(0,l.jsx)(Lt.PaymentElement,{onReady:()=>Me("ready"),onLoadError:()=>{Me("load_error"),Ha(qt(P),"stripe","apm")},onChange:Fe=>{wt(!!Fe.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:()=>{Be()},disabled:!we||!D||G||w||qe!=="ready",style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:F,color:"white",border:"none",borderRadius:L,fontSize:"1rem",fontWeight:600,cursor:!we||!D||G||w||qe!=="ready"?"not-allowed":"pointer",opacity:!we||!D||G||w||qe!=="ready"?.5:1,transition:"opacity 120ms ease-out",...he??{}},children:G?"Processing\u2026":`Pay with ${(0,u.getStripeMethodDisplayName)(e)}`}),q&&(0,l.jsx)(eo,{margin:"0.75rem 0 0",children:q})]})}function Ps({sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:i,paymentElementMethods:d,stripeInstance:c,paymentElementBaseOptions:h,onTokenizedBody:y,onErrorChange:f,onButtonClick:g,onDecline:p,runBeforeButtonClick:w,onLoadStateChange:F,isProcessing:L=!1,submitButtonColor:he="#4A49FF",submitButtonBorderRadius:q=8,submitButtonStyle:P,buttonAppearance:ie,themeId:O,onExpandApm:de,expandedApmMethod:G}){let{emitInstrument:ve}=(0,s.useContext)(Dn),[Ve,we]=(0,s.useState)(null),[wt,qe]=(0,s.useState)(null),Me=(0,s.useRef)(!1),{request:Ae,collect:se,finish:re}=Jr();(0,s.useEffect)(()=>{d.length>0&&c?F?.("ready"):c||F?.("loading")},[d.length,c,F]);let D=(0,s.useCallback)(async x=>{if(!c||Me.current||L)return;Me.current=!0,qe(x);let Y=w?await w("card"):{proceed:!0};if(!Y.proceed){Me.current=!1,qe(null);return}g?.("card");let ke=Y.sessionId??e,ge=Y.nonce??t,ne=Mr([Y.accountPatch?.firstName,Y.accountPatch?.lastName].filter(Boolean).join(" ")||r),Ne=vn({email:Y.accountPatch?.email?.trim()||n?.trim(),firstName:Y.accountPatch?.firstName?.trim()||ne.firstName,lastName:Y.accountPatch?.lastName?.trim()||ne.lastName});if(!(0,u.isValidEmail)(Ne.email)){qe(null);let Ye=await se((0,u.getStripeMethodDisplayName)(x),Ne);if(!Ye){Me.current=!1;return}Ne=Ye,qe(x)}let ot=Ne.email,ft=vn({...Y.accountPatch,...Ne});try{if(f?.(null),!ke||!(0,u.isValidEmail)(ot))throw new Error("Missing sessionId or email for payment.");await o?.(Ne);let Ye=await ca(i,ve,ke,ge??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:x,paymentMethodId:null,intentKind:"payment"});if(Ye.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let oe=Ye.clientSecret;if(typeof window<"u")try{localStorage.setItem(ar,JSON.stringify({clientSecret:oe,sessionId:ke,nonce:ge,accountPatch:ft,paymentMethodType:x,gateway:"stripe"}))}catch{}let{error:$,paymentIntent:z}=await c.confirmPayment({clientSecret:oe,confirmParams:{return_url:window.location.href,payment_method_data:{type:x,billing_details:{name:[Ne.firstName,Ne.lastName].filter(Boolean).join(" "),...ot?{email:ot}:{}}}},redirect:"if_required"});if($){if(typeof window<"u")try{localStorage.removeItem(ar)}catch{}let ye=$.message??"Payment failed.";f?.(ye),p?.(Vt("card",ye,{code:$.code})),await da({billingApiUrl:i,sessionId:ke,nonce:ge,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:x,providerDeclineReason:$.code??"provider_declined"}});return}let We=z?.status;if(!bo(We)){if(typeof window<"u")try{localStorage.removeItem(ar)}catch{}let ye=We==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";f?.(ye),p?.(Vt("card",ye,{code:We??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(ar)}catch{}let Je=typeof z?.payment_method=="string"?z.payment_method:z?.payment_method?.id;y({id:Je??z?.id,type:"card",threeDSecureActionResultTokenId:z?.id,gateway:"stripe",paymentMethodType:x},{accountPatch:ft,paymentMethodCategory:"apm",sessionId:ke,nonce:ge})}catch(Ye){f?.(Ye instanceof Error?Ye.message:"Payment failed. Please try again.")}finally{Me.current=!1,qe(null)}},[c,L,w,g,e,t,n,se,i,ve,r,o,y,f,p]),[Be,Fe]=(0,s.useState)(null),Q=de?G??null:Be,Ee=(0,s.useCallback)(x=>{Me.current||L||Q&&Q!==x||((0,u.needsStripeMethodExplicitConfirm)(x)?de?de(x):Fe(x):D(x))},[Q,L,D,de]),be=(0,s.useMemo)(()=>Be?Es(h,Be):null,[Be,h]);return(0,l.jsx)("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:Ae?(0,l.jsx)(Xr,{identity:Ae.identity,methodLabel:Ae.methodLabel,onComplete:re,onCancel:()=>re(null)},Ae.id):d.map(x=>{let Y=G===x,ke=wt===x,ge=wt!==null&&wt!==x||G!=null&&G!==x;return(0,l.jsxs)(s.default.Fragment,{children:[(0,l.jsx)(Ql,{method:x,themeId:O,submitting:ke,disabled:ge,highlighted:Y,hasNextStep:(0,u.needsStripeMethodExplicitConfirm)(x),onClick:()=>Ee(x),backgroundColor:ie?.backgroundColor,borderColor:ie?.borderColor,textColor:ie?.textColor,borderRadius:ie?.borderRadius,fontFamily:ie?.fontFamily}),!de&&Be===x&&be&&c&&(0,l.jsx)(Lt.Elements,{stripe:c,options:be,children:(0,l.jsx)(Ka,{method:x,sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:i,onTokenizedBody:y,onErrorChange:f,onDecline:p,onCancel:()=>Fe(null),runBeforeButtonClick:w,onButtonClick:g,isProcessing:L,submitButtonColor:he,submitButtonBorderRadius:q,submitButtonStyle:P})},x)]},x)})})}function ec({sessionId:e,nonce:t,billingApiUrl:n,email:r,userId:o,onComplete:i,onError:d,onDecline:c,onTokenizedBody:h,firstName:y,lastName:f,chv:g,className:p,isProcessing:w,error:F,onErrorChange:L,showPayPal:he=!0,showStripe:q=!0,enabledPaymentMethods:P,enabledPaymentMethodCountries:ie,showApplePay:O=!0,showGooglePay:de=!0,layout:G="default",theme:ve,buttonsTheme:Ve,buttonsStyles:we,appearance:wt,cardButtonContent:qe,cardBackButtonContent:Me,cardTitleContent:Ae,showSecurityFooter:se,onButtonClick:re,onBeforeButtonClick:D,onBuyerIdentityReady:Be,enableAVS:Fe,cardFieldOrder:Q,cardPreFormSlot:Ee,avsLayout:be="row",country:x,zip:Y,addressLine1:ke,addressLine2:ge,city:ne,state:Ne,onCountryChange:ot,onZipChange:ft,avsCheck:Ye,checkoutType:oe,checkoutLayout:$,totalAmount:z=0,currency:We="usd",initialCardOpen:Je=!1,directPaypal:ye,isSubscription:at=!1,session:k,dataAttachmentPending:E=!1,dataAttachmentRequiresIdentity:Oe=!1,debug:pe=!1}){let le=fr(),rt=Jo(),ze=(0,s.useContext)(Jn),{emitInstrument:Xe}=(0,s.useContext)(Dn),At=k??ze.session,I=At?.gateways?.paypal?.providerObjectType??ye?.providerObjectType,ee=E||ze.claimPending===!0,vt=Oe||ze.claimRequiresIdentity===!0,Ze=ee&&!vt,Jt=Gi(),[Kt,M]=(0,s.useState)(!1),[pt,Rt]=(0,s.useState)(null),[it,kt]=(0,s.useState)(x??"US"),[pn,en]=(0,s.useState)(Y??""),[mn,Nt]=(0,s.useState)(ke??""),[bn,Ht]=(0,s.useState)(ge??""),[mt,Qe]=(0,s.useState)(ne??""),[yt,tn]=(0,s.useState)(Ne??""),[tt,Xt]=(0,s.useState)(""),[Zt,nn]=(0,s.useState)({}),zt=(0,s.useRef)(Y??""),$t=(0,s.useRef)(x??"US"),Pn=(0,s.useRef)(ke??""),rn=(0,s.useRef)(ge??""),Un=(0,s.useRef)(ne??""),on=(0,s.useRef)(Ne??""),_n=(0,s.useRef)(""),an=(0,s.useRef)({});(0,s.useEffect)(()=>{let a=(b,K,Le,H,Ce)=>{if(an.current[b])return;let Re=K?.trim();!Re||Re===Le.current||(Le.current=Re,H(Re),Ce?.(Re))};a("country",x,$t,kt,ot),a("zip",Y,zt,en,ft),a("addressLine1",ke,Pn,Nt),a("addressLine2",ge,rn,Ht),a("city",ne,Un,Qe),a("state",Ne,on,tn)},[x,Y,ke,ge,ne,Ne,ot,ft]);let ce=(0,s.useMemo)(()=>(0,u.resolveAVSConfig)(Fe),[Fe]),Cn=ce!==null,Qn=(0,s.useMemo)(()=>(0,u.isAuthorizationOnlySession)(k),[k]),er=!!k?.vault?.html,Pr=!!k?.gateways?.pcivault,Ir=!!(k?.gateways?.stripe?.enabledPaymentMethods??P)?.includes("card"),W=er||Ir||Pr,Ie=!!(q&&W&&le&&e),[Yt,sn]=(0,s.useState)(()=>G!=="buttons"||Je?e??null:null),[Te,qn]=(0,s.useState)(0),Tn=G!=="buttons"||Je||!!e&&Yt===e,Bt=(0,s.useMemo)(()=>!le||!Ie||!e||!Tn?null:le.cardCapture({sessionId:e,captureMethod:k?.captureMethod}),[le,Ie,e,Tn,k?.captureMethod]),ln=(0,s.useMemo)(()=>{let a=it,b=ce?(0,u.isAVSFieldVisible)(ce.postal_code,a):!1;return Jl(a,pn,b)},[ce,it,pn]),{avsInvalid:Rr,invalidAvsFields:Er}=(0,s.useMemo)(()=>{let a={line1:!1,city:!1,state:!1,zip:!1};if(!Ie||!ce)return{avsInvalid:!1,invalidAvsFields:a};let b=it,K=(Ce,Re)=>(0,u.isAVSFieldVisible)(Ce,b)&&!Re.trim(),Le={line1:K(ce.address_line_1,mn),city:K(ce.city,mt),state:K(ce.state,yt),zip:ln.empty||ln.malformed};return{avsInvalid:Le.line1||Le.city||Le.state||Le.zip,invalidAvsFields:Le}},[Ie,ce,it,mn,mt,yt,ln]),[Sn,lr]=(0,s.useState)(!1),[$n,xn]=(0,s.useState)(!1),[bt,tr]=(0,s.useState)(!1),[wn,jn]=(0,s.useState)({line1:!1,city:!1,state:!1}),yn=(0,s.useRef)(!1),Vn=(0,s.useRef)({email:!1,line1:!1,city:!1,state:!1,zip:!1}),Kn=(0,s.useRef)(!1),dt=(0,s.useCallback)(a=>{Vn.current[a]=!0,Kn.current=!0},[]),kn=(0,s.useCallback)(a=>!yn.current&&Vn.current[a],[]),Mn=(0,s.useCallback)(a=>{kn(a)&&jn(b=>b[a]?b:{...b,[a]:!0})},[kn]),[In,Hn]=(0,s.useState)(()=>$a(k?.vault)),[Ue,cn]=(0,s.useState)(Je&&W?"card":"buttons"),[Et,cr]=(0,s.useState)(null),dr=Ue==="expanding"||Ue==="card",ur=k?.gateways?.stripe?"stripe":void 0,Rn=(0,s.useCallback)(()=>{Xe?.({class:"card_surface",provider:ur})},[ur,Xe]),Yn=(0,s.useRef)(null),Ut=(0,s.useCallback)(a=>{Yn.current&&clearTimeout(Yn.current),Yn.current=setTimeout(()=>{Yn.current=null,a()},Ao)},[]);(0,s.useEffect)(()=>()=>{Yn.current&&clearTimeout(Yn.current)},[]);let N=(0,s.useCallback)(()=>{Rn(),sn(e??null),qn(a=>a+1),cn("expanding"),Ut(()=>cn("card"))},[Ut,Rn,e]),U=(0,s.useCallback)(()=>{cn("collapsing"),Ut(()=>cn("buttons"))},[Ut]),te=(0,s.useCallback)(a=>{cr(a),cn("apm-expanding"),Ut(()=>cn("apm-form"))},[Ut]),ae=(0,s.useCallback)(()=>{cn("apm-collapsing"),Ut(()=>{cn("buttons"),cr(null)})},[Ut]);(0,s.useEffect)(()=>{G==="buttons"&&Je&&W&&(sn(e??null),cn("card"))},[G,Je,W,e]);let[Ke,Z]=(0,s.useState)(null),J=(0,s.useRef)(!1),R=(0,s.useRef)(null),B=(0,s.useRef)("idle"),[X,gt]=(0,s.useState)(null),et=(0,s.useRef)(X);(0,s.useEffect)(()=>{et.current=X},[X]);let ue=n||Jt,st=(0,s.useRef)(null),T=(0,s.useMemo)(()=>{if(Be||ze.claimBuyerIdentity||k?.buyerIdentified!==!1||!e||!t)return;let a=`${ue}|${e}|${t}`;st.current?.key!==a&&(st.current={key:a,claim:Wr(new vr.PaymentAPI(ue,{telemetry:!1}),e,t,{...o?{userId:o}:{},...y?{firstName:y}:{},...f?{lastName:f}:{}})});let b=st.current.claim;return async K=>{await b(K)}},[Be,ze.claimBuyerIdentity,k?.buyerIdentified,e,t,ue,o,y,f]),m=Be??ze.claimBuyerIdentity??T,A=F??pt,j=(0,s.useMemo)(()=>(0,u.resolveTheme)(ve),[ve]),v=(0,s.useMemo)(()=>{let a=j?.buttonsLayout??(0,u.resolveButtonsLayoutTheme)(Ve);return we?{...a,...we,cardButton:{...a.cardButton,...we.cardButton},cardFormContainer:{...a.cardFormContainer,...we.cardFormContainer},backButton:{...a.backButton,...we.backButton},backButtonIcon:{...a.backButtonIcon,...we.backButtonIcon},submitButton:{...a.submitButton,...we.submitButton},title:{...a.title,...we.title}}:a},[j,Ve,we]),V=wt??j?.appearance,He=(0,s.useMemo)(()=>ia({appearance:V,buttonsStyles:v,layout:G}),[V,v,G]),Qt=ze.inlineSessionPatchProcessing??!1,lt=(w??Kt)||Qt,ct=ue.replace(/\/+$/,""),me=(0,s.useMemo)(()=>Da({userId:o,email:r,firstName:y,lastName:f,country:x,zip:Y},Zt),[o,r,y,f,x,Y,Zt]),Pe=[me.firstName,me.lastName].filter(a=>!!a?.trim()).join(" "),Ge=!(0,u.isValidEmail)(me.email?.trim()),De=(0,s.useRef)(null);Ie&&De.current===null&&(De.current=Ge);let _e=Ie&&(De.current??Ge),ht=(0,s.useMemo)(()=>Xl(tt,_e),[tt,_e]),Wt=ht.empty||ht.malformed,xe=(0,s.useMemo)(()=>le?le.getRawProvider():null,[le]),fn=(0,s.useMemo)(()=>rt?rt.getRawProvider():null,[rt]),An=z||100,Nr=We.toLowerCase(),va=(0,s.useMemo)(()=>V?(0,vr.toStripeAppearance)(V):null,[V]),Or=va,ii=(0,s.useMemo)(()=>{let a=va??{},b=a.rules??{};return{...a,rules:{...b,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...b[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...b[".AccordionItemContents"]??{}}}}},[va]),si=(0,s.useMemo)(()=>({...Vi(z,k?.captureMethod),currency:Nr,...Or?{appearance:Or}:null}),[z,Nr,k?.captureMethod,Or]),li=(0,s.useMemo)(()=>({mode:"payment",amount:An,currency:Nr,captureMethod:"manual",setupFutureUsage:"off_session",...Or?{appearance:Or}:null}),[An,Nr,Or]),fe=(0,s.useCallback)(a=>{Rt(a),L?.(a)},[L]),ba=(0,s.useRef)(""),[ci,zs]=(0,s.useState)(!1),Pa=(0,s.useCallback)(()=>{zs(!0)},[]);(0,s.useEffect)(()=>{if(!Ie||!_e||!m||!ci||Wt||ba.current)return;let a=vn({email:(0,u.isValidEmail)(me.email?.trim())?me.email?.trim():_n.current.trim(),firstName:me.firstName?.trim(),lastName:me.lastName?.trim()});ba.current=JSON.stringify(a),nn(b=>({...b,...a})),Promise.resolve(m(a)).catch(b=>{ba.current="",fe(b instanceof Error?b.message:"Failed to attach buyer details.")})},[Ie,_e,m,ci,Wt,me.email,me.firstName,me.lastName,fe]),(0,s.useEffect)(()=>{!Ie||!Bt||Bt.setCardFieldOrder?.(Q??null,ce==null&&!_e)},[Ie,Bt,Q,ce,_e]),(0,s.useEffect)(()=>{(Ue==="expanding"||Ue==="collapsing"||Ue==="apm-expanding"||Ue==="apm-collapsing")&&fe(null)},[Ue,fe]);let Wn=(0,s.useCallback)((a,b,K)=>{c?.(Vt(a,b,K))},[c]),zr=(0,s.useCallback)((a,b,K)=>{let Le=K?.popupBlocked??Sr(b),H=Wl(a,Le),Ce=Br(K?.code)??yr(b)??"external_payment_method_failed",Re=new u.FloPayError(H,"api_error",{code:"external_payment_method_failed",param:a});Z(null),G==="buttons"&&(cn("buttons"),cr(null)),fe(H),d?.(Re),console.error("[FloPay] External payment method failed:",{method:a,code:Ce,popupBlocked:Le})},[G,d,fe]);(0,s.useEffect)(()=>{if(!Ie||!e){Hn(null);return}let a=$a(k?.vault);if(a){Hn(a);return}if(!Tn){Hn(null);return}Hn(null);let b=!0;return new vr.PaymentAPI(ct).getVaultCapture(e,t).then(K=>{if(!b)return;let Le=$a(K);Le?Hn(Le):fe("Failed to load the secure card form.")}).catch(K=>{b&&fe(K instanceof Error?K.message:"Failed to load the secure card form.")}),()=>{b=!1}},[Ie,Tn,Te,e,k?.vault,ct,t,fe]);let nr=(0,s.useRef)({onComplete:i,onError:d,updateError:fe,emitDecline:Wn,resolvedAccount:me,avsConfig:ce,avsCheckProp:Ye,sessionId:e,nonce:t,baseUrl:ct,captureMethod:k?.captureMethod,paymentId:k?.paymentId,authorizationExpiresAt:k?.authorizationExpiresAt});nr.current={onComplete:i,onError:d,updateError:fe,emitDecline:Wn,resolvedAccount:me,avsConfig:ce,avsCheckProp:Ye,sessionId:e,nonce:t,baseUrl:ct,captureMethod:k?.captureMethod,paymentId:k?.paymentId,authorizationExpiresAt:k?.authorizationExpiresAt};let Ca=(0,s.useRef)(!1),di=(0,s.useCallback)(()=>{let a=nr.current,b=a.resolvedAccount.email?.trim(),K=(0,u.isValidEmail)(b)?b:_n.current.trim();if(!(0,u.isValidEmail)(K))return null;let Le=a.resolvedAccount.firstName?.trim(),H=a.resolvedAccount.lastName?.trim(),Ce=$t.current||a.resolvedAccount.country||"US",Re=a.avsConfig?(0,u.isAVSFieldVisible)(a.avsConfig.state,Ce):!1,Pt=a.avsConfig?(0,u.isAVSFieldVisible)(a.avsConfig.address_line_1,Ce):!1,Tt=a.avsConfig?(0,u.isAVSFieldVisible)(a.avsConfig.postal_code,Ce):!1,xt=a.avsConfig?(0,u.isAVSFieldVisible)(a.avsConfig.city,Ce):!1,jt=a.avsConfig?(0,u.isAVSFieldVisible)(a.avsConfig.address_line_2,Ce):!1,Ct=Pt&&!Re&&Tt?(0,u.getStateFromPostalCode)(Ce,(zt.current??"").trim()):null,pr=Re?on.current:Ct;return{accountData:{userId:a.resolvedAccount.userId??"",email:K,...Le?{firstName:Le}:{},...H?{lastName:H}:{},...Tt&&zt.current?{zip:zt.current}:{},...xt&&Un.current?{city:Un.current}:{},...pr?{state:pr}:{},...Pt&&Pn.current?{addressLine1:Pn.current}:{},...jt&&rn.current?{addressLine2:rn.current}:{},country:Ce},...a.avsCheckProp===void 0?{}:{avsCheck:a.avsCheckProp},...a.avsConfig?{avsConfig:{country:(0,u.isAVSFieldVisible)(a.avsConfig.country,Ce),postal_code:Tt,address_line_1:Pt,address_line_2:jt,city:xt,state:Re}}:{}}},[]),ui=(0,s.useRef)(ee);ui.current=ee,(0,s.useEffect)(()=>{ee||A!==ps||nr.current.updateError(null)},[ee,A]),(0,s.useEffect)(()=>{!Ie||!Bt||Bt.setSubmitGate?.(Rr||ee||Wt)},[Ie,Bt,Rr,ee,Wt]),(0,s.useEffect)(()=>{if(!Ie||!Bt)return;Ca.current=!1;let a=!1,b=Bt.on("submitting",()=>{lr(!0),R.current&&clearTimeout(R.current),B.current="validation-window",R.current=setTimeout(()=>{R.current=null,B.current==="validation-window"&&(B.current="processing")},Ol),Z("processing");let Re=nr.current;if(!Re.sessionId||!Re.nonce)return;let Pt=di();if(!Pt){Re.updateError("Enter a valid email address."),B.current="idle",Z(null);return}new vr.PaymentAPI(Re.baseUrl).patchAccountSnapshot(Re.sessionId,Re.nonce,Pt,{telemetryMode:"best_effort"}).catch(Tt=>{if(!zl(Tt))return;let xt=Tt instanceof Error?Tt.message:"Please check your billing address and try again.";Re.updateError(xt),B.current="idle",Z(null),Re.onError?.(Tt instanceof u.FloPayError?Tt:new u.FloPayError(xt,"api_error"))})}),K=Bt.on("complete",async Re=>{if(to(Re.sessionId??nr.current.sessionId),B.current="terminal",Z("success"),await new Promise(xt=>setTimeout(xt,1200)),Ca.current)return;Ca.current=!0;let Pt=nr.current,Tt=(0,u.isAuthorizationOnlySession)(Pt)||Re.outcome==="authorized";nr.current.onComplete?.(Tt?{status:"authorized",paymentIntentId:Re.intentId,paymentId:Re.paymentId??Pt.paymentId,sessionId:Re.sessionId??Pt.sessionId,authorizationExpiresAt:Re.authorizationExpiresAt??Pt.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",paymentIntentId:Re.intentId,checkoutMethod:"card"})}),Le=Bt.on("decline",async Re=>{let Pt=nr.current,Tt=Re.message??"Your payment was declined. Please try another card or contact your bank.";B.current="terminal",Pt.updateError(Tt),Z("error");let xt=Re.failureOutcome??(0,u.normalizeCheckoutFailureOutcome)(Re.declineReason)??"authorization_declined";Pt.emitDecline("card",Tt,{code:xt,declineCode:xt}),await new Promise(jt=>setTimeout(jt,1500)),!a&&(B.current="idle",Z(null))}),H=Bt.on("error",async Re=>{let Pt=nr.current,Tt=Re.message??"There was a problem processing your payment. Please try again.";B.current="terminal",Pt.updateError(Tt),Z("error"),Pt.onError?.(new u.FloPayError(Tt,"api_error",{code:Re.failureOutcome??"capture_failed"})),await new Promise(xt=>setTimeout(xt,1500)),!a&&(B.current="idle",Z(null))}),Ce=Bt.on("blocked",()=>{if(!ui.current){lr(!0);return}Pa(),nr.current.updateError(ps)});return()=>{a=!0,R.current&&(clearTimeout(R.current),R.current=null),B.current="idle",b(),K(),Le(),H(),Ce()}},[Ie,Bt,Pa,di]);let rr=!!ye?.clientId,io=Array.isArray(P),No=io&&P.length>0,Us=io&&P.includes("paypal"),{expressMethods:Oo,paymentElementMethods:so}=(0,s.useMemo)(()=>(0,u.partitionStripeMethods)(P,{excludePaypal:rr}),[P,rr]),pi=rr||!!rt,qs=(0,s.useMemo)(()=>pi?Oo.filter(a=>a!=="paypal"):Oo,[Oo,pi]),$s=(0,s.useMemo)(()=>{let a=[];return O&&a.push("apple_pay"),de&&a.push("google_pay"),a},[O,de]),Ur=io?qs:$s,js=q&&Ur.length>0,Sa=Cn?it:x,zo=(0,s.useMemo)(()=>{let a=Sa?.trim().toUpperCase();return a?ie?so.filter(b=>{let K=ie[b];return!K||K.length===0||K.includes(a)}):(0,u.filterStripeMethodsByCountry)(so,Sa):so},[so,Sa,ie]),wa=(0,s.useMemo)(()=>({mode:"payment",amount:An,currency:Nr,paymentMethodCreation:"manual",appearance:ii}),[An,Nr,ii]),[mi,yi]=(0,s.useState)("loading"),[fi,gi]=(0,s.useState)("loading"),[hi,vi]=(0,s.useState)("loading"),[Vs,ka]=(0,s.useState)(!1),[bi,Ia]=(0,s.useState)("loading"),[Uo,Ks]=(0,s.useState)();(0,s.useEffect)(()=>{Ks(ls())},[]);let Pi=he&&(rr||(io?Us:Uo===!1)),Ci=q&&js,lo=!Ze&&Pi&&rr,Si=bi==="retrying"||bi==="exhausted",co=!Ze&&Pi&&!!fn&&(!rr||Si),qr=!Ze&&Ci&&!!xe,uo=!Ze&&q&&No&&zo.length>0&&!!xe,Hs=lo&&!Si?Vs:co&&hs(mi),Ys=qr&&hs(fi),Ws=uo&&hi!=="load_error",wi=a=>a==="loading"||a==="ready",ki=lo||co&&wi(mi)||qr&&wi(fi)||uo&&hi!=="load_error",qo=(0,s.useRef)(!1);(0,s.useEffect)(()=>{if(!qo.current){if(!q&&!he){qo.current=!0;let a=new u.FloPayError("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");d?.(a),fe(a.message)}else if(!q&&he&&!rr&&!fn){qo.current=!0;let a=new u.FloPayError("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");d?.(a),fe(a.message)}else if(Uo!==void 0&&!Ze&&!W&&!ki){qo.current=!0;let a=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?.(a),fe(a.message)}}},[q,he,rr,fn,Uo,Ze,W,ki,d,fe]);let Ii=(0,s.useRef)(!1);(0,s.useEffect)(()=>{if(Ii.current||!No)return;let a=[];O!==!0&&a.push("showApplePay"),de!==!0&&a.push("showGooglePay"),a.length!==0&&(Ii.current=!0,console.warn(`[FloPay] ${a.join(" / ")} ${a.length===1?"is":"are"} deprecated: the Apple Pay / Google Pay surface is now driven by \`gateways.stripe.enabledPaymentMethods\` on the session response. Remove the legacy prop(s) to silence this warning.`))},[No,O,de]);let Ri=(0,s.useCallback)((a,b)=>ze.applyInlineSessionPatch?ze.applyInlineSessionPatch(a).then(K=>({error:null,sessionId:K.sessionId||e,nonce:K.session?.clientSecret||t})).catch(K=>{let Le=gs(b,K);return fe(Le.message),d?.(Le),{error:Le,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[ze.applyInlineSessionPatch,t,d,e,fe]),Gn=(0,s.useCallback)(async a=>{if(!D)return{proceed:!0};try{let b=await D({method:a,sessionId:e||void 0,createSession:ze.inlineSessionDraft});if(b===!1)return{proceed:!1};if(b&&typeof b=="object"){b.account&&nn(Le=>({...Le??{},...b.account}));let K=await Ri(b,a);return K.error?{proceed:!1,accountPatch:b.account}:{proceed:!0,accountPatch:b.account,sessionId:K.sessionId,nonce:K.nonce}}return{proceed:!0}}catch(b){let K=gs(a,b);return fe(K.message),d?.(K),{proceed:!1}}},[Ri,ze.inlineSessionDraft,D,d,e,fe]),Ei=(0,s.useCallback)(async(a,b)=>{if(J.current)return;J.current=!0,M(!0),Z("processing"),fe(null);let K=b?.sessionId??e,Le=b?.nonce??t,H=Da(me,b?.accountPatch),Ce=b?.completionPaymentMethodId??Po(a),Re=a.originalPaymentMethodId?{...a,originalPaymentMethodId:void 0}:a,Pt=Vl(a),Tt=()=>{Xe?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"process_payment",provider:Pt})};try{let jt=await new vr.PaymentAPI(ct).processPayment(H.userId??"",{sessionId:K,nonce:Le,paymentMethodCategory:b?.paymentMethodCategory??Hl(a),tokenizedData:Re,accountData:{...b?.accountPatch,userId:H.userId??"",email:H.email??"",...H.firstName?{firstName:H.firstName}:{},...H.lastName?{lastName:H.lastName}:{},...ce?(()=>{let ut=$t.current,Fn=(0,u.isAVSFieldVisible)(ce.state,ut),dn=(0,u.isAVSFieldVisible)(ce.address_line_1,ut),Mt=(0,u.isAVSFieldVisible)(ce.postal_code,ut),xr=dn&&!Fn&&Mt?(0,u.getStateFromPostalCode)(ut,(zt.current??"").trim()):null,ho=Fn?on.current:xr;return{country:ut,...Mt&&zt.current?{zip:zt.current}:{},...(0,u.isAVSFieldVisible)(ce.city,ut)&&Un.current?{city:Un.current}:{},...ho?{state:ho}:{},...dn&&Pn.current?{addressLine1:Pn.current}:{},...(0,u.isAVSFieldVisible)(ce.address_line_2,ut)&&rn.current?{addressLine2:rn.current}:{}}})():{}},chv:g,avsCheck:Ye??!1,checkoutType:oe,checkoutLayout:$,avsConfig:ce?{country:(0,u.isAVSFieldVisible)(ce.country,$t.current),postal_code:(0,u.isAVSFieldVisible)(ce.postal_code,$t.current),address_line_1:(0,u.isAVSFieldVisible)(ce.address_line_1,$t.current),address_line_2:(0,u.isAVSFieldVisible)(ce.address_line_2,$t.current),city:(0,u.isAVSFieldVisible)(ce.city,$t.current),state:(0,u.isAVSFieldVisible)(ce.state,$t.current)}:void 0});if(jt.ok){let ut=jt.status===204?null:await jt.json().catch(()=>null),Fn=(0,u.isAuthorizationOnlySession)(k)||ut?.status==="authorized";to(K),Z("success"),gt(null),await new Promise(xr=>setTimeout(xr,1200));let dn;typeof ut?.paymentId=="string"?dn=ut.paymentId:k?.paymentId&&(dn=k.paymentId);let Mt;typeof ut?.authorizationExpiresAt=="string"?Mt=ut.authorizationExpiresAt:k?.authorizationExpiresAt&&(Mt=k.authorizationExpiresAt),i?.(Fn?{status:"authorized",...dn===void 0?{}:{paymentId:dn},sessionId:typeof ut?.sessionId=="string"?ut.sessionId:K,...Mt===void 0?{}:{authorizationExpiresAt:Mt},paymentIntentId:a.threeDSecureActionResultTokenId,paymentMethodId:Ce,checkoutMethod:a.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:a.threeDSecureActionResultTokenId,paymentMethodId:Ce,checkoutMethod:a.isPaypal?"paypal":"card"});return}let Ct=await jt.json().catch(()=>null);if(Ct?.type==="paypal_redirect_required"){let ut=Ct.threeDSecureToken,Fn=Ct.paymentMethodId||a.id||"";if(!le||!ut){Z("error"),fe("PayPal authorization required but no token provided.");return}try{let dn=rt?.getRawProvider();if(!dn){fe("PayPal is not available.");return}let Mt={return_url:window.location.href};Fn&&(Mt.payment_method=Fn);let{error:xr}=await dn.confirmPayment({clientSecret:ut,confirmParams:Mt,redirect:"if_required"});if(xr){Z("error");let ho=xr.message??"PayPal payment failed.";fe(ho),Wn("paypal",ho,{code:xr.code})}}catch(dn){Z("error"),fe(dn instanceof Error?dn.message:"PayPal authorization failed.")}return}if(Ct?.type==="paypal_direct_required"){let ut=Ct.orderId;if(!ut){Z("error"),fe("PayPal retry required but no order id provided.");return}let Fn=et.current?.attempts??0;if(Fn>=2){Z("error"),fe("PayPal payment could not be completed after multiple attempts."),Wn("paypal","paypal_direct_required retry limit exceeded");return}ka(!1),Ia("loading"),gt({orderId:ut,attempts:Fn+1}),Z(null);return}(0,u.classifyPaymentRejection)(jt.status,Ct)||Tt(),Z("error");let pr=Ct?.message??"Payment failed. Please try again.";fe(pr),Wn(a.isPaypal?"paypal":"card",pr,{code:Ct?.code??Ct?.gatewayErrorCode,declineCode:Ct?.declineCode??Ct?.gatewayDeclineReason}),await new Promise(ut=>setTimeout(ut,1500))}catch(xt){Ss(xt)||Tt(),Z("error"),fe(xt instanceof Error?xt.message:"An unexpected error occurred"),await new Promise(jt=>setTimeout(jt,1500))}finally{M(!1),Z(null),J.current=!1}},[ct,e,t,me,ce,Ye,oe,$,g,le,rt,k,i,fe,Wn,Xe]),gn=(0,s.useCallback)((a,b)=>{h?h(a):Ei(a,b)},[h,Ei]),po=`${Cs}:${e}`;(0,s.useEffect)(()=>{if(typeof window>"u")return;let a=localStorage.getItem(po);if(!a)return;let b;try{b=JSON.parse(a)}catch{localStorage.removeItem(po);return}if(!b||typeof b.createdAt!="number"||Date.now()-b.createdAt<0||Date.now()-b.createdAt>Dl||typeof b.paymentMethodId!="string"||typeof b.providerIntentId!="string"||typeof b.paymentMethodType!="string"||b.sessionId!==e||!t||b.nonce!==t||!Ur.includes(b.paymentMethodType)){localStorage.removeItem(po);return}localStorage.removeItem(po),gn({id:b.paymentMethodId,type:"card",threeDSecureActionResultTokenId:b.providerIntentId,gateway:"stripe",paymentMethodType:b.paymentMethodType},{...b.accountPatch?{accountPatch:b.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t})},[gn,t,e,po,Ur]);let _i=(0,s.useRef)(!1);(0,s.useEffect)(()=>{if(typeof window>"u"||_i.current)return;let a=new URLSearchParams(window.location.search),b=a.get("payment_intent"),K=a.get("payment_intent_client_secret"),Le=a.get("redirect_status");if(!b||!K)return;let H=jt=>{let Ct=localStorage.getItem(jt);if(!Ct)return null;try{return JSON.parse(Ct)}catch{return localStorage.removeItem(jt),null}},Ce=H(ar)??H(us),Re;if(Ce?.clientSecret){if(Ce.clientSecret!==K)return;Re={...Ce.accountPatch?{accountPatch:Ce.accountPatch}:{},...Ce.sessionId?{sessionId:Ce.sessionId}:{},...Ce.nonce?{nonce:Ce.nonce}:{}}}else if(Ce?.sessionId&&Ce.sessionId!==e)return;_i.current=!0,localStorage.removeItem(ar),localStorage.removeItem(us);let Pt=new URL(window.location.href);Pt.searchParams.delete("payment_intent"),Pt.searchParams.delete("payment_intent_client_secret"),Pt.searchParams.delete("redirect_status"),window.history.replaceState({},"",Pt.toString());let Tt=Ce?.paymentMethodType??Ce?.tokenType??"card",xt="card";(async()=>{let jt=le?.getRawProvider();if(!jt){let Mt="Payment is not available \u2014 please refresh and try again.";fe(Mt),Wn(xt,Mt);return}if(Le==="failed"){let Mt="Payment was declined. Please try again.";fe(Mt),Wn(xt,Mt);return}let{paymentIntent:Ct,error:pr}=await jt.retrievePaymentIntent(K);if(pr){let Mt=pr.message??"Failed to retrieve payment status.";fe(Mt),Wn(xt,Mt,{code:pr.code});return}let ut=Ct?.status,Fn=bo(ut);if(!Ct||!Fn){let Mt=ut==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";fe(Mt),Wn(xt,Mt,{code:ut??"missing_payment_intent"});return}let dn=typeof Ct.payment_method=="string"?Ct.payment_method:Ct.payment_method?.id;gn({id:dn??Ce?.paymentMethodId??Ce?.tokenId??Ct.id,type:"card",threeDSecureActionResultTokenId:Ct.id,gateway:Ce?.gateway??"stripe",paymentMethodType:Tt},Re)})()},[e,gn,le,fe,Wn]);let Ra=(0,s.useCallback)(a=>{a.preventDefault()},[]);if(!(le!==null))return(0,l.jsx)("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let mo=G==="buttons",hn=V?.variables,Gs=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),Ea=hn?.colorBackground,Js=Ea&&!Gs.has(Ea)?Ea:void 0,yo=v.cardInputBorder??(mo?"#e5e7eb":"#A4A4FF"),Ti=hn?.colorDanger??"#dc2626",_t=a=>Er[a]&&(wn[a]||Sn),$o=Wt&&(bt||Sn),Bn=a=>a?Ti:yo,jo=(ln.malformed||ln.empty)&&($n||Sn),Xs=Bn(jo),_a=v.cardFormContainer?.backgroundColor??Js??(mo?"white":"#EDEDFF"),$r=v.cardInputBackground??hn?.colorBackground??"white",Ta=Kr(Me),xi=Kr(Ae),jr=v.nameInput,Mi=v.cardInputFontSize??Zl(jr?.fontSize)??hn?.fontSizeBase??"16px",Ai=typeof jr?.fontFamily=="string"?jr.fontFamily:hn?.fontFamily??"Poppins, sans-serif",Bi=qa(jr?.fontWeight)??400,Zs=v.cardInputColor??(typeof jr?.color=="string"?jr.color:void 0)??hn?.colorText??"#262833",Qs=v.cardInputPlaceholderColor??"#9ca3af",Ft=hn?.borderRadius??"8px",_r=hn?.borderRadius??v.cardButton?.borderRadius??Ft,Tr=hn?.colorPrimary??"#4A49FF",el=hn?.colorPrimaryHover??ao(Tr,.12),xa=hn?.colorText??"#262833",Ma={fontSize:Mi,fontFamily:Ai,fontWeight:Bi,color:Zs,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},fo={marginTop:"0.375rem",...Ma,fontSize:"0.75rem",lineHeight:1.4,color:Ti},tl={"--flopay-input-placeholder-color":Qs,"--flopay-input-font-size":Mi,"--flopay-input-font-family":Ai,"--flopay-input-font-weight":String(Bi)},go=v.cardFormContainer??{},Aa=go.padding??(mo?"0":"1rem"),Ba=go.borderRadius??Ft,nl=Bt&&In?(0,l.jsx)(oo,{capture:Bt,html:In.html,messageToken:In.messageToken,expectedOrigin:In.expectedOrigin,theme:He,onReady:()=>{if(!_e&&!ce||typeof document>"u")return;let a=()=>{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){yn.current=!0;try{K.focus()}finally{yn.current=!1}}};Kn.current||a()},onError:a=>fe(a),onValidation:a=>{let b=B.current;(b==="idle"||b==="validation-window")&&(fe(a),a&&B.current==="validation-window"&&(R.current&&(clearTimeout(R.current),R.current=null),B.current="idle",Z(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"}),Fi=(0,l.jsxs)("div",{onFocusCapture:a=>{["INPUT","SELECT","TEXTAREA","IFRAME"].includes(a.target.tagName)&&Rn()},style:{backgroundColor:_a,borderRadius:Ba,...go,padding:Aa,...tl,display:"flex",flexDirection:"column"},children:[(0,l.jsx)("style",{children:`
30
+ `,sa=44,Ao=280,ys=`flopay-card-enter ${Ao}ms cubic-bezier(0, 0, 0.2, 1) both`,fs=`flopay-card-exit ${Ao}ms cubic-bezier(0.4, 0, 0.2, 1) both`,Vl=`flopay-buttons-enter ${Ao}ms cubic-bezier(0, 0, 0.2, 1) both`,Kl=`flopay-buttons-exit ${Ao}ms cubic-bezier(0.4, 0, 0.2, 1) both`;function Hl(e){return e.gateway==="stripe"?"stripe":e.gateway==="paypal"||e.isPaypal?"paypal":void 0}function Ga(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 Wl={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"};function Yl(e){return e.isPaypal||e.gateway==="paypal"||e.paymentMethodType==="paypal"?"paypal":e.paymentMethodType==="apple_pay"||e.paymentMethodType==="google_pay"?"wallet":e.paymentMethodType&&e.paymentMethodType!=="card"?"apm":"card"}var Is={width:"100%",minHeight:sa,margin:"0 0 0.5rem",padding:"0.75rem 0.875rem",border:"1px solid #2563eb",borderRadius:8,background:"#eff6ff",color:"#1d4ed8",fontSize:"0.95rem",fontWeight:700,cursor:"pointer"};function Gl(e){switch(e){case"paypal":return"PayPal";case"apple_pay":return"Apple Pay";case"google_pay":return"Google Pay";default:return"Card"}}function gs(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function Ha(e){return e==="paypal"?"PayPal":(0,u.getStripeMethodDisplayName)(e)}function Jl(e,t){let n=`We couldn't open ${Ha(e)}. Try again or choose another payment method.`;return t?`${n} Allow pop-ups for this site, then try again.`:n}function Xl(e){let t=(0,u.getPostalCodeExample)(e);return`Enter a valid ${(0,u.getPostalCodeLabel)(e)}${t?` (e.g. ${t})`:""}`}function Zl(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 Ql(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 hs(e,t){return t instanceof u.FloPayError?t:new u.FloPayError(t instanceof Error?t.message:`${Gl(e)} before-click hook failed.`,"validation_error")}function Ka(){return(0,l.jsx)("style",{children:jl})}function ec(e){return typeof e=="number"?`${e}px`:e}function Rs(e,t){let n=e.availablePaymentMethods;return n&&t.some(r=>n[r])?"ready":"unavailable"}function Es({state:e,placeholderTestId:t,borderRadius:n=8,children:r}){return e==="unavailable"||e==="load_error"?null:(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 vs(e){return e!=="unavailable"&&e!=="load_error"}function da(e){return(0,l.jsx)(nc,{...e})}function bs({sessionId:e,nonce:t,email:n,billingApiUrl:r,onTokenizedBody:o,onErrorChange:i,isProcessing:d=!1,onButtonClick:c,onDecline:v,onTechnicalFailure:y,runBeforeButtonClick:f,billingName:g,onBuyerIdentityReady:p,onLoadStateChange:I,placeholderBorderRadius:F}){let N=vr(),{emitInstrument:ge}=(0,s.useContext)(qn),V=(0,$t.useStripe)(),S=(0,$t.useElements)(),[se,q]=(0,s.useState)("loading");(0,s.useEffect)(()=>{I?.(se)},[se,I]);let[de,G]=(0,s.useState)(!1),he=!(0,u.isValidEmail)(n?.trim())||!g?.trim(),{request:Ke,collect:Se,finish:Rt}=Jr(),$e=(0,s.useRef)(!1),Ae=(0,s.useRef)(null),Be=(0,s.useRef)(null),[le,ae]=(0,s.useState)(0),[D,Fe]=(0,s.useState)(!1),De=(0,s.useRef)(!1),te=(0,s.useRef)(new Map),{startAttempt:Re,finishAttempt:ve,invalidateAttempt:x,isAttemptInvalidated:Q,isAttemptCurrent:we}=ko((ie,Y,$)=>{y?.(ie,Y,{...$,popupBlocked:$?.popupBlocked??kr(Y)}),Fe(!0),ae(Ue=>Ue+1)});(0,s.useEffect)(()=>{D&&Be.current?.focus()},[D,le]);let ue=(0,s.useCallback)(()=>{ae(ie=>ie+1)},[]),ce=(0,s.useCallback)((ie,Y,$)=>{x($),y?.("paypal",ie,{code:Y,popupBlocked:kr(ie)}),Fe(!0),ue()},[x,y,ue]),ze=(0,s.useCallback)(()=>{window.setTimeout(()=>{(Ae.current?.querySelector("iframe")??Ae.current)?.focus()},0)},[]);(0,s.useEffect)(()=>{De.current&&(De.current=!1,ze())},[ze,le]);let rt=(0,s.useCallback)(()=>{Fe(!1),i?.(null),ze()},[ze,i]);(0,s.useEffect)(()=>{if(!V||$e.current)return;let ie=new URLSearchParams(window.location.search),Y=ie.get("payment_intent"),$=ie.get("payment_intent_client_secret"),Ue=ie.get("redirect_status");if(!Y||!$)return;$e.current=!0;let Qe;try{let ot=localStorage.getItem(Mo);if(ot){let ne=JSON.parse(ot);ne.clientSecret===$&&(Qe={...ne.accountPatch?{accountPatch:ne.accountPatch}:{},...ne.sessionId?{sessionId:ne.sessionId}:{},...ne.nonce?{nonce:ne.nonce}:{}})}}catch{}try{localStorage.removeItem(Mo)}catch{}let ye=new URL(window.location.href);ye.searchParams.delete("payment_intent"),ye.searchParams.delete("payment_intent_client_secret"),ye.searchParams.delete("redirect_status"),window.history.replaceState({},"",ye.toString()),(async()=>{try{if(G(!0),Ue==="failed"){let h="PayPal payment was declined. Please try again.";i?.(h),v?.(Qt("paypal",h));return}let{paymentIntent:ot,error:ne}=await V.retrievePaymentIntent($);if(ne){i?.(ne.message??"Failed to retrieve PayPal payment status.");return}if(ot&&(ot.status==="requires_capture"||ot.status==="succeeded")){let h=typeof ot.payment_method=="string"?ot.payment_method:ot.payment_method?.id;o({id:h??ot.id,type:"card",threeDSecureActionResultTokenId:ot.id,isPaypal:!0},Qe)}else{let h="PayPal payment was not completed. Please try again.";i?.(h),v?.(Qt("paypal",h))}}catch(ot){i?.(ot instanceof Error?ot.message:"Failed to complete PayPal payment.")}finally{G(!1)}})()},[V,o,i,v]);let gt=(0,s.useCallback)(async ie=>{if(d||de){ie.reject();return}let Y=f?await f("paypal"):{proceed:!0};if(!Y.proceed){te.current.delete(le),ie.reject();return}let $=Re("paypal");te.current.set(le,{generation:$,accountPatch:Y.accountPatch,sessionId:Y.sessionId,nonce:Y.nonce}),Fe(!1),c?.("paypal"),ie.resolve()},[d,c,f,Re,de,le]),Ge=(0,s.useCallback)(async ie=>{if(!V||!S)return;let Y=te.current.get(le);if(Y&&!we(Y.generation)){te.current.delete(le);return}if(!Y&&Q()||Y&&!ve(Y.generation))return;Y||ve();let $=Y??null;if(te.current.delete(le),!$&&f){let h=await f("paypal");if(!h.proceed){ie.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}$={accountPatch:h.accountPatch,sessionId:h.sessionId,nonce:h.nonce}}let Ue=$?.sessionId??e,Qe=$?.nonce??t,ye=await $l({event:ie,prepared:$,email:n,billingName:g,methodLabel:"PayPal",collect:Se});if(!ye){ie.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let ot=ye.email,ne={...$?.accountPatch,...kn(ye,!0)};try{if(G(!0),i?.(null),!Ue||!(0,u.isValidEmail)(ot))throw new Error("Missing sessionId or email for PayPal payment");await p?.(ye);let h=V.createPaymentMethod,{error:tt,paymentMethod:Ee}=await h({type:"paypal"});if(tt){ce(tt,"stripe_paypal_create_payment_method_failed",Y?.generation),ie.paymentFailed({reason:"fail"});return}let O=await la(r,ge,Ue,Qe??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:Ee?.id??null,intentKind:"payment"});if(O.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let Le=O.clientSecret,xe={return_url:window.location.href};if(Ee?.id&&(xe.payment_method=Ee.id),typeof window<"u")try{localStorage.setItem(Mo,JSON.stringify({clientSecret:Le,sessionId:Ue,nonce:Qe,accountPatch:ne}))}catch{}let{error:pt,paymentIntent:mt}=await V.confirmPayment({clientSecret:Le,confirmParams:xe,redirect:"if_required"});if(pt){if(typeof window<"u")try{localStorage.removeItem(Mo)}catch{}if(Po(pt)){let A=pt.message??"Your payment was declined.";i?.(A),v?.(Qt("paypal",A,{code:hr(pt),declineCode:Zr(pt)})),await ca({billingApiUrl:r,sessionId:Ue,nonce:Qe,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:hr(pt)??"provider_declined"}})}else ce(pt,"stripe_paypal_confirm_failed",Y?.generation);return}if(typeof window<"u")try{localStorage.removeItem(Mo)}catch{}let R=typeof mt?.payment_method=="string"?mt.payment_method:mt?.payment_method?.id;o({id:R??mt?.id,type:"card",threeDSecureActionResultTokenId:mt?.id,isPaypal:!0},{accountPatch:ne,paymentMethodCategory:"paypal",sessionId:Ue,nonce:Qe});return}catch(h){ce(h,"stripe_paypal_failed",Y?.generation)}finally{G(!1)}},[V,S,e,t,n,g,Se,p,r,ge,o,i,v,f,ce,ve,we,Q,le]);return(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(Es,{state:se,placeholderTestId:"flopay-paypal-placeholder",borderRadius:F,children:(0,l.jsxs)("div",{ref:Ae,tabIndex:-1,"data-testid":"flopay-paypal-focus-target",role:"group","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[D&&(0,l.jsx)("button",{ref:Be,type:"button","data-testid":"flopay-paypal-retry-button",onClick:rt,style:Is,children:"Try PayPal again"}),Ke&&(0,l.jsx)(Xr,{identity:Ke.identity,methodLabel:Ke.methodLabel,onComplete:Rt,onCancel:()=>Rt(null)},Ke.id),(0,l.jsx)("div",{style:{display:Ke?"none":void 0},children:(0,l.jsx)($t.ExpressCheckoutElement,{onReady:ie=>q(Rs(ie,["paypal"])),onLoadError:()=>{q("load_error"),Ya(Wt(N),"paypal","paypal")},onClick:gt,onConfirm:Ge,onCancel:()=>{let ie=te.current.get(le);te.current.delete(le),Wt(N)?.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),x(ie?.generation),Fe(!1),De.current=!0,ue()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:he,emailRequired:he,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},le)})]})}),de&&(0,l.jsx)(jn,{status:"processing"})]})}function Cs({sessionId:e,nonce:t,email:n,billingApiUrl:r,intentKind:o,expressMethods:i,onTokenizedBody:d,onErrorChange:c,onButtonClick:v,onDecline:y,onTechnicalFailure:f,runBeforeButtonClick:g,billingName:p,onBuyerIdentityReady:I,onLoadStateChange:F,placeholderBorderRadius:N}){let ge=vr(),{emitInstrument:V}=(0,s.useContext)(qn),S=(0,$t.useStripe)(),se=(0,$t.useElements)(),[q,de]=(0,s.useState)("loading");(0,s.useEffect)(()=>{F?.(q)},[q,F]);let[G,he]=(0,s.useState)(!1),Ke=(0,s.useRef)(!(0,u.isValidEmail)(n?.trim())||!p?.trim()).current,{request:Se,collect:Rt,finish:$e}=Jr(),Ae=(0,s.useRef)(null),Be=(0,s.useRef)(null),[le,ae]=(0,s.useState)(0),[D,Fe]=(0,s.useState)(!1),[De,te]=(0,s.useState)("google_pay"),Re=(0,s.useRef)(!1),ve=(0,s.useRef)("google_pay"),x=(0,s.useRef)("google_pay"),Q=(0,s.useRef)(null),we=(0,s.useRef)(new Set);(0,s.useEffect)(()=>()=>{for(let h of we.current)window.clearTimeout(h);we.current.clear()},[]);let ue=(0,s.useRef)(new Map),{startAttempt:ce,finishAttempt:ze,invalidateAttempt:rt,isAttemptInvalidated:gt,isAttemptCurrent:Ge,generationRef:ie}=ko((h,tt,Ee)=>{f?.(h,tt,{...Ee,popupBlocked:Ee?.popupBlocked??kr(tt)}),te(h),Fe(!0),ae(O=>O+1)});(0,s.useEffect)(()=>{D&&Be.current?.focus()},[D,le]);let Y=(0,s.useCallback)(()=>{ae(h=>h+1)},[]),$=(0,s.useCallback)((h,tt,Ee,O)=>{rt(O),f?.(h,tt,{code:Ee,popupBlocked:kr(tt)}),te(h),Fe(!0),Y()},[rt,f,Y]),Ue=(0,s.useCallback)(()=>{window.setTimeout(()=>{(Ae.current?.querySelector("iframe")??Ae.current)?.focus()},0)},[]);(0,s.useEffect)(()=>{Re.current&&(Re.current=!1,Ue())},[Ue,le]);let Qe=(0,s.useCallback)(()=>{Fe(!1),c?.(null),Ue()},[Ue,c]),ye=(0,s.useCallback)(async h=>{let tt=!1,Ee=He=>{tt||(tt=!0,h.paymentFailed({reason:"fail",...He?{message:He}:{}}))};if(!S||!se){Ee();return}let O=ue.current.get(le);if(O&&!Ge(O.generation)){ue.current.delete(le),Ee();return}if(!O&&gt()){Ee();return}if(O&&!ze(O.generation)){Ee();return}O||ze();let Le=h.expressPaymentType??O?.method??ve.current,xe=O??null,pt=gs(Le),mt;Le==="apple_pay"?mt="apple_pay":Le==="google_pay"&&(mt="google_pay");let R=O?.generation??ie.current,A=Wt(ge),ht=A?.now()??globalThis.performance?.now()??Date.now(),Je=new AbortController,Yt=!1,fn=!1,L=null,jt=e,Gt="processing",lt="other",Lt="provider_runtime",gn,In=new Promise((He,yt)=>{gn=yt}),hn=window.setTimeout(()=>{Yt=!0,Je.abort(),gn($a)},Ol),Nt=async(He,yt,Ct)=>{Gt=He,lt=yt,Lt=yt==="intent_create"?"transport_error":"provider_runtime";let on=A?.now()??globalThis.performance?.now()??Date.now();try{return await Promise.race([Ct,In])}finally{let ct=A?.now()??globalThis.performance?.now()??Date.now();A?.performance({stage:He,durationMs:Math.max(0,ct-on),durationMode:"machine",requestCategory:yt,paymentMethodCategory:"wallet",provider:"stripe",...Yt?{statusClass:"timeout"}:{}})}};try{if(he(!0),c?.(null),!xe&&g){let P=await Nt("processing","other",g(pt));if(!P.proceed){Ee();return}xe={accountPatch:P.accountPatch,sessionId:P.sessionId,nonce:P.nonce}}let He=xe?.sessionId??e;jt=He;let yt=xe?.nonce??t,Ct=Q.current??xe?.accountPatch,on=ks({event:h,fallbackEmail:Ct?.email??n,fallbackName:[Ct?.firstName,Ct?.lastName].join(" ").trim()||p});if(!(0,u.isValidEmail)(on.email)){Ee("Buyer details are required."),Rt(Ha(Le),on).then(P=>{P&&(Q.current=P)});return}Q.current=null;let ct={...xe?.accountPatch,...kn(on,!0)};await Nt("processing","provider_sdk",Promise.resolve(I?.(on)));let{error:vn}=await Nt("tokenization","provider_sdk",se.submit());if(vn){Ee(),$(Le,vn,"stripe_wallet_submit_failed",O?.generation);return}if(!He)throw new Error("Missing sessionId or email for payment.");let Xe=await Nt("processing","intent_create",la(r,V,He,yt??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:Le,paymentMethodId:null,intentKind:o},{signal:Je.signal}));if(Xe.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Jt=Xe.clientSecret;window.clearTimeout(hn),fn=!0,A?.performance({stage:"callback",durationMs:Math.max(0,(A?.now()??globalThis.performance?.now()??Date.now())-ht),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe"});let bn=A?.now()??globalThis.performance?.now()??Date.now(),an={stage:"provider_confirmation",provider:"stripe",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",...mt?{walletType:mt}:{},attempt:R},Kt=!1;A?.log({name:"payment.provider_confirmation.started",...an}),L=window.setTimeout(()=>{L!==null&&we.current.delete(L),Kt=!0;let P=A?.now()??globalThis.performance?.now()??Date.now();A?.error({errorCode:"REQUEST_TIMEOUT",...an,operationOutcome:"watchdog_expired",checkoutSessionId:He,durationMs:Math.max(0,P-bn),statusClass:"timeout",failureCategory:"provider_runtime"}),A?.flush?.().catch(()=>{})},zl),we.current.add(L);let Ot=P=>{L!==null&&(window.clearTimeout(L),we.current.delete(L),L=null);let ft=A?.now()??globalThis.performance?.now()??Date.now(),Et=Math.max(0,ft-bn),_t=P;return Kt&&(P==="resolved"?_t="resolved_late":P==="returned_error"?_t="returned_error_late":_t="rejected_late"),A?.log({name:"payment.provider_confirmation.returned",...an,operationOutcome:_t}),A?.performance({...an,durationMs:Et,durationMode:"buyer",operationOutcome:_t}),{durationMs:Et,operationOutcome:_t}},en=!1,Xt=P=>{if(!P||typeof P!="object")return null;let ft=P;if(ft.error)return null;let Et=ft.setupIntent??ft.paymentIntent,_t=Et?.id,cn=Et?.status,dr=ft.setupIntent?cn==="succeeded":bo(typeof cn=="string"?cn:void 0),Fn=Et?.payment_method,z=null;return typeof Fn=="string"?z=Fn:typeof Fn?.id=="string"&&(z=Fn.id),!dr||typeof _t!="string"||!z?null:{intentId:_t,paymentMethodId:z}},Rn=P=>{if(en||O&&ie.current!==O.generation)return;let ft=Xt(P);if(!ft)return;let{intentId:Et,paymentMethodId:_t}=ft;en=!0;let cn=`${Ss}:${He}`;if(typeof window<"u")try{localStorage.setItem(cn,JSON.stringify({createdAt:Date.now(),sessionId:He,nonce:yt,accountPatch:ct,paymentMethodId:_t,providerIntentId:Et,paymentMethodType:Le}))}catch{}try{d({id:_t,type:"card",threeDSecureActionResultTokenId:Et},{accountPatch:ct,paymentMethodCategory:"wallet",sessionId:He,nonce:yt})}finally{if(typeof window<"u")try{localStorage.removeItem(cn)}catch{}}},xt,sn;try{let P=await((0,u.isSetupIntentClientSecret)(Jt)?S.confirmSetup({elements:se,clientSecret:Jt,redirect:"if_required"}):S.confirmPayment({elements:se,clientSecret:Jt,redirect:"if_required"}));if(!P||typeof P!="object"||(xt=P,!xt.error&&!Xt(xt)))throw ja;sn=Ot(xt.error?"returned_error":"resolved")}catch(P){let ft=P===ja,Et=Ot(ft?"returned_error":"rejected");throw A?.error({...ft?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response"}:Da(P),...an,operationOutcome:Et.operationOutcome,checkoutSessionId:He,durationMs:Et.durationMs,statusClass:"unknown"}),P}let Pt=xt.error;if(Pt){if(Po(Pt)){let P=Pt.message??"Your payment was declined.";Ee(P),c?.(P),y?.(Qt(pt,P,{code:hr(Pt),declineCode:Zr(Pt)})),ca({billingApiUrl:r,sessionId:He,nonce:yt,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:Le,providerDeclineReason:hr(Pt)??"provider_declined",...Xe.intentKind==="payment"&&Xe.providerObjectId.startsWith("pi_")?{providerIntentId:Xe.providerObjectId}:{}}})}else A?.error({...Da(Pt),...an,operationOutcome:sn.operationOutcome,checkoutSessionId:He,durationMs:sn.durationMs,statusClass:"unknown"}),Ee(),$(Le,Pt,"stripe_wallet_confirm_failed",O?.generation);return}if(Rn(xt),!en)throw new Error("Invalid provider returned for APM intent")}catch(He){if(He===$a){let yt=A?.now()??globalThis.performance?.now()??Date.now();A?.error({errorCode:"REQUEST_TIMEOUT",stage:Gt,requestCategory:lt,paymentMethodCategory:"wallet",provider:"stripe",...mt?{walletType:mt}:{},operationOutcome:"watchdog_expired",checkoutSessionId:jt,durationMs:Math.max(0,yt-ht),statusClass:"timeout",failureCategory:Lt,attempt:R}),A?.flush?.().catch(()=>{})}Ee(),$(Le,He,He===$a?"stripe_wallet_authorization_timeout":"stripe_wallet_failed",O?.generation)}finally{if(window.clearTimeout(hn),L!==null&&(window.clearTimeout(L),we.current.delete(L)),!fn){let He=A?.now()??globalThis.performance?.now()??Date.now();A?.performance({stage:"callback",durationMs:Math.max(0,He-ht),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe",...Yt?{statusClass:"timeout"}:{}})}he(!1)}},[S,se,e,t,n,p,Rt,I,r,V,o,d,c,y,g,$,ze,Ge,gt,ie,ge,le]),ot=(0,s.useMemo)(()=>{let h=["applePay","googlePay","paypal","link","amazonPay","klarna"],tt=new Set(["applePay","googlePay"]),Ee=new Set(i.map(u.stripeExpressMethodToOptionKey)),O={};for(let Le of h)Ee.has(Le)?O[Le]=tt.has(Le)?"always":"auto":O[Le]="never";return O},[i]),ne=(0,s.useMemo)(()=>i.map(u.stripeExpressMethodToOptionKey),[i]);return(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(Es,{state:q,placeholderTestId:"flopay-wallet-placeholder",borderRadius:N,children:(0,l.jsxs)("div",{ref:Ae,tabIndex:-1,"data-testid":"flopay-wallet-focus-target",role:"group","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[D&&(0,l.jsxs)("button",{ref:Be,type:"button","data-testid":"flopay-wallet-retry-button",onClick:Qe,style:Is,children:["Try ",Ha(De)," again"]}),Se&&(0,l.jsx)(Xr,{identity:Se.identity,methodLabel:Se.methodLabel,onComplete:$e,onCancel:()=>$e(null)},Se.id),(0,l.jsx)("div",{style:{display:Se?"none":void 0},children:(0,l.jsx)($t.ExpressCheckoutElement,{onReady:h=>{de(Rs(h,ne))},onLoadError:h=>{de("load_error"),Ya(Wt(ge),"stripe","wallet")},onClick:async h=>{ve.current=h.expressPaymentType,x.current=gs(h.expressPaymentType);let tt=!0,Ee=window.setTimeout(()=>{tt=!1,h.reject()},Nl),O=g?await g(x.current):{proceed:!0};if(window.clearTimeout(Ee),!tt)return;if(!O.proceed){ue.current.delete(le),h.reject();return}let Le=ce(h.expressPaymentType);ue.current.set(le,{generation:Le,method:h.expressPaymentType,accountPatch:O.accountPatch,sessionId:O.sessionId,nonce:O.nonce}),Fe(!1),v?.(x.current),h.resolve()},onConfirm:ye,onCancel:()=>{let h=ue.current.get(le);ue.current.delete(le),Wt(ge)?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet"}),rt(h?.generation),Fe(!1),Re.current=!0,Y()},options:{buttonType:{applePay:"plain",googlePay:"plain"},paymentMethods:ot,emailRequired:Ke,billingAddressRequired:Ke,layout:{maxColumns:1,overflow:"never"}}},le)})]})}),G&&(0,l.jsx)(jn,{status:"processing"})]})}function _s(e,t){return{...e,paymentMethodTypes:[t],...t==="revolut_pay"||t==="sepa_debit"||t==="us_bank_account"?{setupFutureUsage:"off_session"}:null}}function tc({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:f,fontFamily:g}){let p=(0,u.resolveStripeMethodBrandVariant)(e,t),I=ds[e],[F,N]=(0,s.useState)(!1),ge=!!I&&!F,V=p?.backgroundColor??c??"#ffffff",S=p?.borderColor??v??"#d1d5db",se=p?.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:sa,padding:"0 1rem",backgroundColor:V,color:se,border:`1px solid ${S}`,borderRadius:f??8,fontSize:"0.95rem",fontWeight:600,fontFamily:g,cursor:n||r?"not-allowed":"pointer",opacity:r&&!n?.55:1,animation:n?"flopay-pulse 1.5s ease-in-out infinite":void 0,display:"flex",alignItems:"center",justifyContent:"center",gap:8,transition:"transform 0.1s, opacity 140ms ease-out, border-color 140ms ease-out",boxShadow:o?"0 0 0 2px rgba(74, 73, 255, 0.15)":void 0},children:n?(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:[ge?(0,l.jsx)("img",{src:I,alt:"","aria-hidden":"true",onError:()=>N(!0),loading:"lazy",decoding:"async",width:30,height:20,style:{width:30,height:20,flexShrink:0,borderRadius:3,objectFit:"contain",display:"inline-flex"}}):null,!ge&&p?.logoSvg?(0,l.jsx)("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:p.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:se,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 Wa({method:e,sessionId:t,nonce:n,email:r,billingName:o,onBuyerIdentityReady:i,billingApiUrl:d,onTokenizedBody:c,onErrorChange:v,onDecline:y,onCancel:f,runBeforeButtonClick:g,onButtonClick:p,isProcessing:I,submitButtonColor:F,submitButtonBorderRadius:N,submitButtonStyle:ge,errorText:V}){let S=vr(),{emitInstrument:se}=(0,s.useContext)(qn),q=(0,$t.useStripe)(),de=(0,$t.useElements)(),[G,he]=(0,s.useState)(!1),Ke=(0,s.useRef)(!1),[Se,Rt]=(0,s.useState)(!1),[$e,Ae]=(0,s.useState)("loading"),[Be,le]=(0,s.useState)(""),ae=!(0,u.isValidEmail)(r?.trim()),D=!ae||(0,u.isValidEmail)(Be.trim()),Fe=(0,s.useCallback)(async()=>{if(!q||!de||I||Ke.current||!Se)return;Ke.current=!0,he(!0);let De=g?await g("card"):{proceed:!0};if(!De.proceed){Ke.current=!1,he(!1);return}p?.("card");let te=De.sessionId??t,Re=De.nonce??n,ve=Mr(o?.trim()),x=kn({email:De.accountPatch?.email?.trim()||r?.trim()||Be.trim(),firstName:De.accountPatch?.firstName?.trim()||ve.firstName,lastName:De.accountPatch?.lastName?.trim()||ve.lastName}),Q=x.email,we=kn({...De.accountPatch,...x});try{if(v?.(null),!(0,u.isValidEmail)(Q))throw new Error("A valid email address is required for payment.");await i?.(x);let ue=await de.submit();if(ue.error){v?.(ue.error.message??"Payment failed.");return}let ce=[x.firstName,x.lastName].filter(Boolean).join(" "),ze=await q.createPaymentMethod({elements:de,params:{billing_details:{email:Q,...ce?{name:ce}:{}}}});if(ze.error||!ze.paymentMethod){v?.(ze.error?.message??"Failed to create payment method.");return}let rt=ze.paymentMethod;if(!te||!Q)throw new Error("Missing sessionId or email for payment.");let gt=rt.type||e,Ge=await la(d,se,te,Re??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:gt,paymentMethodId:null,intentKind:"payment"});if(Ge.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let ie=Ge.clientSecret;if(typeof window<"u")try{localStorage.setItem(sr,JSON.stringify({clientSecret:ie,sessionId:te,nonce:Re,accountPatch:we,paymentMethodId:rt.id,paymentMethodType:rt.type??e,gateway:"stripe"}))}catch{}let{error:Y,paymentIntent:$}=await q.confirmPayment({clientSecret:ie,confirmParams:{return_url:window.location.href,payment_method:rt.id},redirect:"if_required"});if(Y){if(typeof window<"u")try{localStorage.removeItem(sr)}catch{}let ye=Y.message??"Payment failed.";v?.(ye),y?.(Qt("card",ye,{code:Y.code})),await ca({billingApiUrl:d,sessionId:te,nonce:Re,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:Y.code??"provider_declined"}});return}let Ue=$?.status;if(!bo(Ue)){if(typeof window<"u")try{localStorage.removeItem(sr)}catch{}let ye=Ue==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";v?.(ye),y?.(Qt("card",ye,{code:Ue??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(sr)}catch{}let Qe=typeof $?.payment_method=="string"?$.payment_method:$?.payment_method?.id;c({id:Qe??rt.id,type:"card",threeDSecureActionResultTokenId:$?.id,gateway:"stripe",paymentMethodType:rt.type??e},{accountPatch:we,paymentMethodCategory:"apm",sessionId:te,nonce:Re})}catch(ue){v?.(ue instanceof Error?ue.message:"Payment failed. Please try again.")}finally{Ke.current=!1,he(!1)}},[q,de,I,Se,g,p,t,n,r,o,Be,i,d,se,e,c,v,y]);return(0,l.jsxs)("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[ae&&(0,l.jsx)("div",{"data-testid":"flopay-apm-identity-fields",style:{display:"flex",flexDirection:"column",gap:"0.75rem",marginBottom:"0.75rem"},children:ae&&(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:Be,onChange:De=>le(De.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]})}),(0,l.jsx)($t.PaymentElement,{onReady:()=>Ae("ready"),onLoadError:()=>{Ae("load_error"),Ya(Wt(S),"stripe","apm")},onChange:De=>{Rt(!!De.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:()=>{Fe()},disabled:!Se||!D||G||I||$e!=="ready",style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:F,color:"white",border:"none",borderRadius:N,fontSize:"1rem",fontWeight:600,cursor:!Se||!D||G||I||$e!=="ready"?"not-allowed":"pointer",opacity:!Se||!D||G||I||$e!=="ready"?.5:1,transition:"opacity 120ms ease-out",...ge??{}},children:G?"Processing\u2026":`Pay with ${(0,u.getStripeMethodDisplayName)(e)}`}),V&&(0,l.jsx)(eo,{margin:"0.75rem 0 0",children:V})]})}function Ps({sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:i,paymentElementMethods:d,stripeInstance:c,paymentElementBaseOptions:v,onTokenizedBody:y,onErrorChange:f,onButtonClick:g,onDecline:p,runBeforeButtonClick:I,onLoadStateChange:F,isProcessing:N=!1,submitButtonColor:ge="#4A49FF",submitButtonBorderRadius:V=8,submitButtonStyle:S,buttonAppearance:se,themeId:q,onExpandApm:de,expandedApmMethod:G}){let{emitInstrument:he}=(0,s.useContext)(qn),[Ke,Se]=(0,s.useState)(null),[Rt,$e]=(0,s.useState)(null),Ae=(0,s.useRef)(!1),{request:Be,collect:le,finish:ae}=Jr();(0,s.useEffect)(()=>{d.length>0&&c?F?.("ready"):c||F?.("loading")},[d.length,c,F]);let D=(0,s.useCallback)(async x=>{if(!c||Ae.current||N)return;Ae.current=!0,$e(x);let Q=I?await I("card"):{proceed:!0};if(!Q.proceed){Ae.current=!1,$e(null);return}g?.("card");let we=Q.sessionId??e,ue=Q.nonce??t,ce=Mr([Q.accountPatch?.firstName,Q.accountPatch?.lastName].filter(Boolean).join(" ")||r),ze=kn({email:Q.accountPatch?.email?.trim()||n?.trim(),firstName:Q.accountPatch?.firstName?.trim()||ce.firstName,lastName:Q.accountPatch?.lastName?.trim()||ce.lastName});if(!(0,u.isValidEmail)(ze.email)){$e(null);let Ge=await le((0,u.getStripeMethodDisplayName)(x),ze);if(!Ge){Ae.current=!1;return}ze=Ge,$e(x)}let rt=ze.email,gt=kn({...Q.accountPatch,...ze});try{if(f?.(null),!we||!(0,u.isValidEmail)(rt))throw new Error("Missing sessionId or email for payment.");await o?.(ze);let Ge=await la(i,he,we,ue??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:x,paymentMethodId:null,intentKind:"payment"});if(Ge.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let ie=Ge.clientSecret;if(typeof window<"u")try{localStorage.setItem(sr,JSON.stringify({clientSecret:ie,sessionId:we,nonce:ue,accountPatch:gt,paymentMethodType:x,gateway:"stripe"}))}catch{}let{error:Y,paymentIntent:$}=await c.confirmPayment({clientSecret:ie,confirmParams:{return_url:window.location.href,payment_method_data:{type:x,billing_details:{name:[ze.firstName,ze.lastName].filter(Boolean).join(" "),...rt?{email:rt}:{}}}},redirect:"if_required"});if(Y){if(typeof window<"u")try{localStorage.removeItem(sr)}catch{}let ye=Y.message??"Payment failed.";f?.(ye),p?.(Qt("card",ye,{code:Y.code})),await ca({billingApiUrl:i,sessionId:we,nonce:ue,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:x,providerDeclineReason:Y.code??"provider_declined"}});return}let Ue=$?.status;if(!bo(Ue)){if(typeof window<"u")try{localStorage.removeItem(sr)}catch{}let ye=Ue==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";f?.(ye),p?.(Qt("card",ye,{code:Ue??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(sr)}catch{}let Qe=typeof $?.payment_method=="string"?$.payment_method:$?.payment_method?.id;y({id:Qe??$?.id,type:"card",threeDSecureActionResultTokenId:$?.id,gateway:"stripe",paymentMethodType:x},{accountPatch:gt,paymentMethodCategory:"apm",sessionId:we,nonce:ue})}catch(Ge){f?.(Ge instanceof Error?Ge.message:"Payment failed. Please try again.")}finally{Ae.current=!1,$e(null)}},[c,N,I,g,e,t,n,le,i,he,r,o,y,f,p]),[Fe,De]=(0,s.useState)(null),te=de?G??null:Fe,Re=(0,s.useCallback)(x=>{Ae.current||N||te&&te!==x||((0,u.needsStripeMethodExplicitConfirm)(x)?de?de(x):De(x):D(x))},[te,N,D,de]),ve=(0,s.useMemo)(()=>Fe?_s(v,Fe):null,[Fe,v]);return(0,l.jsx)("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:Be?(0,l.jsx)(Xr,{identity:Be.identity,methodLabel:Be.methodLabel,onComplete:ae,onCancel:()=>ae(null)},Be.id):d.map(x=>{let Q=G===x,we=Rt===x,ue=Rt!==null&&Rt!==x||G!=null&&G!==x;return(0,l.jsxs)(s.default.Fragment,{children:[(0,l.jsx)(tc,{method:x,themeId:q,submitting:we,disabled:ue,highlighted:Q,hasNextStep:(0,u.needsStripeMethodExplicitConfirm)(x),onClick:()=>Re(x),backgroundColor:se?.backgroundColor,borderColor:se?.borderColor,textColor:se?.textColor,borderRadius:se?.borderRadius,fontFamily:se?.fontFamily}),!de&&Fe===x&&ve&&c&&(0,l.jsx)($t.Elements,{stripe:c,options:ve,children:(0,l.jsx)(Wa,{method:x,sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:i,onTokenizedBody:y,onErrorChange:f,onDecline:p,onCancel:()=>De(null),runBeforeButtonClick:I,onButtonClick:g,isProcessing:N,submitButtonColor:ge,submitButtonBorderRadius:V,submitButtonStyle:S})},x)]},x)})})}function nc({sessionId:e,nonce:t,billingApiUrl:n,email:r,userId:o,onComplete:i,onError:d,onDecline:c,onTokenizedBody:v,firstName:y,lastName:f,chv:g,className:p,isProcessing:I,error:F,onErrorChange:N,showPayPal:ge=!0,showStripe:V=!0,enabledPaymentMethods:S,enabledPaymentMethodCountries:se,showApplePay:q=!0,showGooglePay:de=!0,layout:G="default",theme:he,buttonsTheme:Ke,buttonsStyles:Se,appearance:Rt,cardButtonContent:$e,cardBackButtonContent:Ae,cardTitleContent:Be,showSecurityFooter:le,onButtonClick:ae,onBeforeButtonClick:D,onBuyerIdentityReady:Fe,enableAVS:De,cardFieldOrder:te,cardPreFormSlot:Re,avsLayout:ve="row",country:x,zip:Q,addressLine1:we,addressLine2:ue,city:ce,state:ze,onCountryChange:rt,onZipChange:gt,avsCheck:Ge,checkoutType:ie,checkoutLayout:Y,totalAmount:$=0,currency:Ue="usd",initialCardOpen:Qe=!1,directPaypal:ye,isSubscription:ot=!1,session:ne,dataAttachmentPending:h=!1,dataAttachmentRequiresIdentity:tt=!1,debug:Ee=!1}){let O=vr(),Le=Jo(),xe=(0,s.useContext)(tr),{emitInstrument:pt}=(0,s.useContext)(qn),mt=ne??xe.session,R=mt?.gateways?.paypal?.providerObjectType??ye?.providerObjectType,A=h||xe.claimPending===!0,ht=tt||xe.claimRequiresIdentity===!0,Je=A&&!ht,Yt=Ji(),[fn,L]=(0,s.useState)(!1),[jt,Gt]=(0,s.useState)(null),[lt,Lt]=(0,s.useState)(x??"US"),[gn,In]=(0,s.useState)(Q??""),[hn,Nt]=(0,s.useState)(we??""),[He,yt]=(0,s.useState)(ue??""),[Ct,on]=(0,s.useState)(ce??""),[ct,vn]=(0,s.useState)(ze??""),[Xe,Jt]=(0,s.useState)(""),[bn,an]=(0,s.useState)({}),Kt=(0,s.useRef)(Q??""),Ot=(0,s.useRef)(x??"US"),en=(0,s.useRef)(we??""),Xt=(0,s.useRef)(ue??""),Rn=(0,s.useRef)(ce??""),xt=(0,s.useRef)(ze??""),sn=(0,s.useRef)(""),Pt=(0,s.useRef)({});(0,s.useEffect)(()=>{let a=(C,W,Oe,Z,Ce)=>{if(Pt.current[C])return;let Ie=W?.trim();!Ie||Ie===Oe.current||(Oe.current=Ie,Z(Ie),Ce?.(Ie))};a("country",x,Ot,Lt,rt),a("zip",Q,Kt,In,gt),a("addressLine1",we,en,Nt),a("addressLine2",ue,Xt,yt),a("city",ce,Rn,on),a("state",ze,xt,vn)},[x,Q,we,ue,ce,ze,rt,gt]);let P=(0,s.useMemo)(()=>(0,u.resolveAVSConfig)(De),[De]),ft=P!==null,Et=(0,s.useMemo)(()=>(0,u.isAuthorizationOnlySession)(ne),[ne]),_t=!!ne?.vault?.html,cn=!!ne?.gateways?.pcivault,Fn=!!(ne?.gateways?.stripe?.enabledPaymentMethods??S)?.includes("card"),z=_t||Fn||cn,ke=!!(V&&z&&O&&e),[tn,dn]=(0,s.useState)(()=>G!=="buttons"||Qe?e??null:null),[_e,Hn]=(0,s.useState)(0),Dn=G!=="buttons"||Qe||!!e&&tn===e,zt=(0,s.useMemo)(()=>!O||!ke||!e||!Dn?null:O.cardCapture({sessionId:e,captureMethod:ne?.captureMethod}),[O,ke,e,Dn,ne?.captureMethod]),un=(0,s.useMemo)(()=>{let a=lt,C=P?(0,u.isAVSFieldVisible)(P.postal_code,a):!1;return Zl(a,gn,C)},[P,lt,gn]),{avsInvalid:Rr,invalidAvsFields:Er}=(0,s.useMemo)(()=>{let a={line1:!1,city:!1,state:!1,zip:!1};if(!ke||!P)return{avsInvalid:!1,invalidAvsFields:a};let C=lt,W=(Ce,Ie)=>(0,u.isAVSFieldVisible)(Ce,C)&&!Ie.trim(),Oe={line1:W(P.address_line_1,hn),city:W(P.city,Ct),state:W(P.state,ct),zip:un.empty||un.malformed};return{avsInvalid:Oe.line1||Oe.city||Oe.state||Oe.zip,invalidAvsFields:Oe}},[ke,P,lt,hn,Ct,ct,un]),[En,ur]=(0,s.useState)(!1),[Wn,Ln]=(0,s.useState)(!1),[St,or]=(0,s.useState)(!1),[_n,Yn]=(0,s.useState)({line1:!1,city:!1,state:!1}),Cn=(0,s.useRef)(!1),Gn=(0,s.useRef)({email:!1,line1:!1,city:!1,state:!1,zip:!1}),Jn=(0,s.useRef)(!1),dt=(0,s.useCallback)(a=>{Gn.current[a]=!0,Jn.current=!0},[]),Tn=(0,s.useCallback)(a=>!Cn.current&&Gn.current[a],[]),Nn=(0,s.useCallback)(a=>{Tn(a)&&Yn(C=>C[a]?C:{...C,[a]:!0})},[Tn]),[xn,Xn]=(0,s.useState)(()=>Va(ne?.vault)),[qe,pn]=(0,s.useState)(Qe&&z?"card":"buttons"),[Mt,pr]=(0,s.useState)(null),mr=qe==="expanding"||qe==="card",yr=ne?.gateways?.stripe?"stripe":void 0,Mn=(0,s.useCallback)(()=>{pt?.({class:"card_surface",provider:yr})},[yr,pt]),Zn=(0,s.useRef)(null),Ht=(0,s.useCallback)(a=>{Zn.current&&clearTimeout(Zn.current),Zn.current=setTimeout(()=>{Zn.current=null,a()},Ao)},[]);(0,s.useEffect)(()=>()=>{Zn.current&&clearTimeout(Zn.current)},[]);let U=(0,s.useCallback)(()=>{Mn(),dn(e??null),Hn(a=>a+1),pn("expanding"),Ht(()=>pn("card"))},[Ht,Mn,e]),j=(0,s.useCallback)(()=>{pn("collapsing"),Ht(()=>pn("buttons"))},[Ht]),re=(0,s.useCallback)(a=>{pr(a),pn("apm-expanding"),Ht(()=>pn("apm-form"))},[Ht]),oe=(0,s.useCallback)(()=>{pn("apm-collapsing"),Ht(()=>{pn("buttons"),pr(null)})},[Ht]);(0,s.useEffect)(()=>{G==="buttons"&&Qe&&z&&(dn(e??null),pn("card"))},[G,Qe,z,e]);let[We,ee]=(0,s.useState)(null),J=(0,s.useRef)(!1),E=(0,s.useRef)(null),B=(0,s.useRef)("idle"),[X,vt]=(0,s.useState)(null),et=(0,s.useRef)(X);(0,s.useEffect)(()=>{et.current=X},[X]);let pe=n||Yt,at=(0,s.useRef)(null),T=(0,s.useMemo)(()=>{if(Fe||xe.claimBuyerIdentity||ne?.buyerIdentified!==!1||!e||!t)return;let a=`${pe}|${e}|${t}`;at.current?.key!==a&&(at.current={key:a,claim:Yr(new Pr.PaymentAPI(pe,{telemetry:!1}),e,t,{...o?{userId:o}:{},...y?{firstName:y}:{},...f?{lastName:f}:{}})});let C=at.current.claim;return async W=>{await C(W)}},[Fe,xe.claimBuyerIdentity,ne?.buyerIdentified,e,t,pe,o,y,f]),m=Fe??xe.claimBuyerIdentity??T,M=F??jt,K=(0,s.useMemo)(()=>(0,u.resolveTheme)(he),[he]),b=(0,s.useMemo)(()=>{let a=K?.buttonsLayout??(0,u.resolveButtonsLayoutTheme)(Ke);return Se?{...a,...Se,cardButton:{...a.cardButton,...Se.cardButton},cardFormContainer:{...a.cardFormContainer,...Se.cardFormContainer},backButton:{...a.backButton,...Se.backButton},backButtonIcon:{...a.backButtonIcon,...Se.backButtonIcon},submitButton:{...a.submitButton,...Se.submitButton},title:{...a.title,...Se.title}}:a},[K,Ke,Se]),H=Rt??K?.appearance,Ye=(0,s.useMemo)(()=>ia({appearance:H,buttonsStyles:b,layout:G}),[H,b,G]),ln=xe.inlineSessionPatchProcessing??!1,it=(I??fn)||ln,st=pe.replace(/\/+$/,""),me=(0,s.useMemo)(()=>Fa({userId:o,email:r,firstName:y,lastName:f,country:x,zip:Q},bn),[o,r,y,f,x,Q,bn]),be=[me.firstName,me.lastName].filter(a=>!!a?.trim()).join(" "),Ze=!(0,u.isValidEmail)(me.email?.trim()),Ne=(0,s.useRef)(null);ke&&Ne.current===null&&(Ne.current=Ze);let Te=ke&&(Ne.current??Ze),bt=(0,s.useMemo)(()=>Ql(Xe,Te),[Xe,Te]),nn=bt.empty||bt.malformed,Me=(0,s.useMemo)(()=>O?O.getRawProvider():null,[O]),Pn=(0,s.useMemo)(()=>Le?Le.getRawProvider():null,[Le]),On=$||100,Nr=Ue.toLowerCase(),ha=(0,s.useMemo)(()=>H?(0,Pr.toStripeAppearance)(H):null,[H]),Or=ha,li=(0,s.useMemo)(()=>{let a=ha??{},C=a.rules??{};return{...a,rules:{...C,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...C[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...C[".AccordionItemContents"]??{}}}}},[ha]),ci=(0,s.useMemo)(()=>({...Hi($,ne?.captureMethod),currency:Nr,...Or?{appearance:Or}:null}),[$,Nr,ne?.captureMethod,Or]),di=(0,s.useMemo)(()=>({mode:"payment",amount:On,currency:Nr,captureMethod:"manual",setupFutureUsage:"off_session",...Or?{appearance:Or}:null}),[On,Nr,Or]),fe=(0,s.useCallback)(a=>{Gt(a),N?.(a)},[N]),va=(0,s.useRef)(""),[ui,Us]=(0,s.useState)(!1),ba=(0,s.useCallback)(()=>{Us(!0)},[]);(0,s.useEffect)(()=>{if(!ke||!Te||!m||!ui||nn||va.current)return;let a=kn({email:(0,u.isValidEmail)(me.email?.trim())?me.email?.trim():sn.current.trim(),firstName:me.firstName?.trim(),lastName:me.lastName?.trim()});va.current=JSON.stringify(a),an(C=>({...C,...a})),Promise.resolve(m(a)).catch(C=>{va.current="",fe(C instanceof Error?C.message:"Failed to attach buyer details.")})},[ke,Te,m,ui,nn,me.email,me.firstName,me.lastName,fe]),(0,s.useEffect)(()=>{!ke||!zt||zt.setCardFieldOrder?.(te??null,P==null&&!Te)},[ke,zt,te,P,Te]),(0,s.useEffect)(()=>{(qe==="expanding"||qe==="collapsing"||qe==="apm-expanding"||qe==="apm-collapsing")&&fe(null)},[qe,fe]);let Qn=(0,s.useCallback)((a,C,W)=>{c?.(Qt(a,C,W))},[c]),zr=(0,s.useCallback)((a,C,W)=>{let Oe=W?.popupBlocked??kr(C),Z=Jl(a,Oe),Ce=Br(W?.code)??hr(C)??"external_payment_method_failed",Ie=new u.FloPayError(Z,"api_error",{code:"external_payment_method_failed",param:a});ee(null),G==="buttons"&&(pn("buttons"),pr(null)),fe(Z),d?.(Ie),console.error("[FloPay] External payment method failed:",{method:a,code:Ce,popupBlocked:Oe})},[G,d,fe]);(0,s.useEffect)(()=>{if(!ke||!e){Xn(null);return}let a=Va(ne?.vault);if(a){Xn(a);return}if(!Dn){Xn(null);return}Xn(null);let C=!0;return new Pr.PaymentAPI(st).getVaultCapture(e,t).then(W=>{if(!C)return;let Oe=Va(W);Oe?Xn(Oe):fe("Failed to load the secure card form.")}).catch(W=>{C&&fe(W instanceof Error?W.message:"Failed to load the secure card form.")}),()=>{C=!1}},[ke,Dn,_e,e,ne?.vault,st,t,fe]);let ar=(0,s.useRef)({onComplete:i,onError:d,updateError:fe,emitDecline:Qn,resolvedAccount:me,avsConfig:P,avsCheckProp:Ge,sessionId:e,nonce:t,baseUrl:st,captureMethod:ne?.captureMethod,paymentId:ne?.paymentId,authorizationExpiresAt:ne?.authorizationExpiresAt});ar.current={onComplete:i,onError:d,updateError:fe,emitDecline:Qn,resolvedAccount:me,avsConfig:P,avsCheckProp:Ge,sessionId:e,nonce:t,baseUrl:st,captureMethod:ne?.captureMethod,paymentId:ne?.paymentId,authorizationExpiresAt:ne?.authorizationExpiresAt};let Ca=(0,s.useRef)(!1),pi=(0,s.useCallback)(()=>{let a=ar.current,C=a.resolvedAccount.email?.trim(),W=(0,u.isValidEmail)(C)?C:sn.current.trim();if(!(0,u.isValidEmail)(W))return null;let Oe=a.resolvedAccount.firstName?.trim(),Z=a.resolvedAccount.lastName?.trim(),Ce=Ot.current||a.resolvedAccount.country||"US",Ie=a.avsConfig?(0,u.isAVSFieldVisible)(a.avsConfig.state,Ce):!1,wt=a.avsConfig?(0,u.isAVSFieldVisible)(a.avsConfig.address_line_1,Ce):!1,Bt=a.avsConfig?(0,u.isAVSFieldVisible)(a.avsConfig.postal_code,Ce):!1,Ft=a.avsConfig?(0,u.isAVSFieldVisible)(a.avsConfig.city,Ce):!1,Zt=a.avsConfig?(0,u.isAVSFieldVisible)(a.avsConfig.address_line_2,Ce):!1,kt=wt&&!Ie&&Bt?(0,u.getStateFromPostalCode)(Ce,(Kt.current??"").trim()):null,fr=Ie?xt.current:kt;return{accountData:{userId:a.resolvedAccount.userId??"",email:W,...Oe?{firstName:Oe}:{},...Z?{lastName:Z}:{},...Bt&&Kt.current?{zip:Kt.current}:{},...Ft&&Rn.current?{city:Rn.current}:{},...fr?{state:fr}:{},...wt&&en.current?{addressLine1:en.current}:{},...Zt&&Xt.current?{addressLine2:Xt.current}:{},country:Ce},...a.avsCheckProp===void 0?{}:{avsCheck:a.avsCheckProp},...a.avsConfig?{avsConfig:{country:(0,u.isAVSFieldVisible)(a.avsConfig.country,Ce),postal_code:Bt,address_line_1:wt,address_line_2:Zt,city:Ft,state:Ie}}:{}}},[]),mi=(0,s.useRef)(A);mi.current=A,(0,s.useEffect)(()=>{A||M!==ms||ar.current.updateError(null)},[A,M]),(0,s.useEffect)(()=>{!ke||!zt||zt.setSubmitGate?.(Rr||A||nn)},[ke,zt,Rr,A,nn]),(0,s.useEffect)(()=>{if(!ke||!zt)return;Ca.current=!1;let a=!1,C=zt.on("submitting",()=>{ur(!0),E.current&&clearTimeout(E.current),B.current="validation-window",E.current=setTimeout(()=>{E.current=null,B.current==="validation-window"&&(B.current="processing")},Ul),ee("processing");let Ie=ar.current;if(!Ie.sessionId||!Ie.nonce)return;let wt=pi();if(!wt){Ie.updateError("Enter a valid email address."),B.current="idle",ee(null);return}new Pr.PaymentAPI(Ie.baseUrl).patchAccountSnapshot(Ie.sessionId,Ie.nonce,wt,{telemetryMode:"best_effort"}).catch(Bt=>{if(!ql(Bt))return;let Ft=Bt instanceof Error?Bt.message:"Please check your billing address and try again.";Ie.updateError(Ft),B.current="idle",ee(null),Ie.onError?.(Bt instanceof u.FloPayError?Bt:new u.FloPayError(Ft,"api_error"))})}),W=zt.on("complete",async Ie=>{if(to(Ie.sessionId??ar.current.sessionId),B.current="terminal",ee("success"),await new Promise(Ft=>setTimeout(Ft,1200)),Ca.current)return;Ca.current=!0;let wt=ar.current,Bt=(0,u.isAuthorizationOnlySession)(wt)||Ie.outcome==="authorized";ar.current.onComplete?.(Bt?{status:"authorized",paymentIntentId:Ie.intentId,paymentId:Ie.paymentId??wt.paymentId,sessionId:Ie.sessionId??wt.sessionId,authorizationExpiresAt:Ie.authorizationExpiresAt??wt.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",paymentIntentId:Ie.intentId,checkoutMethod:"card"})}),Oe=zt.on("decline",async Ie=>{let wt=ar.current,Bt=Ie.message??"Your payment was declined. Please try another card or contact your bank.";B.current="terminal",wt.updateError(Bt),ee("error");let Ft=Ie.failureOutcome??(0,u.normalizeCheckoutFailureOutcome)(Ie.declineReason)??"authorization_declined";wt.emitDecline("card",Bt,{code:Ft,declineCode:Ft}),await new Promise(Zt=>setTimeout(Zt,1500)),!a&&(B.current="idle",ee(null))}),Z=zt.on("error",async Ie=>{let wt=ar.current,Bt=Ie.message??"There was a problem processing your payment. Please try again.";B.current="terminal",wt.updateError(Bt),ee("error"),wt.onError?.(new u.FloPayError(Bt,"api_error",{code:Ie.failureOutcome??"capture_failed"})),await new Promise(Ft=>setTimeout(Ft,1500)),!a&&(B.current="idle",ee(null))}),Ce=zt.on("blocked",()=>{if(!mi.current){ur(!0);return}ba(),ar.current.updateError(ms)});return()=>{a=!0,E.current&&(clearTimeout(E.current),E.current=null),B.current="idle",C(),W(),Oe(),Z(),Ce()}},[ke,zt,ba,pi]);let ir=!!ye?.clientId,io=Array.isArray(S),No=io&&S.length>0,qs=io&&S.includes("paypal"),{expressMethods:Oo,paymentElementMethods:so}=(0,s.useMemo)(()=>(0,u.partitionStripeMethods)(S,{excludePaypal:ir}),[S,ir]),yi=ir||!!Le,$s=(0,s.useMemo)(()=>yi?Oo.filter(a=>a!=="paypal"):Oo,[Oo,yi]),js=(0,s.useMemo)(()=>{let a=[];return q&&a.push("apple_pay"),de&&a.push("google_pay"),a},[q,de]),Ur=io?$s:js,Vs=V&&Ur.length>0,Pa=ft?lt:x,zo=(0,s.useMemo)(()=>{let a=Pa?.trim().toUpperCase();return a?se?so.filter(C=>{let W=se[C];return!W||W.length===0||W.includes(a)}):(0,u.filterStripeMethodsByCountry)(so,Pa):so},[so,Pa,se]),Sa=(0,s.useMemo)(()=>({mode:"payment",amount:On,currency:Nr,paymentMethodCreation:"manual",appearance:li}),[On,Nr,li]),[fi,gi]=(0,s.useState)("loading"),[hi,vi]=(0,s.useState)("loading"),[bi,Ci]=(0,s.useState)("loading"),[Ks,wa]=(0,s.useState)(!1),[Pi,ka]=(0,s.useState)("loading"),[Uo,Hs]=(0,s.useState)();(0,s.useEffect)(()=>{Hs(cs())},[]);let Si=ge&&(ir||(io?qs:Uo===!1)),wi=V&&Vs,lo=!Je&&Si&&ir,ki=Pi==="retrying"||Pi==="exhausted",co=!Je&&Si&&!!Pn&&(!ir||ki),qr=!Je&&wi&&!!Me,uo=!Je&&V&&No&&zo.length>0&&!!Me,Ws=lo&&!ki?Ks:co&&vs(fi),Ys=qr&&vs(hi),Gs=uo&&bi!=="load_error",Ii=a=>a==="loading"||a==="ready",Ri=lo||co&&Ii(fi)||qr&&Ii(hi)||uo&&bi!=="load_error",qo=(0,s.useRef)(!1);(0,s.useEffect)(()=>{if(!qo.current){if(!V&&!ge){qo.current=!0;let a=new u.FloPayError("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");d?.(a),fe(a.message)}else if(!V&&ge&&!ir&&!Pn){qo.current=!0;let a=new u.FloPayError("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");d?.(a),fe(a.message)}else if(Uo!==void 0&&!Je&&!z&&!Ri){qo.current=!0;let a=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?.(a),fe(a.message)}}},[V,ge,ir,Pn,Uo,Je,z,Ri,d,fe]);let Ei=(0,s.useRef)(!1);(0,s.useEffect)(()=>{if(Ei.current||!No)return;let a=[];q!==!0&&a.push("showApplePay"),de!==!0&&a.push("showGooglePay"),a.length!==0&&(Ei.current=!0,console.warn(`[FloPay] ${a.join(" / ")} ${a.length===1?"is":"are"} deprecated: the Apple Pay / Google Pay surface is now driven by \`gateways.stripe.enabledPaymentMethods\` on the session response. Remove the legacy prop(s) to silence this warning.`))},[No,q,de]);let _i=(0,s.useCallback)((a,C)=>xe.applyInlineSessionPatch?xe.applyInlineSessionPatch(a).then(W=>({error:null,sessionId:W.sessionId||e,nonce:W.session?.clientSecret||t})).catch(W=>{let Oe=hs(C,W);return fe(Oe.message),d?.(Oe),{error:Oe,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[xe.applyInlineSessionPatch,t,d,e,fe]),er=(0,s.useCallback)(async a=>{if(!D)return{proceed:!0};try{let C=await D({method:a,sessionId:e||void 0,createSession:xe.inlineSessionDraft});if(C===!1)return{proceed:!1};if(C&&typeof C=="object"){C.account&&an(Oe=>({...Oe??{},...C.account}));let W=await _i(C,a);return W.error?{proceed:!1,accountPatch:C.account}:{proceed:!0,accountPatch:C.account,sessionId:W.sessionId,nonce:W.nonce}}return{proceed:!0}}catch(C){let W=hs(a,C);return fe(W.message),d?.(W),{proceed:!1}}},[_i,xe.inlineSessionDraft,D,d,e,fe]),Ti=(0,s.useCallback)(async(a,C)=>{if(J.current)return;J.current=!0,L(!0),ee("processing"),fe(null);let W=C?.sessionId??e,Oe=C?.nonce??t,Z=Fa(me,C?.accountPatch),Ce=C?.completionPaymentMethodId??Co(a),Ie=a.originalPaymentMethodId?{...a,originalPaymentMethodId:void 0}:a,wt=Hl(a),Bt=()=>{pt?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"process_payment",provider:wt})};try{let Zt=await new Pr.PaymentAPI(st).processPayment(Z.userId??"",{sessionId:W,nonce:Oe,paymentMethodCategory:C?.paymentMethodCategory??Yl(a),tokenizedData:Ie,accountData:{...C?.accountPatch,userId:Z.userId??"",email:Z.email??"",firstName:Z.firstName||void 0,lastName:Z.lastName||void 0,...P?(()=>{let ut=Ot.current,Un=(0,u.isAVSFieldVisible)(P.state,ut),mn=(0,u.isAVSFieldVisible)(P.address_line_1,ut),Dt=(0,u.isAVSFieldVisible)(P.postal_code,ut),xr=mn&&!Un&&Dt?(0,u.getStateFromPostalCode)(ut,(Kt.current??"").trim()):null,ho=Un?xt.current:xr;return{country:ut,...Dt&&Kt.current?{zip:Kt.current}:{},...(0,u.isAVSFieldVisible)(P.city,ut)&&Rn.current?{city:Rn.current}:{},...ho?{state:ho}:{},...mn&&en.current?{addressLine1:en.current}:{},...(0,u.isAVSFieldVisible)(P.address_line_2,ut)&&Xt.current?{addressLine2:Xt.current}:{}}})():{}},chv:g,avsCheck:Ge??!1,checkoutType:ie,checkoutLayout:Y,avsConfig:P?{country:(0,u.isAVSFieldVisible)(P.country,Ot.current),postal_code:(0,u.isAVSFieldVisible)(P.postal_code,Ot.current),address_line_1:(0,u.isAVSFieldVisible)(P.address_line_1,Ot.current),address_line_2:(0,u.isAVSFieldVisible)(P.address_line_2,Ot.current),city:(0,u.isAVSFieldVisible)(P.city,Ot.current),state:(0,u.isAVSFieldVisible)(P.state,Ot.current)}:void 0});if(Zt.ok){let ut=Zt.status===204?null:await Zt.json().catch(()=>null),Un=(0,u.isAuthorizationOnlySession)(ne)||ut?.status==="authorized";to(W),ee("success"),vt(null),await new Promise(xr=>setTimeout(xr,1200));let mn;typeof ut?.paymentId=="string"?mn=ut.paymentId:ne?.paymentId&&(mn=ne.paymentId);let Dt;typeof ut?.authorizationExpiresAt=="string"?Dt=ut.authorizationExpiresAt:ne?.authorizationExpiresAt&&(Dt=ne.authorizationExpiresAt),i?.(Un?{status:"authorized",...mn===void 0?{}:{paymentId:mn},sessionId:typeof ut?.sessionId=="string"?ut.sessionId:W,...Dt===void 0?{}:{authorizationExpiresAt:Dt},paymentIntentId:a.threeDSecureActionResultTokenId,paymentMethodId:Ce,checkoutMethod:a.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:a.threeDSecureActionResultTokenId,paymentMethodId:Ce,checkoutMethod:a.isPaypal?"paypal":"card"});return}let kt=await Zt.json().catch(()=>null);if(kt?.type==="paypal_redirect_required"){let ut=kt.threeDSecureToken,Un=kt.paymentMethodId||a.id||"";if(!O||!ut){ee("error"),fe("PayPal authorization required but no token provided.");return}try{let mn=Le?.getRawProvider();if(!mn){fe("PayPal is not available.");return}let Dt={return_url:window.location.href};Un&&(Dt.payment_method=Un);let{error:xr}=await mn.confirmPayment({clientSecret:ut,confirmParams:Dt,redirect:"if_required"});if(xr){ee("error");let ho=xr.message??"PayPal payment failed.";fe(ho),Qn("paypal",ho,{code:xr.code})}}catch(mn){ee("error"),fe(mn instanceof Error?mn.message:"PayPal authorization failed.")}return}if(kt?.type==="paypal_direct_required"){let ut=kt.orderId;if(!ut){ee("error"),fe("PayPal retry required but no order id provided.");return}let Un=et.current?.attempts??0;if(Un>=2){ee("error"),fe("PayPal payment could not be completed after multiple attempts."),Qn("paypal","paypal_direct_required retry limit exceeded");return}wa(!1),ka("loading"),vt({orderId:ut,attempts:Un+1}),ee(null);return}(0,u.classifyPaymentRejection)(Zt.status,kt)||Bt(),ee("error");let fr=kt?.message??"Payment failed. Please try again.";fe(fr),Qn(a.isPaypal?"paypal":"card",fr,{code:kt?.code??kt?.gatewayErrorCode,declineCode:kt?.declineCode??kt?.gatewayDeclineReason}),await new Promise(ut=>setTimeout(ut,1500))}catch(Ft){ws(Ft)||Bt(),ee("error"),fe(Ft instanceof Error?Ft.message:"An unexpected error occurred"),await new Promise(Zt=>setTimeout(Zt,1500))}finally{L(!1),ee(null),J.current=!1}},[st,e,t,me,P,Ge,ie,Y,g,O,Le,ne,i,fe,Qn,pt]),Sn=(0,s.useCallback)((a,C)=>{v?v(a):Ti(a,C)},[v,Ti]),po=`${Ss}:${e}`;(0,s.useEffect)(()=>{if(typeof window>"u")return;let a=localStorage.getItem(po);if(!a)return;let C;try{C=JSON.parse(a)}catch{localStorage.removeItem(po);return}if(!C||typeof C.createdAt!="number"||Date.now()-C.createdAt<0||Date.now()-C.createdAt>Ll||typeof C.paymentMethodId!="string"||typeof C.providerIntentId!="string"||typeof C.paymentMethodType!="string"||C.sessionId!==e||!t||C.nonce!==t||!Ur.includes(C.paymentMethodType)){localStorage.removeItem(po);return}localStorage.removeItem(po),Sn({id:C.paymentMethodId,type:"card",threeDSecureActionResultTokenId:C.providerIntentId,gateway:"stripe",paymentMethodType:C.paymentMethodType},{...C.accountPatch?{accountPatch:C.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t})},[Sn,t,e,po,Ur]);let xi=(0,s.useRef)(!1);(0,s.useEffect)(()=>{if(typeof window>"u"||xi.current)return;let a=new URLSearchParams(window.location.search),C=a.get("payment_intent"),W=a.get("payment_intent_client_secret"),Oe=a.get("redirect_status");if(!C||!W)return;let Z=Zt=>{let kt=localStorage.getItem(Zt);if(!kt)return null;try{return JSON.parse(kt)}catch{return localStorage.removeItem(Zt),null}},Ce=Z(sr)??Z(ps),Ie;if(Ce?.clientSecret){if(Ce.clientSecret!==W)return;Ie={...Ce.accountPatch?{accountPatch:Ce.accountPatch}:{},...Ce.sessionId?{sessionId:Ce.sessionId}:{},...Ce.nonce?{nonce:Ce.nonce}:{}}}else if(Ce?.sessionId&&Ce.sessionId!==e)return;xi.current=!0,localStorage.removeItem(sr),localStorage.removeItem(ps);let wt=new URL(window.location.href);wt.searchParams.delete("payment_intent"),wt.searchParams.delete("payment_intent_client_secret"),wt.searchParams.delete("redirect_status"),window.history.replaceState({},"",wt.toString());let Bt=Ce?.paymentMethodType??Ce?.tokenType??"card",Ft="card";(async()=>{let Zt=O?.getRawProvider();if(!Zt){let Dt="Payment is not available \u2014 please refresh and try again.";fe(Dt),Qn(Ft,Dt);return}if(Oe==="failed"){let Dt="Payment was declined. Please try again.";fe(Dt),Qn(Ft,Dt);return}let{paymentIntent:kt,error:fr}=await Zt.retrievePaymentIntent(W);if(fr){let Dt=fr.message??"Failed to retrieve payment status.";fe(Dt),Qn(Ft,Dt,{code:fr.code});return}let ut=kt?.status,Un=bo(ut);if(!kt||!Un){let Dt=ut==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";fe(Dt),Qn(Ft,Dt,{code:ut??"missing_payment_intent"});return}let mn=typeof kt.payment_method=="string"?kt.payment_method:kt.payment_method?.id;Sn({id:mn??Ce?.paymentMethodId??Ce?.tokenId??kt.id,type:"card",threeDSecureActionResultTokenId:kt.id,gateway:Ce?.gateway??"stripe",paymentMethodType:Bt},Ie)})()},[e,Sn,O,fe,Qn]);let Ia=(0,s.useCallback)(a=>{a.preventDefault()},[]);if(!(O!==null))return(0,l.jsx)("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let mo=G==="buttons",wn=H?.variables,Js=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),Ra=wn?.colorBackground,Xs=Ra&&!Js.has(Ra)?Ra:void 0,yo=b.cardInputBorder??(mo?"#e5e7eb":"#A4A4FF"),Mi=wn?.colorDanger??"#dc2626",At=a=>Er[a]&&(_n[a]||En),$o=nn&&(St||En),zn=a=>a?Mi:yo,jo=(un.malformed||un.empty)&&(Wn||En),Zs=zn(jo),Ea=b.cardFormContainer?.backgroundColor??Xs??(mo?"white":"#EDEDFF"),$r=b.cardInputBackground??wn?.colorBackground??"white",_a=Kr(Ae),Ai=Kr(Be),jr=b.nameInput,Bi=b.cardInputFontSize??ec(jr?.fontSize)??wn?.fontSizeBase??"16px",Fi=typeof jr?.fontFamily=="string"?jr.fontFamily:wn?.fontFamily??"Poppins, sans-serif",Di=qa(jr?.fontWeight)??400,Qs=b.cardInputColor??(typeof jr?.color=="string"?jr.color:void 0)??wn?.colorText??"#262833",el=b.cardInputPlaceholderColor??"#9ca3af",Ut=wn?.borderRadius??"8px",_r=wn?.borderRadius??b.cardButton?.borderRadius??Ut,Tr=wn?.colorPrimary??"#4A49FF",tl=wn?.colorPrimaryHover??ao(Tr,.12),Ta=wn?.colorText??"#262833",xa={fontSize:Bi,fontFamily:Fi,fontWeight:Di,color:Qs,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},fo={marginTop:"0.375rem",...xa,fontSize:"0.75rem",lineHeight:1.4,color:Mi},nl={"--flopay-input-placeholder-color":el,"--flopay-input-font-size":Bi,"--flopay-input-font-family":Fi,"--flopay-input-font-weight":String(Di)},go=b.cardFormContainer??{},Ma=go.padding??(mo?"0":"1rem"),Aa=go.borderRadius??Ut,rl=zt&&xn?(0,l.jsx)(oo,{capture:zt,html:xn.html,messageToken:xn.messageToken,expectedOrigin:xn.expectedOrigin,theme:Ye,onReady:()=>{if(!Te&&!P||typeof document>"u")return;let a=()=>{let W=(document.querySelector('[data-testid="flopay-vault-identity-fields"]')??document.querySelector('[data-testid="flopay-avs-fields"]'))?.querySelector("input:not([disabled]), select:not([disabled])");if(W){Cn.current=!0;try{W.focus()}finally{Cn.current=!1}}};Jn.current||a()},onError:a=>fe(a),onValidation:a=>{let C=B.current;(C==="idle"||C==="validation-window")&&(fe(a),a&&B.current==="validation-window"&&(E.current&&(clearTimeout(E.current),E.current=null),B.current="idle",ee(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"}),Li=(0,l.jsxs)("div",{onFocusCapture:a=>{["INPUT","SELECT","TEXTAREA","IFRAME"].includes(a.target.tagName)&&Mn()},style:{backgroundColor:Ea,borderRadius:Aa,...go,padding:Ma,...nl,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 @@ ${Jt.join(`
35
35
  font-family: var(--flopay-input-font-family);
36
36
  font-weight: var(--flopay-input-font-weight);
37
37
  }
38
- `}),mo&&dr&&(0,l.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:Ie?-2:0},children:[(0,l.jsxs)("button",{type:"button",onClick:U,style:{display:"inline-flex",alignItems:"center",gap:Ta?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:v.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...v.backButton},"aria-label":"Back to payment methods",children:[(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",...v.backButtonIcon},children:(0,l.jsx)("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,l.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,l.jsx)(Yr,{content:Me})]}),xi?(0,l.jsx)("div",{style:{flex:1}}):(0,l.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:v.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...v.title},children:(0,l.jsx)(vo,{content:Ae})})]}),!mo&&!xi&&(0,l.jsx)("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:xa,order:Ie?-3:0,...v.title},children:(0,l.jsx)(vo,{content:Ae})}),Ie&&Ee&&(0,l.jsx)("div",{style:{order:-2,width:"100%"},children:Ee}),Ie&&_e&&(0,l.jsxs)("div",{"data-testid":"flopay-vault-identity-fields",style:{order:-1,marginTop:"0.5rem"},children:[(0,l.jsx)("div",{style:{backgroundColor:$r,border:`1px solid ${Bn($o)}`,borderRadius:Ft,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:a=>{dt("email"),_n.current=a.target.value,Xt(a.target.value)},onPointerDown:()=>dt("email"),onKeyDown:()=>dt("email"),onBlur:()=>{kn("email")&&tr(!0),Wt||Pa()},disabled:lt,required:!0,"aria-invalid":$o||void 0,"aria-describedby":$o?"flopay-buyer-email-error":void 0,"data-testid":"flopay-email",style:{width:"100%",border:"none",outline:"none",background:"transparent",...Ma}})}),$o&&(0,l.jsx)("div",{id:"flopay-buyer-email-error",role:"alert","data-testid":"flopay-email-error",style:fo,children:ht.empty?"Email address is required":"Enter a valid email address"})]}),ce&&(0,l.jsx)("div",{style:{order:Ie?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let a=it,b=(H=!1)=>({backgroundColor:$r,border:`1px solid ${Bn(H)}`,borderRadius:Ft,marginTop:"0.5rem",padding:"10px"}),K=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...Ma}),Le=(0,u.getStateOptions)(a);return(0,l.jsxs)(l.Fragment,{children:[(0,u.isAVSFieldVisible)(ce.address_line_1,a)&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)("div",{style:b(_t("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:mn,onChange:H=>{dt("line1"),an.current.addressLine1=!0,Pn.current=H.target.value,Nt(H.target.value)},onPointerDown:()=>dt("line1"),onKeyDown:()=>dt("line1"),onBlur:()=>Mn("line1"),disabled:lt,required:!0,"aria-invalid":_t("line1")||void 0,"aria-describedby":_t("line1")?"flopay-billing-address-line1-error":void 0,"data-testid":"flopay-address-line1",style:K()})}),_t("line1")&&(0,l.jsx)("div",{id:"flopay-billing-address-line1-error",role:"alert","data-testid":"flopay-address-line1-error",style:fo,children:"Street address is required"})]}),(0,u.isAVSFieldVisible)(ce.address_line_2,a)&&(0,l.jsx)("div",{style:b(),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:bn,onChange:H=>{an.current.addressLine2=!0,rn.current=H.target.value,Ht(H.target.value)},disabled:lt,"data-testid":"flopay-address-line2",style:K()})}),((0,u.isAVSFieldVisible)(ce.city,a)||(0,u.isAVSFieldVisible)(ce.state,a))&&(0,l.jsxs)("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[(0,u.isAVSFieldVisible)(ce.city,a)&&(0,l.jsx)("div",{style:{flex:1,backgroundColor:$r,borderTop:`1px solid ${Bn(_t("city"))}`,borderRight:`1px solid ${Bn(_t("city"))}`,borderBottom:`1px solid ${Bn(_t("city"))}`,borderLeft:`1px solid ${Bn(_t("city"))}`,padding:"10px",borderTopLeftRadius:Ft,borderBottomLeftRadius:Ft,...(0,u.isAVSFieldVisible)(ce.state,a)?{borderRight:"none",borderTopRightRadius:0,borderBottomRightRadius:0}:{borderRadius:Ft}},children:(0,l.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-city",name:"billing-city",placeholder:"City",autoComplete:"billing address-level2",value:mt,onChange:H=>{dt("city"),an.current.city=!0,Un.current=H.target.value,Qe(H.target.value)},onPointerDown:()=>dt("city"),onKeyDown:()=>dt("city"),onBlur:()=>Mn("city"),disabled:lt,required:!0,"aria-invalid":_t("city")||void 0,"aria-describedby":_t("city")?"flopay-billing-city-error":void 0,"data-testid":"flopay-city",style:K()})}),(0,u.isAVSFieldVisible)(ce.state,a)&&(0,l.jsx)("div",{style:{flex:1,backgroundColor:$r,borderTop:`1px solid ${Bn(_t("state"))}`,borderRight:`1px solid ${Bn(_t("state"))}`,borderBottom:`1px solid ${Bn(_t("state"))}`,borderLeft:`1px solid ${Bn(_t("state"))}`,padding:"10px",borderTopRightRadius:Ft,borderBottomRightRadius:Ft,...(0,u.isAVSFieldVisible)(ce.city,a)?{borderTopLeftRadius:0,borderBottomLeftRadius:0,borderLeft:`1px solid ${Bn(_t("state")||_t("city"))}`}:{borderRadius:Ft}},children:Le?(0,l.jsxs)("select",{id:"flopay-billing-state",name:"billing-state",value:yt,onChange:H=>{dt("state"),an.current.state=!0,on.current=H.target.value,tn(H.target.value)},onPointerDown:()=>dt("state"),onKeyDown:()=>dt("state"),onBlur:()=>Mn("state"),disabled:lt,autoComplete:"billing address-level1",required:!0,"aria-invalid":_t("state")||void 0,"aria-describedby":_t("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)(a)}),Le.map(H=>(0,l.jsx)("option",{value:H.code,children:H.name},H.code))]}):(0,l.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-state",name:"billing-state",placeholder:(0,u.getStateLabel)(a),autoComplete:"billing address-level1",value:yt,onChange:H=>{dt("state"),an.current.state=!0,on.current=H.target.value,tn(H.target.value)},onPointerDown:()=>dt("state"),onKeyDown:()=>dt("state"),onBlur:()=>Mn("state"),disabled:lt,required:!0,"aria-invalid":_t("state")||void 0,"aria-describedby":_t("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:K()})})]}),_t("city")&&(0,l.jsx)("div",{id:"flopay-billing-city-error",role:"alert","data-testid":"flopay-city-error",style:fo,children:"City is required"}),_t("state")&&(0,l.jsxs)("div",{id:"flopay-billing-state-error",role:"alert","data-testid":"flopay-state-error",style:fo,children:[(0,u.getStateLabel)(a)," is required"]}),((0,u.isAVSFieldVisible)(ce.country,a)||(0,u.isAVSFieldVisible)(ce.postal_code,a))&&(0,l.jsxs)("div",{style:{display:"flex",flexDirection:be==="column"?"column":"row",gap:be==="column"?"0.5rem":"0",marginTop:"0.5rem"},children:[(0,u.isAVSFieldVisible)(ce.country,a)&&(0,l.jsx)("div",{style:{flex:be==="row"?1:void 0,backgroundColor:$r,borderTop:`1px solid ${yo}`,borderRight:`1px solid ${yo}`,borderBottom:`1px solid ${yo}`,borderLeft:`1px solid ${yo}`,padding:"10px",...be==="row"&&(0,u.isAVSFieldVisible)(ce.postal_code,a)?{borderRadius:"0",borderTopLeftRadius:Ft,borderBottomLeftRadius:Ft,borderRight:"none"}:{borderRadius:Ft}},children:(0,l.jsx)("select",{id:"flopay-billing-country",name:"billing-country",value:it,onChange:H=>{an.current.country=!0,$t.current=H.target.value,kt(H.target.value),ot?.(H.target.value),on.current="",tn("")},disabled:lt,autoComplete:"billing country","data-testid":"flopay-country",style:{...K(),cursor:"pointer"},children:u.COUNTRY_OPTIONS.map(H=>(0,l.jsxs)("option",{value:H.code,children:[H.flag," ",H.name]},H.code))})}),(0,u.isAVSFieldVisible)(ce.postal_code,a)&&(0,l.jsx)("div",{style:{flex:be==="row"?1:void 0,backgroundColor:$r,border:`1px solid ${Xs}`,padding:"10px",...be==="row"&&(0,u.isAVSFieldVisible)(ce.country,a)?{borderRadius:"0",borderTopRightRadius:Ft,borderBottomRightRadius:Ft}:{borderRadius:Ft}},children:(0,l.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-postal-code",name:"billing-postal-code",placeholder:(0,u.getPostalCodeLabel)(it),autoComplete:"billing postal-code",value:pn,onChange:H=>{dt("zip"),an.current.zip=!0,zt.current=H.target.value,en(H.target.value),ft?.(H.target.value)},onPointerDown:()=>dt("zip"),onKeyDown:()=>dt("zip"),onBlur:()=>{kn("zip")&&xn(!0)},disabled:lt,required:ln.required,"aria-invalid":jo||void 0,"aria-describedby":jo?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:K()})})]}),jo&&(0,l.jsx)("div",{id:"flopay-billing-postal-code-error",role:"alert","data-testid":"flopay-zip-error",style:fo,children:ln.empty?`${(0,u.getPostalCodeLabel)(a)} is required`:Gl(a)})]})})()}),Ie&&nl,A&&(0,l.jsx)(eo,{margin:"0.75rem 0",styleOverride:v.errorBanner,children:A})]}),Vo={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"},Di=a=>pe?!he||!rr?(0,l.jsx)("pre",{"data-testid":a,style:Vo,children:"FloPay/DirectPayPal-debug - not enabled"}):(0,l.jsx)("pre",{"data-testid":a,style:Vo,children:["FloPay/DirectPayPal-debug (parent gate)",` showPayPal=${he}`,` directPaypalConfigured=${rr}`,` inAppBrowserDetected=${String(Uo)}`,` shouldRenderDirectPayPal=${lo}`,` shouldRenderStripePayPal=${co}`,` hasPaypalStripeInstance=${!!fn}`].join(`
39
- `)}):null,Li=a=>pe?!q||!xe?(0,l.jsx)("pre",{"data-testid":a,style:Vo,children:"FloPay/Stripe-debug - not enabled"}):(0,l.jsx)("pre",{"data-testid":a,style:Vo,children:["FloPay/Stripe-debug (parent gate)",` showStripe=${q}`,` currency=${We}`,` amountInCents=${An}`,` enabledPaymentMethods: ${JSON.stringify(P??[])}`,` enabledPaymentMethodsProvided=${io}`,` hasEnabledMethods=${No}`,` expressMethods: ${JSON.stringify(Oo)}`,` walletExpressMethods: ${JSON.stringify(Ur)}`,` paymentElementMethods: ${JSON.stringify(so)}`,` paymentElementMethodsForCurrency: ${JSON.stringify(zo)}`,` hasStripeInstance=${!!xe}`,` shouldRenderWallets=${qr}`,` shouldRenderPaymentElement=${uo}`].join(`
40
- `)}):null,Ni=Ue==="apm-expanding"||Ue==="apm-form"||Ue==="apm-collapsing",Vr;Ue==="apm-expanding"?Vr=ms:Ue==="apm-collapsing"&&(Vr=ys);let Ko=Et?Es(wa,Et):null;if(G==="buttons"){let a=Ue==="buttons"||Ue==="expanding"||Ue==="apm-expanding",b=Ue==="expanding"||Ue==="card"||Ue==="collapsing",K=qe===void 0?{boxSizing:"border-box",height:la,padding:"0 1rem"}:{padding:"0.9rem 1rem"},Le;Ue==="expanding"||Ue==="apm-expanding"?Le=jl:(Ue==="collapsing"||Ue==="apm-collapsing")&&(Le=$l);let H;return Ue==="expanding"?H=ms:Ue==="collapsing"&&(H=ys),(0,l.jsxs)("form",{onSubmit:Ra,className:p,noValidate:!0,style:{position:"relative"},children:[(0,l.jsx)(ja,{}),Ke&&(0,l.jsx)(Nn,{status:Ke,errorMessage:A,authorized:Qn}),(0,l.jsxs)("div",{style:{display:"grid"},children:[(0,l.jsxs)("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!a&&!Le?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!a&&!Le?Kl:{},...Le?{animation:Le,pointerEvents:"none"}:{}},children:[Di("flopay-direct-paypal-gate-debug"),Li("flopay-stripe-gate-debug"),lo&&ye&&(0,l.jsxs)(l.Fragment,{children:[X&&(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)(Io,{sessionId:e,nonce:t,billingApiUrl:ue,email:me.email,billingName:Pe||void 0,onBuyerIdentityReady:m,clientId:ye.clientId,environment:ye.environment,currency:We.toUpperCase(),isSubscription:at,providerObjectType:I,onTokenizedBody:gn,onComplete:i,onErrorChange:fe,onDecline:c,onTechnicalFailure:zr,onButtonClick:re,runBeforeButtonClick:Gn,isProcessing:lt,onLoadStateChange:ka,onInitializationStateChange:Ia,session:At,existingOrderId:X?.orderId,debug:pe},X?.orderId??"fresh")]}),co&&(0,l.jsx)(Lt.Elements,{stripe:fn,options:li,children:(0,l.jsx)(vs,{sessionId:e,nonce:t,email:me.email,billingName:Pe||void 0,onBuyerIdentityReady:m,billingApiUrl:ue,onTokenizedBody:gn,onErrorChange:fe,isProcessing:lt,onButtonClick:re,onDecline:c,onTechnicalFailure:zr,runBeforeButtonClick:Gn,onLoadStateChange:yi,placeholderBorderRadius:_r})}),qr?(0,l.jsx)(Lt.Elements,{stripe:xe,options:si,children:(0,l.jsx)(bs,{sessionId:e,nonce:t,email:me.email,billingName:Pe||void 0,onBuyerIdentityReady:m,billingApiUrl:ue,intentKind:z>0?"payment":"setup",expressMethods:Ur,onTokenizedBody:gn,onErrorChange:fe,onButtonClick:re,onDecline:c,onTechnicalFailure:zr,runBeforeButtonClick:Gn,onLoadStateChange:gi,placeholderBorderRadius:_r})}):null,!qr&&Ci?(0,l.jsx)("div",{style:{height:la,borderRadius:_r,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,uo&&(0,l.jsx)(Ps,{sessionId:e,nonce:t,email:me.email,billingName:[me.firstName,me.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:m,billingApiUrl:ue,paymentElementMethods:zo,stripeInstance:xe,paymentElementBaseOptions:wa,onTokenizedBody:gn,onErrorChange:fe,onButtonClick:re,onDecline:c,runBeforeButtonClick:Gn,onLoadStateChange:vi,isProcessing:lt,submitButtonColor:Tr,submitButtonBorderRadius:Ft,submitButtonStyle:v.submitButton,onExpandApm:te,expandedApmMethod:Et,themeId:ve,buttonAppearance:{backgroundColor:v.cardButton?.backgroundColor,borderColor:v.cardInputBorder,textColor:v.cardButton?.color,borderRadius:_r}}),Ie&&(0,l.jsx)("button",{type:"button",onClick:async()=>{lt||!(await Gn("card")).proceed||(re?.("card"),N())},disabled:lt,style:{width:"100%",...K,...v.cardButton,...Ya({themeBundle:j,resolvedPrimaryColor:Tr,resolvedBorderRadius:Ft,submitButtonStyle:v.submitButton,explicitPrimaryColor:hn?.colorPrimary}),fontSize:v.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:Ce=>{!lt&&(j||hn?.colorPrimary)&&(Ce.currentTarget.style.backgroundColor=el)},onMouseLeave:Ce=>{(j||hn?.colorPrimary)&&(Ce.currentTarget.style.backgroundColor=Tr)},onMouseDown:Ce=>{Ce.currentTarget.style.transform="scale(0.985)"},onMouseUp:Ce=>{Ce.currentTarget.style.transform="scale(1)"},children:(0,l.jsx)(Hr,{content:qe})}),A&&Ue==="buttons"&&(0,l.jsx)(eo,{margin:"0.25rem 0",styleOverride:v.errorBanner,children:A})]}),Ie&&b&&(0,l.jsx)("div",{style:{gridArea:"1 / 1",...H?{animation:H}:{},...Ue==="collapsing"?{pointerEvents:"none"}:{}},children:Fi}),q&&Ni&&Et&&Ko&&xe&&(0,l.jsx)("div",{style:{gridArea:"1 / 1",...Vr?{animation:Vr}:{},...Ue==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,l.jsxs)("div",{style:{backgroundColor:_a,borderRadius:Ba,...go,padding:Aa},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:ae,style:{display:"inline-flex",alignItems:"center",gap:Ta?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:v.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...v.backButton},"aria-label":"Back to payment methods",children:[(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",...v.backButtonIcon},children:(0,l.jsx)("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,l.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,l.jsx)(Yr,{content:Me})]}),(0,l.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:v.titleFontSize??"1.05rem",color:xa,paddingRight:80,...v.title},children:`Pay with ${(0,u.getStripeMethodDisplayName)(Et)}`})]}),(0,l.jsx)(Lt.Elements,{stripe:xe,options:Ko,children:(0,l.jsx)(Ka,{method:Et,sessionId:e,nonce:t,email:me.email,billingName:[me.firstName,me.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:m,billingApiUrl:ue,onTokenizedBody:gn,onErrorChange:fe,onDecline:c,onCancel:ae,runBeforeButtonClick:Gn,onButtonClick:re,isProcessing:lt,submitButtonColor:Tr,submitButtonBorderRadius:Ft,submitButtonStyle:v.submitButton,errorText:A})},Et)]})})]})]})}return Ni&&Et&&Ko&&xe&&q?(0,l.jsxs)("form",{onSubmit:Ra,className:p,noValidate:!0,style:{position:"relative"},children:[(0,l.jsx)(ja,{}),Ke&&(0,l.jsx)(Nn,{status:Ke,errorMessage:A,authorized:Qn}),(0,l.jsx)("div",{style:{...Vr?{animation:Vr}:{},...Ue==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,l.jsxs)("div",{style:{backgroundColor:_a,borderRadius:Ba,...go,padding:Aa},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:ae,style:{display:"inline-flex",alignItems:"center",gap:Ta?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:v.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...v.backButton},"aria-label":"Back to payment methods",children:[(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",...v.backButtonIcon},children:(0,l.jsx)("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,l.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,l.jsx)(Yr,{content:Me})]}),(0,l.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:v.titleFontSize??"1.05rem",color:xa,paddingRight:80,...v.title},children:`Pay with ${(0,u.getStripeMethodDisplayName)(Et)}`})]}),(0,l.jsx)(Lt.Elements,{stripe:xe,options:Ko,children:(0,l.jsx)(Ka,{method:Et,sessionId:e,nonce:t,email:me.email,billingName:[me.firstName,me.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:m,billingApiUrl:ue,onTokenizedBody:gn,onErrorChange:fe,onDecline:c,onCancel:ae,runBeforeButtonClick:Gn,onButtonClick:re,isProcessing:lt,submitButtonColor:Tr,submitButtonBorderRadius:Ft,submitButtonStyle:v.submitButton,errorText:A})},Et)]})})]}):(0,l.jsxs)("form",{onSubmit:Ra,className:p,noValidate:!0,style:{position:"relative"},children:[(0,l.jsx)(ja,{}),Ke&&(0,l.jsx)(Nn,{status:Ke,errorMessage:A,authorized:Qn}),(0,l.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Di("flopay-direct-paypal-gate-debug-default"),Li("flopay-stripe-gate-debug-default"),lo&&ye&&(0,l.jsxs)(l.Fragment,{children:[X&&(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)(Io,{sessionId:e,nonce:t,billingApiUrl:ue,email:me.email,billingName:Pe||void 0,onBuyerIdentityReady:m,clientId:ye.clientId,environment:ye.environment,currency:We.toUpperCase(),isSubscription:at,providerObjectType:I,onTokenizedBody:gn,onComplete:i,onErrorChange:fe,onDecline:c,onTechnicalFailure:zr,onButtonClick:re,runBeforeButtonClick:Gn,isProcessing:lt,onLoadStateChange:ka,onInitializationStateChange:Ia,session:At,existingOrderId:X?.orderId,debug:pe},X?.orderId??"fresh")]}),co&&(0,l.jsx)(Lt.Elements,{stripe:fn,options:li,children:(0,l.jsx)(vs,{sessionId:e,nonce:t,email:me.email,billingName:Pe||void 0,onBuyerIdentityReady:m,billingApiUrl:ue,onTokenizedBody:gn,onErrorChange:fe,isProcessing:lt,onButtonClick:re,onDecline:c,onTechnicalFailure:zr,runBeforeButtonClick:Gn,onLoadStateChange:yi,placeholderBorderRadius:_r})}),qr&&(0,l.jsx)(Lt.Elements,{stripe:xe,options:si,children:(0,l.jsx)(bs,{sessionId:e,nonce:t,email:me.email,billingName:Pe||void 0,onBuyerIdentityReady:m,billingApiUrl:ue,intentKind:z>0?"payment":"setup",expressMethods:Ur,onTokenizedBody:gn,onErrorChange:fe,onButtonClick:re,onDecline:c,onTechnicalFailure:zr,runBeforeButtonClick:Gn,onLoadStateChange:gi,placeholderBorderRadius:_r})}),uo&&(0,l.jsx)(Ps,{sessionId:e,nonce:t,email:me.email,billingName:[me.firstName,me.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:ue,paymentElementMethods:zo,stripeInstance:xe,paymentElementBaseOptions:wa,onTokenizedBody:gn,onErrorChange:fe,onButtonClick:re,onDecline:c,runBeforeButtonClick:Gn,onLoadStateChange:vi,isProcessing:lt,submitButtonColor:Tr,submitButtonBorderRadius:Ft,submitButtonStyle:v.submitButton,themeId:ve,onExpandApm:te,expandedApmMethod:Et,buttonAppearance:{backgroundColor:v.cardButton?.backgroundColor,borderColor:v.cardInputBorder,textColor:v.cardButton?.color,borderRadius:_r}})]}),Ie&&(Ys||Hs||Ws)&&(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"}})]}),Ie&&Fi]})}var S=require("react/jsx-runtime"),Lr=44,oi="flopay_checkout_saved_payment_resume",ya=new Map,pa=new Map;function _s(e,t){t.settled&&t.consumers===0&&ya.get(e)===t&&ya.delete(e)}function tc(e,t,n){let r=pa.get(e);if(r&&(!r.sdkGeneratedIdempotencyKey||!t||r.sdkGeneratedIdempotencyKey===t))return r.attempt;let o=n(),i={attempt:o,sdkGeneratedIdempotencyKey:t};pa.set(e,i);let d=()=>{pa.get(e)===i&&pa.delete(e)};return o.then(d,d),o}function Bo(e){return new Promise(t=>setTimeout(t,e))}function ma(e,t,n){let r=Zo({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:Se.SDK_VERSION,enabled:t!==!1});return r.beginCheckout(n),r}function Fo(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function Wa(e,t,n,r,o){let i=ma(e,t,n);i.error({errorCode:r,stage:o,paymentMethodCategory:"unknown",...o==="session_read"?{requestCategory:"session_read"}:{}}),Fo(i)}function nc(e){return e.type==="validation_error"||e.code==="checkout_session_not_found"||e.code==="checkout_session_expired"||e.code==="checkout_session_completed"||e.code==="session_auto_completed"}function ni(e){let t=e?.data.paypal?.publishableKey;if(t)return{clientId:t,environment:e?.data.paypal?.environment,providerObjectType:e?.data.paypal?.providerObjectType}}function Ga(e){return!e||e.data.stripe?.publishableKey?!1:!!ni(e)?.clientId}function br(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function rc(){if(!br())return null;try{let e=window.sessionStorage.getItem(oi);return e?JSON.parse(e):null}catch{return null}}function Ts(e){if(br())try{window.sessionStorage.setItem(oi,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function Ja(){if(br())try{window.sessionStorage.removeItem(oi)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}var ai=":idempotency-key";function As(e,t){if(!br())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 Xa(e,t,n,r){if(br())try{window.sessionStorage.setItem(e,JSON.stringify(r?{canonicalIdentity:t,sid:n,nonce:r}:{canonicalIdentity:t,sid:n}))}catch(o){console.warn("[FloPayCheckout] Failed to persist checkout session cache.",o)}}function ri(e,t){if(br())try{As(e,t)&&window.sessionStorage.removeItem(e)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout session cache.",n)}}function Bs(e,t){if(!br())return null;try{let n=window.sessionStorage.getItem(e+ai);if(!n)return null;try{let r=JSON.parse(n);return typeof r=="string"?r?{idempotencyKey:r}:null:!r||typeof r.idempotencyKey!="string"||!r.idempotencyKey||"canonicalIdentity"in r&&r.canonicalIdentity!==t?null:{..."canonicalIdentity"in r?{canonicalIdentity:t}:{},idempotencyKey:r.idempotencyKey}}catch{return{idempotencyKey:n}}}catch{return null}}function Za(e,t,n){if(br())try{window.sessionStorage.setItem(e+ai,JSON.stringify({canonicalIdentity:t,idempotencyKey:n}))}catch(r){console.warn("[FloPayCheckout] Failed to persist checkout idempotency key.",r)}}function Qa(e,t){if(ri(e,t),!!br())try{Bs(e,t)&&window.sessionStorage.removeItem(e+ai)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout idempotency key.",n)}}function oc(){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 xs(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 ei(e,t){return e?"custom_layout":t==="buttons"?"buttons_layout":"default_layout"}function ac(e,t){return e?"unknown":t==="buttons"?"buttons":"embedded"}function Ms(e){return e?.gateways?.stripe?"stripe":e?.gateways?.paypal?"paypal":void 0}function ic(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 ti(e,t){return`${e}:${t.totalAmount??""}:${t.overrideAmount??""}:${t.quantity??1}:${t.currency??""}`}function sc(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 Do(e,t=!1){let n=e?.account?.email?.trim().toLowerCase()??"",r={c:e?.clientId,cur:e?.currency??"",captureMethod:e?.captureMethod??"",a:{e:n,u:n?"":e?.account?.userId??"",country:e?.account?.country??""},successUrl:e?.successUrl,cancelUrl:e?.cancelUrl,p:e?.products?.map(o=>ti(`${o.type??""}:${o.code??o.providerItemId??o.providerPlanId??""}`,o)).sort(),i:e?.items?.map(o=>ti(o.code??o.providerItemId??"",o)).sort(),s:e?.subscriptions?.map(o=>ti(o.code??o.providerPlanId??"",o)).sort(),couponCodes:e?.couponCodes?[...e.couponCodes].sort():void 0,checkoutMetadata:sc(e?.checkoutMetadata),...t?{tagsData:e?.tagsData,utmMetadata:e?.utmMetadata,tokenizedData:e?.tokenizedData,checkoutMode:e?.checkoutMode??"full"}:{}};return JSON.stringify(r)}function lc(e,t=!1){let n=Do(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 cc(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,Se.resolveSessionCurrency)(t.currency,t.items,t.subscriptions,t.products);if(!o||e.currency.toUpperCase()!==o.toUpperCase())return!1;let i=(t.products??(0,Se.foldIntoProducts)(t.items,t.subscriptions)).map(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,f)=>`${y.code}:${y.type??""}`.localeCompare(`${f.code}:${f.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,f)=>`${y.code}:${y.type??""}`.localeCompare(`${f.code}:${f.type??""}`));if(i.length!==d.length)return!1;for(let[y,f]of i.entries()){let g=d[y];if(g===void 0||f.code!==g.code||f.type!==void 0&&f.type!==g.type||f.quantity!==g.quantity||f.totalAmount!==g.totalAmount||f.overrideAmount!==g.overrideAmount||f.currency!==g.currency)return!1}let c=[...t.couponCodes??[]].sort(),h=[...e.coupons??[]].sort();return c.length===h.length&&c.every((y,f)=>y===h[f])}function fa({sessionId:e,nonce:t,createSession:n,billingApiUrl:r,telemetry:o,appearance:i,locale:d,loading:c,error:h,onComplete:y,onError:f,onInstrument:g,onDecline:p,onCountryChange:w,onZipChange:F,showPayPal:L=!0,showStripe:he=!0,enabledPaymentMethods:q,showApplePay:P=!0,showGooglePay:ie=!0,debug:O=!1,layout:de,theme:G,buttonsTheme:ve,buttonsStyles:Ve,cardButtonContent:we,cardBackButtonContent:wt,cardTitleContent:qe,showSecurityFooter:Me,onButtonClick:Ae,onBeforeButtonClick:se,enableAVS:re,cardFieldOrder:D,cardPreFormSlot:Be,avsLayout:Fe,className:Q,initialErrorMessage:Ee=null,children:be,checkoutMode:x,confirmLabel:Y,renderConfirmButton:ke,onSessionCompleted:ge}){let ne=(0,Se.resolveBillingApiUrl)(r),Ne=(0,C.useMemo)(()=>(0,Se.resolveTheme)(G),[G]),ot=i??Ne?.appearance,ft=n?"embedded_checkout":"standard_checkout",Ye=ei(be,de),[oe,$]=(0,C.useState)(null),[z,We]=(0,C.useState)(null),Je=(0,C.useRef)(null),[ye,at]=(0,C.useState)(null),k=(0,C.useRef)(null),[E,Oe]=(0,C.useState)(null),pe=(0,C.useMemo)(()=>n?Do(n):"",[n]),le=n?`create:${pe}`:`session:${e??""}`,rt=Ms(E),ze=(0,C.useRef)(new Set),Xe=(0,C.useRef)(le),At=(0,C.useRef)(le);wo(()=>{At.current=le,Xe.current!==le&&(Xe.current=le,ze.current.clear())},[le]);let I=(0,C.useCallback)(N=>{if(At.current===le){if(Na.has(N.name)){if(ze.current.has(N.name))return;ze.current.add(N.name)}nt(()=>g?.(N))}},[le,g]),ee=Qr(I,le),vt=(0,C.useRef)(!1),Ze=(0,C.useCallback)(N=>{if(vt.current)return;let U=N.gateway||!rt?N:{...N,gateway:rt};I(U)},[I,rt]);(0,C.useEffect)(()=>{ee({class:"lifecycle",name:"checkout.mount"})},[ee]);let[Jt,Kt]=(0,C.useState)(e??""),M=e??Jt,pt=n?"":M,[Rt,it]=(0,C.useState)(!0),[kt,pn]=(0,C.useState)(null),[en,mn]=(0,C.useState)("full"),[Nt,bn]=(0,C.useState)(!1),[Ht,mt]=(0,C.useState)(Ee),[Qe,yt]=(0,C.useState)(null),[tn,tt]=(0,C.useState)(null),[Xt,Zt]=(0,C.useState)(!1),[nn,zt]=(0,C.useState)(void 0),[$t,Pn]=(0,C.useState)(""),[rn,Un]=(0,C.useState)(!1),[on,_n]=(0,C.useState)(!1),[an,ce]=(0,C.useState)(!1),Cn=(0,C.useRef)(0),Qn=(0,C.useRef)(void 0),[er,Pr]=(0,C.useState)("loading"),[kr,Ir]=(0,C.useState)(0),W=(0,C.useRef)(!1),Ie=(0,C.useRef)(!1),Yt=(0,C.useRef)(!1),sn=(0,C.useRef)(null),Te=(0,C.useMemo)(()=>({checkoutMode:x??en,layout:ac(be,de)}),[x,be,en,de]),qn=(0,C.useRef)(y);qn.current=y;let Tn=(0,C.useRef)(f);Tn.current=f;let Bt=(0,C.useRef)(p);Bt.current=p,(0,C.useEffect)(()=>{qt(z)?.setCheckoutContext(Te),ye&&ye!==z&&qt(ye)?.setCheckoutContext(Te)},[z,ye,Te]);let ln=(0,C.useRef)(ge);ln.current=ge;let Rr=(0,C.useCallback)(N=>{Pr(N),!(N!=="exhausted"||Yt.current)&&(Yt.current=!0,Tn.current?.(new Se.FloPayError("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),Er=(0,C.useCallback)(()=>{Pr("retrying"),Ir(N=>N+1)},[]);(0,C.useEffect)(()=>{Pr("loading"),Ir(0),Yt.current=!1},[M]),(0,C.useEffect)(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:Se.SDK_VERSION,checkout_type:ft,checkout_layout:Ye,billing_api_url:ne})},[Ye,ft,ne]);let Sn=(0,C.useMemo)(()=>n?Do(n,!0):"",[n]),lr=(0,C.useMemo)(()=>$t===Sn?nn:void 0,[nn,$t,Sn]),$n=(0,C.useMemo)(()=>n?Fa(n,lr):void 0,[n,lr]),xn=x??$n?.checkoutMode??"full",bt=(0,C.useMemo)(()=>$n?{...$n,checkoutMode:xn}:void 0,[$n,xn]);(0,C.useEffect)(()=>{zt(void 0),Pn(Sn),Qn.current=void 0,ce(!1)},[Sn]),(0,C.useEffect)(()=>{mt(Ee)},[Ee]);let tr=(0,C.useCallback)((N,U,te)=>{nt(()=>{Bt.current?.(Vt(N,U,te))})},[]),wn=(0,C.useCallback)(async(N,U)=>{mt(null),tt(null),Zt(!1),yt("processing");let te=U?.sessionId??N.id,ae=Ms(N),Ke=Je.current??k.current,Z=qt(Ke),J=Ke?null:ma(ne,o,Te),R={log:A=>{Z?Z.log(A):J?.log(A)},error:A=>{Z?Z.error(A):J?.error(A)},terminal:A=>{Z?Z.terminal(A):J?.terminal(A)},performance:A=>{Z?Z.performance(A):J?.performance(A)},now:()=>Z?.now()??J?.now()??0,elapsed:A=>Z?.elapsed(A)??Math.max(0,(J?.now()??A)-A)},B=R.now(),X=!!(U?.initialAutoProcessingError||U?.initialAutoProcessingPending),gt=!1,et,ue=()=>{gt||(gt=!0,X=!0,et=R.now(),R.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),R.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},st=!1,T=()=>{st||(st=!0,R.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),R.performance({stage:"processing",durationMs:R.elapsed(B),durationMode:"machine",paymentMethodCategory:"saved"}),et!==void 0&&R.performance({stage:"recovery",durationMs:R.elapsed(et),durationMode:"machine",paymentMethodCategory:"saved"}))};R.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),vt.current=!0;try{R.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"})}finally{vt.current=!1}ee({class:"lifecycle",name:"payment.processing.started",provider:ae}),X&&ue();let m;try{let A=as(U?.initialAutoProcessingError),j;if(A)ue(),A.type==="paypal_redirect_required"&&sn.current?.publishableKey&&Ts({sessionId:te,publishableKey:sn.current.publishableKey,paypalPublishableKey:sn.current.paypalPublishableKey}),j=await ra(A,{flopay:Je.current,paypalFlopay:k.current,attempt3DS:U?.attempt3DS,billingApiUrl:ne,sessionId:te,session:N,telemetry:!1}),A.type==="paypal_redirect_required"&&Ja();else if(U?.initialAutoProcessingPending){let He=(await new Dr.PaymentAPI(ne,{telemetry:!1}).waitForCheckoutSessionCompletion(U.initialAutoProcessingPending.sessionId,{initialDelayMs:U.initialAutoProcessingPending.retryAfterMs})).data.session;if(!Gr(He))throw Go(He);j=Ar(He,te)}else{if(U?.initialAutoProcessingError)throw wr(U.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:U.initialAutoProcessingError.checkoutMethod});if(U?.fromCreateSession)return U?.fallbackToFull&&(mn("full"),xs("full")),!1;{let v=await ro({billingApiUrl:ne,sessionId:te,session:N,telemetry:!1});v.type==="success"?j=v.result:(ue(),v.type==="paypal_redirect_required"&&sn.current?.publishableKey&&Ts({sessionId:te,publishableKey:sn.current.publishableKey,paypalPublishableKey:sn.current.paypalPublishableKey}),j=await ra(v,{flopay:Je.current,paypalFlopay:k.current,attempt3DS:U?.attempt3DS,billingApiUrl:ne,sessionId:te,session:N,telemetry:!1}),v.type==="paypal_redirect_required"&&Ja())}}te&&to(te),T(),X&&(R.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),R.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),R.terminal({outcome:j.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),Zt(j.status==="authorized"),yt("success"),await Bo(1200),m=()=>qn.current?.(j)}catch(A){let j=xo(A),v=j.checkoutMethod??To;mt(j.message),tt(j.message),Zt(!1),U?.fallbackToFull&&(R.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),mn("full"),xs("full")),T();let V=j.statusCode===void 0?void 0:(0,Se.telemetryStatusClass)(j.statusCode,"unknown"),He=V==="4xx"?{requestCategory:"process_payment",statusClass:V}:{},Qt=V===void 0||V==="4xx";if(Qt&&(j.telemetryOutcome==="payment_declined"||!!(j.declineCode||j.code?.toLowerCase().includes("declin"))))R.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...He});else if(Qt&&(j.telemetryOutcome==="validation_rejected"||j.type==="validation_error"))R.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...He});else{let me=(0,Se.classifyTelemetryFailure)(A,X?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown"),Pe=j.telemetryRequestCategory??"process_payment";vt.current=!0;try{R.error({...me,...j.telemetryFailureCategory?{failureCategory:j.telemetryFailureCategory}:{},stage:X?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:Pe})}finally{vt.current=!1}ee({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:Pe,provider:ae})}return nt(()=>Tn.current?.(j)),tr(v,j,{code:j.code,declineCode:j.declineCode}),yt("error"),await Promise.allSettled([Bo(1500),U?.ensureProvidersReady?U.ensureProvidersReady():Promise.resolve()]),X&&(R.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),R.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{T(),J&&Fo(J),yt(null),tt(null)}return nt(m),!0},[tr,ee,ne,o,Te]);(0,C.useEffect)(()=>{if(typeof window>"u"||Ie.current)return;let N=new URLSearchParams(window.location.search),U=N.get("payment_intent_client_secret");if(!U)return;let te=rc();te&&(Ie.current=!0,(async()=>{let ae,Ke=0;mt(null),tt(null),yt("processing"),bn(!0);try{if(N.get("redirect_status")==="failed")throw Object.assign(new Se.FloPayError("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:Z,paypalFlopay:J}=await aa({publishableKey:te.publishableKey,paypalPublishableKey:te.paypalPublishableKey,billingApiUrl:ne,locale:d,telemetry:o});ae=qt(J??Z),Ke=ae?.now()??0,ae?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),ae?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let R=(J??Z)?.getRawProvider();if(!R)throw Object.assign(new Se.FloPayError("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:B,error:X}=await R.retrievePaymentIntent(U);if(X)throw Object.assign(new Se.FloPayError(X.message??"Failed to retrieve PayPal payment status.","api_error",{code:X.code}),{checkoutMethod:"paypal"});let gt=ji(B?.status);if(!B||gt==="failed")throw Object.assign(new Se.FloPayError("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let et=typeof B.payment_method=="string"?B.payment_method:B.payment_method?.id,ue=gt;if(te.sessionId){let m=(await new Dr.PaymentAPI(ne,{telemetry:!1}).getUnifiedCheckoutSession(te.sessionId)).data.session;if(m&&m.status!=="complete"){let A=await ro({billingApiUrl:ne,sessionId:te.sessionId,session:m,telemetry:!1,tokenizedData:{id:et??B.id,type:"card",threeDSecureActionResultTokenId:B.id,isPaypal:!0}});if(A.type!=="success")throw Object.assign(new Se.FloPayError("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});ue=A.result.status}}te.sessionId&&to(te.sessionId),ae?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),ae?.performance({stage:"redirect_resume",durationMs:ae.elapsed(Ke),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),ae?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),yt("success"),await Bo(1200),nt(()=>qn.current?.({status:ue,paymentIntentId:B.id,paymentMethodId:et,checkoutMethod:"paypal"}))}catch(Z){let J=xo(Z),R=J.checkoutMethod??"paypal",B=!!(J.declineCode||J.code?.toLowerCase().includes("declin"));if(ae)ae.performance({stage:"redirect_resume",durationMs:ae.elapsed(Ke),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),B?ae.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):ae.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(B){let X=ma(ne,o,Te);X.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),Fo(X)}else Wa(ne,o,Te,"REDIRECT_RESUME_FAILED","redirect_resume");mt(J.message),tt(J.message),nt(()=>Tn.current?.(J)),tr(R,J,{code:J.code,declineCode:J.declineCode}),yt("error"),await Bo(1500)}finally{Ja(),oc(),yt(null),tt(null),bn(!1)}})())},[tr,d,ne,o,Te]);let jn=(0,C.useRef)(null),yn=(0,C.useMemo)(()=>bt?Do(bt):"",[bt]),Vn=(0,C.useRef)(bt);Vn.current=bt,(0,C.useEffect)(()=>{Kt(e??"")},[e]),(0,C.useEffect)(()=>{W.current=!1,mt(Ee),tt(null),Zt(!1),yt(null)},[yn,Ee,e]);async function Kn(N,U,te){let ae=ma(ne,o,Te),Ke=new Dr.PaymentAPI(ne,{telemetry:!1}),Z=!1;try{let J=N.idempotencyKey===void 0?void 0:(0,Se.resolveIdempotencyKey)(N.idempotencyKey),R=As(U,te),B=Bs(U,te);R?.canonicalIdentity===te&&B&&B.canonicalIdentity===void 0&&(Za(U,te,B.idempotencyKey),B={...B,canonicalIdentity:te});let X=J??(B?.canonicalIdentity===te?B.idempotencyKey:void 0),gt,et=!1;ae.log({name:R?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let ue=R?.sid??null,st=null,T,m,A=!1;if(ue)try{st=await Ke.getUnifiedCheckoutSession(ue,R?.nonce),R&&R.canonicalIdentity===void 0&&(cc(st.data.session,N)?(Xa(U,te,ue,R.nonce??st.data.session?.clientSecret),B&&B.canonicalIdentity===void 0&&(Za(U,te,B.idempotencyKey),X??(X=B.idempotencyKey))):(Qa(U,te),B=null,X=J,ue=null,st=null));let v=st?.data.session?.status,V=st?.data.session,He=V?.clientSecret||R?.nonce;if(ue&&V?.buyerIdentified===!1&&He&&(m=Wr(Ke,ue,He,N.account)),ue&&st&&v==="complete"){if(Oa(ue))return{sid:ue,result:st};Qa(U,te),ue=null,st=null,et=!0}}catch{ae.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),R?.canonicalIdentity===void 0?(Qa(U,te),X=J):ri(U,te),ue=null}if(!ue){!J&&(et||!X)&&(X=(0,Se.resolveIdempotencyKey)(),gt=X),X&&Za(U,te,X);let v=ae.now(),V=0;ae.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let He={...N,idempotencyKey:X,avsCheck:!!re,avsConfig:typeof re=="object"?re:void 0,checkoutType:"embedded_checkout",checkoutLayout:ei(be,de)};Object.defineProperty(He,Dr.SESSION_CREATE_TELEMETRY,{configurable:!1,enumerable:!1,value:{onAttempt:ct=>{V=Math.max(V,ct)}}});let Qt=()=>{ae.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:"2xx"}),ae.performance({stage:"session_create",durationMs:ae.now()-v,durationMode:"machine",requestCategory:"session_create",attempt:V,statusClass:"2xx"})},lt=ct=>{let me=(0,Se.classifyTelemetryFailure)(ct,"CHECKOUT_SESSION_CREATE_FAILED","unknown");ae.performance({stage:"session_create",durationMs:ae.now()-v,durationMode:"machine",requestCategory:"session_create",attempt:V,statusClass:me.statusClass}),ct instanceof Se.FloPayError&&ct.type==="validation_error"?ae.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown"}):me.statusClass==="4xx"?ae.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create",statusClass:"4xx"}):(ae.error({...me,stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create"}),ee({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_create"}))};try{if((0,Se.isDetachedSessionEligible)(He)){let ct=await Ke.createDetachedSession(He);ct.claimed.catch(()=>{}),st=ct.shell,ue=ct.sessionId,m=ct.claim,T=ct.claimed.then(me=>{let Pe=me.data.session?.id??ct.sessionId;return Pe&&Xa(U,te,Pe,me.data.session?.clientSecret??ct.nonce),Qt(),me},me=>{throw ri(U,te),lt(me),me}).finally(()=>Fo(ae)),T.catch(()=>{}),Z=!0,ae.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),ae.performance({stage:"session_shell",durationMs:ae.now()-v,durationMode:"machine",requestCategory:"session_create",attempt:V,statusClass:"2xx",paymentMethodCategory:"card"})}else st=await Ke.createAndFetchSession(He),Qt()}catch(ct){throw lt(ct),ct}ue=st.data.session?.id??ue??"",ue&&!T&&Xa(U,te,ue,st.data.session?.clientSecret)}let j=st?.data.session;return!m&&ue&&j?.buyerIdentified===!1&&j.clientSecret&&(m=Wr(Ke,ue,j.clientSecret,N.account)),{sid:ue??"",result:st,sdkGeneratedIdempotencyKey:gt,...T?{claimed:T}:{},...m?{claim:m}:{},...A?{claimRequiresIdentity:!0}:{}}}finally{Z||Fo(ae)}}let dt=(0,C.useRef)(Kn);wo(()=>{dt.current=Kn},[Kn]);let kn=(0,C.useCallback)(async(N,U)=>{let te=Vn.current;if(!te)throw new Se.FloPayError("createSession is required to bootstrap checkout.","validation_error");let ae=Fa(te,N),Ke=Do(ae),Z=lc(ae),J=ya.get(Ke);if(!J){let X={canonicalIdentity:Ke,promise:dt.current(ae,Z,Ke),consumers:0,settled:!1};J=X,ya.set(Ke,X);let gt=()=>{X.settled=!0,_s(Ke,X)};X.promise.then(gt,gt)}J.consumers+=1;let R=!1,B=()=>{R||(R=!0,J.consumers-=1,_s(Ke,J))};U?.(B);try{let X=await J.promise;jn.current=Ke,N&&(Pn(Sn),zt(V=>Ui(V,N)));let{sid:gt,result:et,claimed:ue,claim:st,claimRequiresIdentity:T}=X;if(Qn.current=st,ce(T===!0),$(et),et.data.session&&Oe(et.data.session),gt&&Kt(gt),ue){Cn.current+=1;let V=Cn.current;_n(!0),ue.then(He=>{Cn.current===V&&($(He),He.data.session&&Oe(He.data.session),_n(!1),ce(!1))},He=>{Cn.current===V&&(_n(!1),ce(!1),pn(He instanceof Se.FloPayError?He:new Se.FloPayError(He instanceof Error?He.message:"Failed to create session","api_error")))})}else Cn.current+=1,_n(!1),ce(!1);let{publishableKey:m,paypalPublishableKey:A}=oa(et),{flopay:j,paypalFlopay:v}=await aa({publishableKey:m,paypalPublishableKey:A,billingApiUrl:ne,locale:d,telemetry:o});return Je.current=j,We(j),k.current=v,at(v),it(!1),X}catch(X){throw jn.current===Ke&&(jn.current=null),X}finally{U||B()}},[Sn,d,ne,o]),Mn=(0,C.useRef)(wn);Mn.current=wn;let In=(0,C.useRef)(kn);In.current=kn;let Hn=(0,C.useCallback)(async N=>{if(!ic(N)||rn)return{sessionId:Jt,session:E};Un(!0);try{let U=await kn(N);return{sessionId:U.sid,session:U.result.data.session??null}}finally{Un(!1)}},[kn,rn,Jt,E]),Ue=(0,C.useCallback)(async N=>{let U=Qn.current;if(!U)return;let te=Cn.current,ae=await U(N);Cn.current===te&&($(ae),ae.data.session&&Oe(ae.data.session))},[]);(0,C.useEffect)(()=>{let N=!1,U;pn(null);let te=Vn.current;if(yn&&te)return mn(xn),it(!1),jn.current===yn?()=>{N=!0}:(Oe(qi(te,x)),(async()=>{let Z=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),J=xn==="auto"&&!W.current&&!Z;J&&(mt(null),tt(null),yt("processing"));try{let R=await In.current(void 0,et=>{U=et}),B=R.result.data.session??null;sn.current=oa(R.result);let X=Ga(R.result),gt=Oa(R.sid||B?.id);if(!N&&J&&B&&!X&&!gt){W.current=!0,await tc(yn,R.sdkGeneratedIdempotencyKey,()=>Mn.current(B,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:R.result.autoProcessingError,initialAutoProcessingPending:R.result.autoProcessingPending,autoProcessingAttempted:R.result.autoProcessingAttempted,sessionId:R.sid||B.id}));return}!N&&J&&((X||gt)&&(W.current=!0),yt(null),tt(null))}catch(R){if(N)return;let B=Wo(R);if(J&&B==="session_auto_completed"){W.current=!0,yt("success"),await Bo(1200),N||(nt(()=>{qn.current?.({status:"succeeded"})}),yt(null),tt(null));return}J&&(yt(null),tt(null));let X=R instanceof Se.FloPayError?R:new Se.FloPayError(R instanceof Error?R.message:"Failed to create session","api_error");pn(X)}finally{U?.(),U=void 0}})(),()=>{N=!0,U?.()});it(!0);async function ae(){let Z=!1;try{let J=new Dr.PaymentAPI(ne,{telemetry:!1}),R=await J.getUnifiedCheckoutSession(M,t);if(N)return;$(R);let B=R.data.session??null;if(Oe(B),!B)throw new Se.FloPayError("No session data returned","api_error");let X=B.checkoutMode;if(X==="setup")throw new Se.FloPayError("This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.","validation_error",{code:"InvalidCardSetupSurface",param:"sessionId"});if(B.status==="authorized"){it(!1),nt(()=>{qn.current?.(Ar(B,M)),ln.current?.(B.successUrl??"")});return}if(B.status==="complete"){it(!1),nt(()=>{ln.current?.(B.successUrl??"")});return}if(B.status==="expired")throw Yo(B);Z=!0;let gt=x??X??"full";mn(gt),Cn.current+=1;let et=B.clientSecret||t;Qn.current=B.buyerIdentified===!1&&et?Wr(J,M,et,{...B.customer?.id?{userId:B.customer.id}:{}}):void 0,_n(!1),ce(!1);let ue=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),st=Ga(R);if(gt==="auto"&&!W.current&&!ue&&!st){W.current=!0;let T=Ke(R);try{if(await Mn.current(B,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>T,sessionId:M||B.id}),N)return;await T,N||it(!1);return}catch{if(N)return;await T,N||it(!1);return}}await Ke(R),N||it(!1)}catch(J){if(N)return;Z&&ee({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"}),J instanceof Se.FloPayError?!Z&&!nc(J)&&Wa(ne,o,Te,"NETWORK_REQUEST_FAILED","session_read"):Wa(ne,o,Te,"INTERNAL_SDK_ERROR","checkout_mount");let R=J instanceof Se.FloPayError?J:new Se.FloPayError(J instanceof Error?J.message:"Failed to initialize checkout","api_error");pn(R),it(!1)}}async function Ke(Z){let{publishableKey:J,paypalPublishableKey:R}=oa(Z);sn.current={publishableKey:J,paypalPublishableKey:R};let{flopay:B,paypalFlopay:X}=await aa({publishableKey:J,paypalPublishableKey:R,billingApiUrl:ne,locale:d,telemetry:o});Je.current=B,We(B),k.current=X,at(X)}return ae(),()=>{N=!0}},[x,yn,xn,pt,t]);let cn=(0,C.useCallback)(async()=>{if(!(Nt||!E)){bn(!0),mt(null);try{await wn(E,{attempt3DS:!0,fallbackToFull:!0,sessionId:M||E.id})}finally{bn(!1)}}},[M,Nt,wn,E]),Et=ni(oe),cr=Ga(oe),dr=(0,C.useMemo)(()=>{if(!(!oe||!E||!oe.data.stripe?.publishableKey))return{billingApiUrl:ne}},[oe,E,ne]),ur=!!(n&&!be&&de==="buttons"&&se&&xn==="full"),Rn=(0,C.useMemo)(()=>({session:E,loading:Rt,error:kt,checkoutMode:en,inlineSessionDraft:bt,applyInlineSessionPatch:ur?Hn:void 0,inlineSessionPatchProcessing:rn,claimPending:on,claimRequiresIdentity:an,claimBuyerIdentity:Ue}),[E,Rt,kt,en,bt,ur,Hn,rn,on,an,Ue]),Yn=!!n&&de==="buttons"&&!cr&&(!z||!dr),Ut=Qe?(0,S.jsx)(Nn,{status:Qe,errorMessage:tn,authorized:Xt}):null;if(Rt){if(c)return(0,S.jsxs)(S.Fragment,{children:[c,Ut]});if(de==="buttons"){let N=Ne?.buttonsLayout?.cardButton?.borderRadius??Ne?.appearance.variables?.borderRadius??8,U=te=>(0,S.jsx)("div",{style:{height:te,borderRadius:N,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return(0,S.jsxs)(S.Fragment,{children:[(0,S.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[L&&U(Lr),he&&(P||ie)&&U(Lr),he&&U(Lr),(0,S.jsx)("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),Ut]})}return(0,S.jsxs)(S.Fragment,{children:[(0,S.jsxs)("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[(0,S.jsx)("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),(0,S.jsx)("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),Ut]})}return kt?h?(0,S.jsx)(Jn.Provider,{value:Rn,children:h(kt)}):(0,S.jsx)(Jn.Provider,{value:Rn,children:(0,S.jsx)("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:kt.message})}):Yn?(0,S.jsxs)(S.Fragment,{children:[(0,S.jsx)(Jn.Provider,{value:Rn,children:(0,S.jsx)(uc,{onButtonClick:Ae,showPayPal:L,showStripe:he,showApplePay:P,showGooglePay:ie,theme:G,buttonsTheme:ve,buttonsStyles:Ve,cardButtonContent:we,cardBackButtonContent:wt,cardTitleContent:qe})}),Ut]}):cr&&E&&Et?(0,S.jsxs)(S.Fragment,{children:[(0,S.jsx)(Jn.Provider,{value:Rn,children:(0,S.jsxs)("div",{className:Q,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Ht&&(0,S.jsx)(eo,{icon:!1,children:Ht}),er==="retrying"&&(0,S.jsx)("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),er==="exhausted"&&(0,S.jsxs)("div",{role:"alert",children:[(0,S.jsx)("div",{children:"PayPal is temporarily unavailable. Please try again."}),(0,S.jsx)("button",{type:"button",onClick:Er,children:"Retry PayPal"})]}),on?c??(0,S.jsx)("div",{role:"status","data-testid":"flopay-paypal-catalog-loading","aria-label":"Preparing PayPal",style:{height:Lr,borderRadius:8,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"},children:(0,S.jsx)("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})}):er!=="exhausted"&&(0,S.jsx)("div",{"aria-hidden":er==="retrying"?!0:void 0,style:er==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:(0,S.jsx)(ts,{sessionId:M,nonce:E.clientSecret||void 0,billingApiUrl:ne,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:Ue,clientId:Et.clientId,environment:Et.environment,currency:(E.currency??"usd").toUpperCase(),isSubscription:E.mode==="subscription",providerObjectType:Et.providerObjectType,onComplete:y,onErrorChange:mt,onDecline:p,onButtonClick:Ae,onInitializationStateChange:Rr,allowAutomaticRetry:kr===0,session:E,telemetry:o,telemetryContext:Te,onInstrument:Ze,debug:O},`${le}:paypal-init-${kr}`)})]})}),Ut]}):!z||!dr?(0,S.jsx)(S.Fragment,{children:Ut}):en==="confirm"?(0,S.jsxs)(S.Fragment,{children:[(0,S.jsx)(Jn.Provider,{value:Rn,children:(0,S.jsx)(Eo,{flopay:z,paypalFlopay:ye,options:dr,onInstrument:Ze,children:(0,S.jsxs)("div",{className:Q,children:[Ht&&(0,S.jsx)("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:Ht}),ke?ke({onConfirm:cn,isProcessing:Nt}):(0,S.jsx)("button",{type:"button",onClick:cn,disabled:Nt,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:Nt?"not-allowed":"pointer",opacity:Nt?.6:1},children:Nt?"Processing...":Y??"Confirm Purchase"})]})},le)}),Ut]}):(0,S.jsxs)(S.Fragment,{children:[(0,S.jsx)(Jn.Provider,{value:Rn,children:(0,S.jsx)(Eo,{flopay:z,paypalFlopay:ye,options:dr,onInstrument:Ze,children:be?(0,S.jsxs)(S.Fragment,{children:[Ht&&(0,S.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,S.jsx)(dc,{sessionId:M,nonce:E?.clientSecret||void 0,billingApiUrl:ne,session:E,children:be})]}):(0,S.jsx)(ua,{sessionId:M,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,Se.buildCheckoutDisplayData)(E).total*100):0,currency:E?.currency?.toLowerCase()??"usd",onComplete:y,onError:f,onDecline:p,error:Ht,onErrorChange:mt,showPayPal:L,showStripe:he,enabledPaymentMethods:q??oe?.data.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:oe?.data.stripe?.enabledPaymentMethodCountries,showApplePay:P,showGooglePay:ie,layout:de,theme:G,buttonsTheme:ve,buttonsStyles:Ve,appearance:ot,cardButtonContent:we,cardBackButtonContent:wt,cardTitleContent:qe,onButtonClick:Ae,onBeforeButtonClick:se,onBuyerIdentityReady:Ue,enableAVS:re,...D?{cardFieldOrder:D}:{},...Be?{cardPreFormSlot:Be}:{},avsLayout:Fe,country:E?.customer?.country,city:E?.customer?.city,state:E?.customer?.state,onCountryChange:w,onZipChange:F,avsCheck:!!re,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:ei(be,de),className:Q,directPaypal:ni(oe),isSubscription:E?.mode==="subscription",session:E,dataAttachmentPending:on,dataAttachmentRequiresIdentity:an,debug:O})},le)}),Ut]})}function dc({sessionId:e,nonce:t,billingApiUrl:n,session:r,children:o}){return(0,S.jsx)(S.Fragment,{children:C.default.Children.map(o,i=>{if(!C.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:C.default.cloneElement(i,c)})})}function uc({onButtonClick:e,showPayPal:t,showStripe:n=!0,showApplePay:r,showGooglePay:o,theme:i,buttonsTheme:d,buttonsStyles:c,cardButtonContent:h,cardBackButtonContent:y,cardTitleContent:f}){let[g,p]=(0,C.useState)(!1),w=(0,C.useMemo)(()=>(0,Se.resolveTheme)(i),[i]),F=(0,C.useMemo)(()=>{let P=w?.buttonsLayout??(0,Se.resolveButtonsLayoutTheme)(d);return c?{...P,...c,cardButton:{...P.cardButton,...c.cardButton},cardFormContainer:{...P.cardFormContainer,...c.cardFormContainer},backButton:{...P.backButton,...c.backButton},backButtonIcon:{...P.backButtonIcon,...c.backButtonIcon},submitButton:{...P.submitButton,...c.submitButton},title:{...P.title,...c.title}}:P},[w,d,c]),L=w?.buttonsLayout?.cardButton?.borderRadius??w?.appearance.variables?.borderRadius??8,he=P=>(0,S.jsx)("div",{style:{height:P,borderRadius:L,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),q=h===void 0?{boxSizing:"border-box",height:Lr,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(g){let P=F.cardInputBorder??"#e5e7eb",ie=F.cardInputBackground??"white",O=Kr(y),de=Kr(f);return(0,S.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,S.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,S.jsxs)("button",{type:"button",onClick:()=>p(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:O?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,S.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...F.backButtonIcon},children:(0,S.jsx)("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,S.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,S.jsx)(Yr,{content:y})]}),de?(0,S.jsx)("div",{style:{flex:1}}):(0,S.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...F.title},children:(0,S.jsx)(vo,{content:f})})]}),(0,S.jsx)("div",{style:{backgroundColor:ie,border:`1px solid ${P}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:(0,S.jsx)("div",{style:{width:"60%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,S.jsxs)("div",{style:{display:"flex"},children:[(0,S.jsx)("div",{style:{flex:1,backgroundColor:ie,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${P}`,borderLeft:`1px solid ${P}`,borderBottomLeftRadius:8,padding:12,height:45},children:(0,S.jsx)("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,S.jsx)("div",{style:{flex:1,backgroundColor:ie,borderTop:"none",borderRight:`1px solid ${P}`,borderBottom:`1px solid ${P}`,borderLeft:`1px solid ${P}`,borderBottomRightRadius:8,padding:12,height:45},children:(0,S.jsx)("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),(0,S.jsx)("div",{style:{backgroundColor:ie,border:`1px solid ${P}`,borderRadius:8,marginTop:8,padding:12,height:45},children:(0,S.jsx)("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,S.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,S.jsx)("style",{children:`
38
+ `}),mo&&mr&&(0,l.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:ke?-2:0},children:[(0,l.jsxs)("button",{type:"button",onClick:j,style:{display:"inline-flex",alignItems:"center",gap:_a?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:b.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...b.backButton},"aria-label":"Back to payment methods",children:[(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",...b.backButtonIcon},children:(0,l.jsx)("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,l.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,l.jsx)(Wr,{content:Ae})]}),Ai?(0,l.jsx)("div",{style:{flex:1}}):(0,l.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:b.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...b.title},children:(0,l.jsx)(vo,{content:Be})})]}),!mo&&!Ai&&(0,l.jsx)("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:Ta,order:ke?-3:0,...b.title},children:(0,l.jsx)(vo,{content:Be})}),ke&&Re&&(0,l.jsx)("div",{style:{order:-2,width:"100%"},children:Re}),ke&&Te&&(0,l.jsxs)("div",{"data-testid":"flopay-vault-identity-fields",style:{order:-1,marginTop:"0.5rem"},children:[(0,l.jsx)("div",{style:{backgroundColor:$r,border:`1px solid ${zn($o)}`,borderRadius:Ut,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:Xe,onChange:a=>{dt("email"),sn.current=a.target.value,Jt(a.target.value)},onPointerDown:()=>dt("email"),onKeyDown:()=>dt("email"),onBlur:()=>{Tn("email")&&or(!0),nn||ba()},disabled:it,required:!0,"aria-invalid":$o||void 0,"aria-describedby":$o?"flopay-buyer-email-error":void 0,"data-testid":"flopay-email",style:{width:"100%",border:"none",outline:"none",background:"transparent",...xa}})}),$o&&(0,l.jsx)("div",{id:"flopay-buyer-email-error",role:"alert","data-testid":"flopay-email-error",style:fo,children:bt.empty?"Email address is required":"Enter a valid email address"})]}),P&&(0,l.jsx)("div",{style:{order:ke?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let a=lt,C=(Z=!1)=>({backgroundColor:$r,border:`1px solid ${zn(Z)}`,borderRadius:Ut,marginTop:"0.5rem",padding:"10px"}),W=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...xa}),Oe=(0,u.getStateOptions)(a);return(0,l.jsxs)(l.Fragment,{children:[(0,u.isAVSFieldVisible)(P.address_line_1,a)&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)("div",{style:C(At("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:hn,onChange:Z=>{dt("line1"),Pt.current.addressLine1=!0,en.current=Z.target.value,Nt(Z.target.value)},onPointerDown:()=>dt("line1"),onKeyDown:()=>dt("line1"),onBlur:()=>Nn("line1"),disabled:it,required:!0,"aria-invalid":At("line1")||void 0,"aria-describedby":At("line1")?"flopay-billing-address-line1-error":void 0,"data-testid":"flopay-address-line1",style:W()})}),At("line1")&&(0,l.jsx)("div",{id:"flopay-billing-address-line1-error",role:"alert","data-testid":"flopay-address-line1-error",style:fo,children:"Street address is required"})]}),(0,u.isAVSFieldVisible)(P.address_line_2,a)&&(0,l.jsx)("div",{style:C(),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:He,onChange:Z=>{Pt.current.addressLine2=!0,Xt.current=Z.target.value,yt(Z.target.value)},disabled:it,"data-testid":"flopay-address-line2",style:W()})}),((0,u.isAVSFieldVisible)(P.city,a)||(0,u.isAVSFieldVisible)(P.state,a))&&(0,l.jsxs)("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[(0,u.isAVSFieldVisible)(P.city,a)&&(0,l.jsx)("div",{style:{flex:1,backgroundColor:$r,borderTop:`1px solid ${zn(At("city"))}`,borderRight:`1px solid ${zn(At("city"))}`,borderBottom:`1px solid ${zn(At("city"))}`,borderLeft:`1px solid ${zn(At("city"))}`,padding:"10px",borderTopLeftRadius:Ut,borderBottomLeftRadius:Ut,...(0,u.isAVSFieldVisible)(P.state,a)?{borderRight:"none",borderTopRightRadius:0,borderBottomRightRadius:0}:{borderRadius:Ut}},children:(0,l.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-city",name:"billing-city",placeholder:"City",autoComplete:"billing address-level2",value:Ct,onChange:Z=>{dt("city"),Pt.current.city=!0,Rn.current=Z.target.value,on(Z.target.value)},onPointerDown:()=>dt("city"),onKeyDown:()=>dt("city"),onBlur:()=>Nn("city"),disabled:it,required:!0,"aria-invalid":At("city")||void 0,"aria-describedby":At("city")?"flopay-billing-city-error":void 0,"data-testid":"flopay-city",style:W()})}),(0,u.isAVSFieldVisible)(P.state,a)&&(0,l.jsx)("div",{style:{flex:1,backgroundColor:$r,borderTop:`1px solid ${zn(At("state"))}`,borderRight:`1px solid ${zn(At("state"))}`,borderBottom:`1px solid ${zn(At("state"))}`,borderLeft:`1px solid ${zn(At("state"))}`,padding:"10px",borderTopRightRadius:Ut,borderBottomRightRadius:Ut,...(0,u.isAVSFieldVisible)(P.city,a)?{borderTopLeftRadius:0,borderBottomLeftRadius:0,borderLeft:`1px solid ${zn(At("state")||At("city"))}`}:{borderRadius:Ut}},children:Oe?(0,l.jsxs)("select",{id:"flopay-billing-state",name:"billing-state",value:ct,onChange:Z=>{dt("state"),Pt.current.state=!0,xt.current=Z.target.value,vn(Z.target.value)},onPointerDown:()=>dt("state"),onKeyDown:()=>dt("state"),onBlur:()=>Nn("state"),disabled:it,autoComplete:"billing address-level1",required:!0,"aria-invalid":At("state")||void 0,"aria-describedby":At("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:{...W(),cursor:"pointer"},children:[(0,l.jsx)("option",{value:"",children:(0,u.getStateLabel)(a)}),Oe.map(Z=>(0,l.jsx)("option",{value:Z.code,children:Z.name},Z.code))]}):(0,l.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-state",name:"billing-state",placeholder:(0,u.getStateLabel)(a),autoComplete:"billing address-level1",value:ct,onChange:Z=>{dt("state"),Pt.current.state=!0,xt.current=Z.target.value,vn(Z.target.value)},onPointerDown:()=>dt("state"),onKeyDown:()=>dt("state"),onBlur:()=>Nn("state"),disabled:it,required:!0,"aria-invalid":At("state")||void 0,"aria-describedby":At("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:W()})})]}),At("city")&&(0,l.jsx)("div",{id:"flopay-billing-city-error",role:"alert","data-testid":"flopay-city-error",style:fo,children:"City is required"}),At("state")&&(0,l.jsxs)("div",{id:"flopay-billing-state-error",role:"alert","data-testid":"flopay-state-error",style:fo,children:[(0,u.getStateLabel)(a)," is required"]}),((0,u.isAVSFieldVisible)(P.country,a)||(0,u.isAVSFieldVisible)(P.postal_code,a))&&(0,l.jsxs)("div",{style:{display:"flex",flexDirection:ve==="column"?"column":"row",gap:ve==="column"?"0.5rem":"0",marginTop:"0.5rem"},children:[(0,u.isAVSFieldVisible)(P.country,a)&&(0,l.jsx)("div",{style:{flex:ve==="row"?1:void 0,backgroundColor:$r,borderTop:`1px solid ${yo}`,borderRight:`1px solid ${yo}`,borderBottom:`1px solid ${yo}`,borderLeft:`1px solid ${yo}`,padding:"10px",...ve==="row"&&(0,u.isAVSFieldVisible)(P.postal_code,a)?{borderRadius:"0",borderTopLeftRadius:Ut,borderBottomLeftRadius:Ut,borderRight:"none"}:{borderRadius:Ut}},children:(0,l.jsx)("select",{id:"flopay-billing-country",name:"billing-country",value:lt,onChange:Z=>{Pt.current.country=!0,Ot.current=Z.target.value,Lt(Z.target.value),rt?.(Z.target.value),xt.current="",vn("")},disabled:it,autoComplete:"billing country","data-testid":"flopay-country",style:{...W(),cursor:"pointer"},children:u.COUNTRY_OPTIONS.map(Z=>(0,l.jsxs)("option",{value:Z.code,children:[Z.flag," ",Z.name]},Z.code))})}),(0,u.isAVSFieldVisible)(P.postal_code,a)&&(0,l.jsx)("div",{style:{flex:ve==="row"?1:void 0,backgroundColor:$r,border:`1px solid ${Zs}`,padding:"10px",...ve==="row"&&(0,u.isAVSFieldVisible)(P.country,a)?{borderRadius:"0",borderTopRightRadius:Ut,borderBottomRightRadius:Ut}:{borderRadius:Ut}},children:(0,l.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-postal-code",name:"billing-postal-code",placeholder:(0,u.getPostalCodeLabel)(lt),autoComplete:"billing postal-code",value:gn,onChange:Z=>{dt("zip"),Pt.current.zip=!0,Kt.current=Z.target.value,In(Z.target.value),gt?.(Z.target.value)},onPointerDown:()=>dt("zip"),onKeyDown:()=>dt("zip"),onBlur:()=>{Tn("zip")&&Ln(!0)},disabled:it,required:un.required,"aria-invalid":jo||void 0,"aria-describedby":jo?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:W()})})]}),jo&&(0,l.jsx)("div",{id:"flopay-billing-postal-code-error",role:"alert","data-testid":"flopay-zip-error",style:fo,children:un.empty?`${(0,u.getPostalCodeLabel)(a)} is required`:Xl(a)})]})})()}),ke&&rl,M&&(0,l.jsx)(eo,{margin:"0.75rem 0",styleOverride:b.errorBanner,children:M})]}),Vo={margin:0,padding:"6px 8px",background:"#eef2ff",border:"1px solid #c7d2fe",borderRadius:6,color:"#111827",font:"11px/1.35 ui-monospace, SFMono-Regular, Menlo, monospace",whiteSpace:"pre-wrap",wordBreak:"break-word"},Ni=a=>Ee?!ge||!ir?(0,l.jsx)("pre",{"data-testid":a,style:Vo,children:"FloPay/DirectPayPal-debug - not enabled"}):(0,l.jsx)("pre",{"data-testid":a,style:Vo,children:["FloPay/DirectPayPal-debug (parent gate)",` showPayPal=${ge}`,` directPaypalConfigured=${ir}`,` inAppBrowserDetected=${String(Uo)}`,` shouldRenderDirectPayPal=${lo}`,` shouldRenderStripePayPal=${co}`,` hasPaypalStripeInstance=${!!Pn}`].join(`
39
+ `)}):null,Oi=a=>Ee?!V||!Me?(0,l.jsx)("pre",{"data-testid":a,style:Vo,children:"FloPay/Stripe-debug - not enabled"}):(0,l.jsx)("pre",{"data-testid":a,style:Vo,children:["FloPay/Stripe-debug (parent gate)",` showStripe=${V}`,` currency=${Ue}`,` amountInCents=${On}`,` enabledPaymentMethods: ${JSON.stringify(S??[])}`,` enabledPaymentMethodsProvided=${io}`,` hasEnabledMethods=${No}`,` expressMethods: ${JSON.stringify(Oo)}`,` walletExpressMethods: ${JSON.stringify(Ur)}`,` paymentElementMethods: ${JSON.stringify(so)}`,` paymentElementMethodsForCurrency: ${JSON.stringify(zo)}`,` hasStripeInstance=${!!Me}`,` shouldRenderWallets=${qr}`,` shouldRenderPaymentElement=${uo}`].join(`
40
+ `)}):null,zi=qe==="apm-expanding"||qe==="apm-form"||qe==="apm-collapsing",Vr;qe==="apm-expanding"?Vr=ys:qe==="apm-collapsing"&&(Vr=fs);let Ko=Mt?_s(Sa,Mt):null;if(G==="buttons"){let a=qe==="buttons"||qe==="expanding"||qe==="apm-expanding",C=qe==="expanding"||qe==="card"||qe==="collapsing",W=$e===void 0?{boxSizing:"border-box",height:sa,padding:"0 1rem"}:{padding:"0.9rem 1rem"},Oe;qe==="expanding"||qe==="apm-expanding"?Oe=Kl:(qe==="collapsing"||qe==="apm-collapsing")&&(Oe=Vl);let Z;return qe==="expanding"?Z=ys:qe==="collapsing"&&(Z=fs),(0,l.jsxs)("form",{onSubmit:Ia,className:p,noValidate:!0,style:{position:"relative"},children:[(0,l.jsx)(Ka,{}),We&&(0,l.jsx)(jn,{status:We,errorMessage:M,authorized:Et}),(0,l.jsxs)("div",{style:{display:"grid"},children:[(0,l.jsxs)("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!a&&!Oe?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!a&&!Oe?Wl:{},...Oe?{animation:Oe,pointerEvents:"none"}:{}},children:[Ni("flopay-direct-paypal-gate-debug"),Oi("flopay-stripe-gate-debug"),lo&&ye&&(0,l.jsxs)(l.Fragment,{children:[X&&(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)(Io,{sessionId:e,nonce:t,billingApiUrl:pe,email:me.email,billingName:be||void 0,onBuyerIdentityReady:m,clientId:ye.clientId,environment:ye.environment,currency:Ue.toUpperCase(),isSubscription:ot,providerObjectType:R,onTokenizedBody:Sn,onComplete:i,onErrorChange:fe,onDecline:c,onTechnicalFailure:zr,onButtonClick:ae,runBeforeButtonClick:er,isProcessing:it,onLoadStateChange:wa,onInitializationStateChange:ka,session:mt,existingOrderId:X?.orderId,debug:Ee},X?.orderId??"fresh")]}),co&&(0,l.jsx)($t.Elements,{stripe:Pn,options:di,children:(0,l.jsx)(bs,{sessionId:e,nonce:t,email:me.email,billingName:be||void 0,onBuyerIdentityReady:m,billingApiUrl:pe,onTokenizedBody:Sn,onErrorChange:fe,isProcessing:it,onButtonClick:ae,onDecline:c,onTechnicalFailure:zr,runBeforeButtonClick:er,onLoadStateChange:gi,placeholderBorderRadius:_r})}),qr?(0,l.jsx)($t.Elements,{stripe:Me,options:ci,children:(0,l.jsx)(Cs,{sessionId:e,nonce:t,email:me.email,billingName:be||void 0,onBuyerIdentityReady:m,billingApiUrl:pe,intentKind:$>0?"payment":"setup",expressMethods:Ur,onTokenizedBody:Sn,onErrorChange:fe,onButtonClick:ae,onDecline:c,onTechnicalFailure:zr,runBeforeButtonClick:er,onLoadStateChange:vi,placeholderBorderRadius:_r})}):null,!qr&&wi?(0,l.jsx)("div",{style:{height:sa,borderRadius:_r,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,uo&&(0,l.jsx)(Ps,{sessionId:e,nonce:t,email:me.email,billingName:[me.firstName,me.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:m,billingApiUrl:pe,paymentElementMethods:zo,stripeInstance:Me,paymentElementBaseOptions:Sa,onTokenizedBody:Sn,onErrorChange:fe,onButtonClick:ae,onDecline:c,runBeforeButtonClick:er,onLoadStateChange:Ci,isProcessing:it,submitButtonColor:Tr,submitButtonBorderRadius:Ut,submitButtonStyle:b.submitButton,onExpandApm:re,expandedApmMethod:Mt,themeId:he,buttonAppearance:{backgroundColor:b.cardButton?.backgroundColor,borderColor:b.cardInputBorder,textColor:b.cardButton?.color,borderRadius:_r}}),ke&&(0,l.jsx)("button",{type:"button",onClick:async()=>{it||!(await er("card")).proceed||(ae?.("card"),U())},disabled:it,style:{width:"100%",...W,...b.cardButton,...Ga({themeBundle:K,resolvedPrimaryColor:Tr,resolvedBorderRadius:Ut,submitButtonStyle:b.submitButton,explicitPrimaryColor:wn?.colorPrimary}),fontSize:b.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:it?"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:it?.6:1},onMouseEnter:Ce=>{!it&&(K||wn?.colorPrimary)&&(Ce.currentTarget.style.backgroundColor=tl)},onMouseLeave:Ce=>{(K||wn?.colorPrimary)&&(Ce.currentTarget.style.backgroundColor=Tr)},onMouseDown:Ce=>{Ce.currentTarget.style.transform="scale(0.985)"},onMouseUp:Ce=>{Ce.currentTarget.style.transform="scale(1)"},children:(0,l.jsx)(Hr,{content:$e})}),M&&qe==="buttons"&&(0,l.jsx)(eo,{margin:"0.25rem 0",styleOverride:b.errorBanner,children:M})]}),ke&&C&&(0,l.jsx)("div",{style:{gridArea:"1 / 1",...Z?{animation:Z}:{},...qe==="collapsing"?{pointerEvents:"none"}:{}},children:Li}),V&&zi&&Mt&&Ko&&Me&&(0,l.jsx)("div",{style:{gridArea:"1 / 1",...Vr?{animation:Vr}:{},...qe==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,l.jsxs)("div",{style:{backgroundColor:Ea,borderRadius:Aa,...go,padding:Ma},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:oe,style:{display:"inline-flex",alignItems:"center",gap:_a?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:b.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...b.backButton},"aria-label":"Back to payment methods",children:[(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",...b.backButtonIcon},children:(0,l.jsx)("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,l.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,l.jsx)(Wr,{content:Ae})]}),(0,l.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:b.titleFontSize??"1.05rem",color:Ta,paddingRight:80,...b.title},children:`Pay with ${(0,u.getStripeMethodDisplayName)(Mt)}`})]}),(0,l.jsx)($t.Elements,{stripe:Me,options:Ko,children:(0,l.jsx)(Wa,{method:Mt,sessionId:e,nonce:t,email:me.email,billingName:[me.firstName,me.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:m,billingApiUrl:pe,onTokenizedBody:Sn,onErrorChange:fe,onDecline:c,onCancel:oe,runBeforeButtonClick:er,onButtonClick:ae,isProcessing:it,submitButtonColor:Tr,submitButtonBorderRadius:Ut,submitButtonStyle:b.submitButton,errorText:M})},Mt)]})})]})]})}return zi&&Mt&&Ko&&Me&&V?(0,l.jsxs)("form",{onSubmit:Ia,className:p,noValidate:!0,style:{position:"relative"},children:[(0,l.jsx)(Ka,{}),We&&(0,l.jsx)(jn,{status:We,errorMessage:M,authorized:Et}),(0,l.jsx)("div",{style:{...Vr?{animation:Vr}:{},...qe==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,l.jsxs)("div",{style:{backgroundColor:Ea,borderRadius:Aa,...go,padding:Ma},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:oe,style:{display:"inline-flex",alignItems:"center",gap:_a?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:b.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...b.backButton},"aria-label":"Back to payment methods",children:[(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",...b.backButtonIcon},children:(0,l.jsx)("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,l.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,l.jsx)(Wr,{content:Ae})]}),(0,l.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:b.titleFontSize??"1.05rem",color:Ta,paddingRight:80,...b.title},children:`Pay with ${(0,u.getStripeMethodDisplayName)(Mt)}`})]}),(0,l.jsx)($t.Elements,{stripe:Me,options:Ko,children:(0,l.jsx)(Wa,{method:Mt,sessionId:e,nonce:t,email:me.email,billingName:[me.firstName,me.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:m,billingApiUrl:pe,onTokenizedBody:Sn,onErrorChange:fe,onDecline:c,onCancel:oe,runBeforeButtonClick:er,onButtonClick:ae,isProcessing:it,submitButtonColor:Tr,submitButtonBorderRadius:Ut,submitButtonStyle:b.submitButton,errorText:M})},Mt)]})})]}):(0,l.jsxs)("form",{onSubmit:Ia,className:p,noValidate:!0,style:{position:"relative"},children:[(0,l.jsx)(Ka,{}),We&&(0,l.jsx)(jn,{status:We,errorMessage:M,authorized:Et}),(0,l.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Ni("flopay-direct-paypal-gate-debug-default"),Oi("flopay-stripe-gate-debug-default"),lo&&ye&&(0,l.jsxs)(l.Fragment,{children:[X&&(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)(Io,{sessionId:e,nonce:t,billingApiUrl:pe,email:me.email,billingName:be||void 0,onBuyerIdentityReady:m,clientId:ye.clientId,environment:ye.environment,currency:Ue.toUpperCase(),isSubscription:ot,providerObjectType:R,onTokenizedBody:Sn,onComplete:i,onErrorChange:fe,onDecline:c,onTechnicalFailure:zr,onButtonClick:ae,runBeforeButtonClick:er,isProcessing:it,onLoadStateChange:wa,onInitializationStateChange:ka,session:mt,existingOrderId:X?.orderId,debug:Ee},X?.orderId??"fresh")]}),co&&(0,l.jsx)($t.Elements,{stripe:Pn,options:di,children:(0,l.jsx)(bs,{sessionId:e,nonce:t,email:me.email,billingName:be||void 0,onBuyerIdentityReady:m,billingApiUrl:pe,onTokenizedBody:Sn,onErrorChange:fe,isProcessing:it,onButtonClick:ae,onDecline:c,onTechnicalFailure:zr,runBeforeButtonClick:er,onLoadStateChange:gi,placeholderBorderRadius:_r})}),qr&&(0,l.jsx)($t.Elements,{stripe:Me,options:ci,children:(0,l.jsx)(Cs,{sessionId:e,nonce:t,email:me.email,billingName:be||void 0,onBuyerIdentityReady:m,billingApiUrl:pe,intentKind:$>0?"payment":"setup",expressMethods:Ur,onTokenizedBody:Sn,onErrorChange:fe,onButtonClick:ae,onDecline:c,onTechnicalFailure:zr,runBeforeButtonClick:er,onLoadStateChange:vi,placeholderBorderRadius:_r})}),uo&&(0,l.jsx)(Ps,{sessionId:e,nonce:t,email:me.email,billingName:[me.firstName,me.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:pe,paymentElementMethods:zo,stripeInstance:Me,paymentElementBaseOptions:Sa,onTokenizedBody:Sn,onErrorChange:fe,onButtonClick:ae,onDecline:c,runBeforeButtonClick:er,onLoadStateChange:Ci,isProcessing:it,submitButtonColor:Tr,submitButtonBorderRadius:Ut,submitButtonStyle:b.submitButton,themeId:he,onExpandApm:re,expandedApmMethod:Mt,buttonAppearance:{backgroundColor:b.cardButton?.backgroundColor,borderColor:b.cardInputBorder,textColor:b.cardButton?.color,borderRadius:_r}})]}),ke&&(Ys||Ws||Gs)&&(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"}})]}),ke&&Li]})}var k=require("react/jsx-runtime"),Lr=44,ii="flopay_checkout_saved_payment_resume",ma=new Map,ua=new Map;function Ts(e,t){t.settled&&t.consumers===0&&ma.get(e)===t&&ma.delete(e)}function rc(e,t,n){let r=ua.get(e);if(r&&(!r.sdkGeneratedIdempotencyKey||!t||r.sdkGeneratedIdempotencyKey===t))return r.attempt;let o=n(),i={attempt:o,sdkGeneratedIdempotencyKey:t};ua.set(e,i);let d=()=>{ua.get(e)===i&&ua.delete(e)};return o.then(d,d),o}function Bo(e){return new Promise(t=>setTimeout(t,e))}function pa(e,t,n){let r=Zo({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:Pe.SDK_VERSION,enabled:t!==!1});return r.beginCheckout(n),r}function Fo(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function Ja(e,t,n,r,o){let i=pa(e,t,n);i.error({errorCode:r,stage:o,paymentMethodCategory:"unknown",...o==="session_read"?{requestCategory:"session_read"}:{}}),Fo(i)}function oc(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 oi(e){let t=e?.data.paypal?.publishableKey;if(t)return{clientId:t,environment:e?.data.paypal?.environment,providerObjectType:e?.data.paypal?.providerObjectType}}function Xa(e){return!e||e.data.stripe?.publishableKey?!1:!!oi(e)?.clientId}function Sr(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function ac(){if(!Sr())return null;try{let e=window.sessionStorage.getItem(ii);return e?JSON.parse(e):null}catch{return null}}function xs(e){if(Sr())try{window.sessionStorage.setItem(ii,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function Za(){if(Sr())try{window.sessionStorage.removeItem(ii)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}var si=":idempotency-key";function Bs(e,t){if(!Sr())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 Qa(e,t,n,r){if(Sr())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 ai(e,t){if(Sr())try{Bs(e,t)&&window.sessionStorage.removeItem(e)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout session cache.",n)}}function Fs(e,t){if(!Sr())return null;try{let n=window.sessionStorage.getItem(e+si);if(!n)return null;try{let r=JSON.parse(n);return typeof r=="string"?r?{idempotencyKey:r}:null:!r||typeof r.idempotencyKey!="string"||!r.idempotencyKey||"canonicalIdentity"in r&&r.canonicalIdentity!==t?null:{..."canonicalIdentity"in r?{canonicalIdentity:t}:{},idempotencyKey:r.idempotencyKey}}catch{return{idempotencyKey:n}}}catch{return null}}function ei(e,t,n){if(Sr())try{window.sessionStorage.setItem(e+si,JSON.stringify({canonicalIdentity:t,idempotencyKey:n}))}catch(r){console.warn("[FloPayCheckout] Failed to persist checkout idempotency key.",r)}}function ti(e,t){if(ai(e,t),!!Sr())try{Fs(e,t)&&window.sessionStorage.removeItem(e+si)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout idempotency key.",n)}}function ic(){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 Ms(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 ni(e,t){return e?"custom_layout":t==="buttons"?"buttons_layout":"default_layout"}function sc(e,t){return e?"unknown":t==="buttons"?"buttons":"embedded"}function As(e){return e?.gateways?.stripe?"stripe":e?.gateways?.paypal?"paypal":void 0}function lc(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 ri(e,t){return`${e}:${t.totalAmount??""}:${t.overrideAmount??""}:${t.quantity??1}:${t.currency??""}`}function cc(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 Do(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=>ri(`${o.type??""}:${o.code??o.providerItemId??o.providerPlanId??""}`,o)).sort(),i:e?.items?.map(o=>ri(o.code??o.providerItemId??"",o)).sort(),s:e?.subscriptions?.map(o=>ri(o.code??o.providerPlanId??"",o)).sort(),couponCodes:e?.couponCodes?[...e.couponCodes].sort():void 0,checkoutMetadata:cc(e?.checkoutMetadata),...t?{tagsData:e?.tagsData,utmMetadata:e?.utmMetadata,tokenizedData:e?.tokenizedData,checkoutMode:e?.checkoutMode??"full"}:{}};return JSON.stringify(r)}function dc(e,t=!1){let n=Do(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 uc(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,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(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,f)=>`${y.code}:${y.type??""}`.localeCompare(`${f.code}:${f.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,f)=>`${y.code}:${y.type??""}`.localeCompare(`${f.code}:${f.type??""}`));if(i.length!==d.length)return!1;for(let[y,f]of i.entries()){let g=d[y];if(g===void 0||f.code!==g.code||f.type!==void 0&&f.type!==g.type||f.quantity!==g.quantity||f.totalAmount!==g.totalAmount||f.overrideAmount!==g.overrideAmount||f.currency!==g.currency)return!1}let c=[...t.couponCodes??[]].sort(),v=[...e.coupons??[]].sort();return c.length===v.length&&c.every((y,f)=>y===v[f])}function ya({sessionId:e,nonce:t,createSession:n,billingApiUrl:r,telemetry:o,appearance:i,locale:d,loading:c,error:v,onComplete:y,onError:f,onInstrument:g,onDecline:p,onCountryChange:I,onZipChange:F,showPayPal:N=!0,showStripe:ge=!0,enabledPaymentMethods:V,showApplePay:S=!0,showGooglePay:se=!0,debug:q=!1,layout:de,theme:G,buttonsTheme:he,buttonsStyles:Ke,cardButtonContent:Se,cardBackButtonContent:Rt,cardTitleContent:$e,showSecurityFooter:Ae,onButtonClick:Be,onBeforeButtonClick:le,enableAVS:ae,cardFieldOrder:D,cardPreFormSlot:Fe,avsLayout:De,className:te,initialErrorMessage:Re=null,children:ve,checkoutMode:x,confirmLabel:Q,renderConfirmButton:we,onSessionCompleted:ue}){let ce=(0,Pe.resolveBillingApiUrl)(r),ze=(0,w.useMemo)(()=>(0,Pe.resolveTheme)(G),[G]),rt=i??ze?.appearance,gt=n?"embedded_checkout":"standard_checkout",Ge=ni(ve,de),[ie,Y]=(0,w.useState)(null),[$,Ue]=(0,w.useState)(null),Qe=(0,w.useRef)(null),[ye,ot]=(0,w.useState)(null),ne=(0,w.useRef)(null),[h,tt]=(0,w.useState)(null),Ee=(0,w.useMemo)(()=>n?Do(n):"",[n]),O=n?`create:${Ee}`:`session:${e??""}`,Le=As(h),xe=(0,w.useRef)(new Set),pt=(0,w.useRef)(O),mt=(0,w.useRef)(O);wo(()=>{mt.current=O,pt.current!==O&&(pt.current=O,xe.current.clear())},[O]);let R=(0,w.useCallback)(U=>{if(mt.current===O){if(Na.has(U.name)){if(xe.current.has(U.name))return;xe.current.add(U.name)}nt(()=>g?.(U))}},[O,g]),A=Qr(R,O),ht=(0,w.useRef)(!1),Je=(0,w.useCallback)(U=>{if(ht.current)return;let j=U.gateway||!Le?U:{...U,gateway:Le};R(j)},[R,Le]);(0,w.useEffect)(()=>{A({class:"lifecycle",name:"checkout.mount"})},[A]);let[Yt,fn]=(0,w.useState)(e??""),L=e??Yt,jt=n?"":L,[Gt,lt]=(0,w.useState)(!0),[Lt,gn]=(0,w.useState)(null),[In,hn]=(0,w.useState)("full"),[Nt,He]=(0,w.useState)(!1),[yt,Ct]=(0,w.useState)(Re),[on,ct]=(0,w.useState)(null),[vn,Xe]=(0,w.useState)(null),[Jt,bn]=(0,w.useState)(!1),[an,Kt]=(0,w.useState)(void 0),[Ot,en]=(0,w.useState)(""),[Xt,Rn]=(0,w.useState)(!1),[xt,sn]=(0,w.useState)(!1),[Pt,P]=(0,w.useState)(!1),ft=(0,w.useRef)(0),Et=(0,w.useRef)(void 0),[_t,cn]=(0,w.useState)("loading"),[dr,Fn]=(0,w.useState)(0),z=(0,w.useRef)(!1),ke=(0,w.useRef)(!1),tn=(0,w.useRef)(!1),dn=(0,w.useRef)(null),_e=(0,w.useMemo)(()=>({checkoutMode:x??In,layout:sc(ve,de)}),[x,ve,In,de]),Hn=(0,w.useRef)(y);Hn.current=y;let Dn=(0,w.useRef)(f);Dn.current=f;let zt=(0,w.useRef)(p);zt.current=p,(0,w.useEffect)(()=>{Wt($)?.setCheckoutContext(_e),ye&&ye!==$&&Wt(ye)?.setCheckoutContext(_e)},[$,ye,_e]);let un=(0,w.useRef)(ue);un.current=ue;let Rr=(0,w.useCallback)(U=>{cn(U),!(U!=="exhausted"||tn.current)&&(tn.current=!0,Dn.current?.(new Pe.FloPayError("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),Er=(0,w.useCallback)(()=>{cn("retrying"),Fn(U=>U+1)},[]);(0,w.useEffect)(()=>{cn("loading"),Fn(0),tn.current=!1},[L]),(0,w.useEffect)(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:Pe.SDK_VERSION,checkout_type:gt,checkout_layout:Ge,billing_api_url:ce})},[Ge,gt,ce]);let En=(0,w.useMemo)(()=>n?Do(n,!0):"",[n]),ur=(0,w.useMemo)(()=>Ot===En?an:void 0,[an,Ot,En]),Wn=(0,w.useMemo)(()=>n?Ba(n,ur):void 0,[n,ur]),Ln=x??Wn?.checkoutMode??"full",St=(0,w.useMemo)(()=>Wn?{...Wn,checkoutMode:Ln}:void 0,[Wn,Ln]);(0,w.useEffect)(()=>{Kt(void 0),en(En),Et.current=void 0,P(!1)},[En]),(0,w.useEffect)(()=>{Ct(Re)},[Re]);let or=(0,w.useCallback)((U,j,re)=>{nt(()=>{zt.current?.(Qt(U,j,re))})},[]),_n=(0,w.useCallback)(async(U,j)=>{Ct(null),Xe(null),bn(!1),ct("processing");let re=j?.sessionId??U.id,oe=As(U),We=Qe.current??ne.current,ee=Wt(We),J=We?null:pa(ce,o,_e),E={log:M=>{ee?ee.log(M):J?.log(M)},error:M=>{ee?ee.error(M):J?.error(M)},terminal:M=>{ee?ee.terminal(M):J?.terminal(M)},performance:M=>{ee?ee.performance(M):J?.performance(M)},now:()=>ee?.now()??J?.now()??0,elapsed:M=>ee?.elapsed(M)??Math.max(0,(J?.now()??M)-M)},B=E.now(),X=!!(j?.initialAutoProcessingError||j?.initialAutoProcessingPending),vt=!1,et,pe=()=>{vt||(vt=!0,X=!0,et=E.now(),E.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),E.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},at=!1,T=()=>{at||(at=!0,E.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),E.performance({stage:"processing",durationMs:E.elapsed(B),durationMode:"machine",paymentMethodCategory:"saved"}),et!==void 0&&E.performance({stage:"recovery",durationMs:E.elapsed(et),durationMode:"machine",paymentMethodCategory:"saved"}))};E.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),ht.current=!0;try{E.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"})}finally{ht.current=!1}A({class:"lifecycle",name:"payment.processing.started",provider:oe}),X&&pe();let m;try{let M=is(j?.initialAutoProcessingError),K;if(M)pe(),M.type==="paypal_redirect_required"&&dn.current?.publishableKey&&xs({sessionId:re,publishableKey:dn.current.publishableKey,paypalPublishableKey:dn.current.paypalPublishableKey}),K=await ra(M,{flopay:Qe.current,paypalFlopay:ne.current,attempt3DS:j?.attempt3DS,billingApiUrl:ce,sessionId:re,session:U,telemetry:!1}),M.type==="paypal_redirect_required"&&Za();else if(j?.initialAutoProcessingPending){let Ye=(await new Dr.PaymentAPI(ce,{telemetry:!1}).waitForCheckoutSessionCompletion(j.initialAutoProcessingPending.sessionId,{initialDelayMs:j.initialAutoProcessingPending.retryAfterMs})).data.session;if(!Gr(Ye))throw Go(Ye);K=Ar(Ye,re)}else{if(j?.initialAutoProcessingError)throw Ir(j.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:j.initialAutoProcessingError.checkoutMethod});if(j?.fromCreateSession)return j?.fallbackToFull&&(hn("full"),Ms("full")),!1;{let b=await ro({billingApiUrl:ce,sessionId:re,session:U,telemetry:!1});b.type==="success"?K=b.result:(pe(),b.type==="paypal_redirect_required"&&dn.current?.publishableKey&&xs({sessionId:re,publishableKey:dn.current.publishableKey,paypalPublishableKey:dn.current.paypalPublishableKey}),K=await ra(b,{flopay:Qe.current,paypalFlopay:ne.current,attempt3DS:j?.attempt3DS,billingApiUrl:ce,sessionId:re,session:U,telemetry:!1}),b.type==="paypal_redirect_required"&&Za())}}re&&to(re),T(),X&&(E.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),E.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),E.terminal({outcome:K.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),bn(K.status==="authorized"),ct("success"),await Bo(1200),m=()=>Hn.current?.(K)}catch(M){let K=xo(M),b=K.checkoutMethod??To;Ct(K.message),Xe(K.message),bn(!1),j?.fallbackToFull&&(E.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),hn("full"),Ms("full")),T();let H=K.statusCode===void 0?void 0:(0,Pe.telemetryStatusClass)(K.statusCode,"unknown"),Ye=H==="4xx"?{requestCategory:"process_payment",statusClass:H}:{},ln=H===void 0||H==="4xx";if(ln&&(K.telemetryOutcome==="payment_declined"||!!(K.declineCode||K.code?.toLowerCase().includes("declin"))))E.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...Ye});else if(ln&&(K.telemetryOutcome==="validation_rejected"||K.type==="validation_error"))E.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...Ye});else{let me=(0,Pe.classifyTelemetryFailure)(M,X?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown"),be=K.telemetryRequestCategory??"process_payment";ht.current=!0;try{E.error({...me,...K.telemetryFailureCategory?{failureCategory:K.telemetryFailureCategory}:{},stage:X?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:be})}finally{ht.current=!1}A({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:be,provider:oe})}return nt(()=>Dn.current?.(K)),or(b,K,{code:K.code,declineCode:K.declineCode}),ct("error"),await Promise.allSettled([Bo(1500),j?.ensureProvidersReady?j.ensureProvidersReady():Promise.resolve()]),X&&(E.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),E.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{T(),J&&Fo(J),ct(null),Xe(null)}return nt(m),!0},[or,A,ce,o,_e]);(0,w.useEffect)(()=>{if(typeof window>"u"||ke.current)return;let U=new URLSearchParams(window.location.search),j=U.get("payment_intent_client_secret");if(!j)return;let re=ac();re&&(ke.current=!0,(async()=>{let oe,We=0;Ct(null),Xe(null),ct("processing"),He(!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:ee,paypalFlopay:J}=await aa({publishableKey:re.publishableKey,paypalPublishableKey:re.paypalPublishableKey,billingApiUrl:ce,locale:d,telemetry:o});oe=Wt(J??ee),oe?.setCheckoutContext(_e),We=oe?.now()??0,oe?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),oe?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let E=(J??ee)?.getRawProvider();if(!E)throw Object.assign(new Pe.FloPayError("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:B,error:X}=await E.retrievePaymentIntent(j);if(X)throw Object.assign(new Pe.FloPayError(X.message??"Failed to retrieve PayPal payment status.","api_error",{code:X.code}),{checkoutMethod:"paypal"});let vt=Ki(B?.status);if(!B||vt==="failed")throw Object.assign(new Pe.FloPayError("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let et=typeof B.payment_method=="string"?B.payment_method:B.payment_method?.id,pe=vt;if(re.sessionId){let m=(await new Dr.PaymentAPI(ce,{telemetry:!1}).getUnifiedCheckoutSession(re.sessionId)).data.session;if(m&&m.status!=="complete"){let M=await ro({billingApiUrl:ce,sessionId:re.sessionId,session:m,telemetry:!1,tokenizedData:{id:et??B.id,type:"card",threeDSecureActionResultTokenId:B.id,isPaypal:!0}});if(M.type!=="success")throw Object.assign(new Pe.FloPayError("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});pe=M.result.status}}re.sessionId&&to(re.sessionId),oe?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),oe?.performance({stage:"redirect_resume",durationMs:oe.elapsed(We),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),oe?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),ct("success"),await Bo(1200),nt(()=>Hn.current?.({status:pe,paymentIntentId:B.id,paymentMethodId:et,checkoutMethod:"paypal"}))}catch(ee){let J=xo(ee),E=J.checkoutMethod??"paypal",B=!!(J.declineCode||J.code?.toLowerCase().includes("declin"));if(oe)oe.performance({stage:"redirect_resume",durationMs:oe.elapsed(We),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),B?oe.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):oe.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(B){let X=pa(ce,o,_e);X.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),Fo(X)}else Ja(ce,o,_e,"REDIRECT_RESUME_FAILED","redirect_resume");Ct(J.message),Xe(J.message),nt(()=>Dn.current?.(J)),or(E,J,{code:J.code,declineCode:J.declineCode}),ct("error"),await Bo(1500)}finally{Za(),ic(),ct(null),Xe(null),He(!1)}})())},[or,d,ce,o,_e]);let Yn=(0,w.useRef)(null),Cn=(0,w.useMemo)(()=>St?Do(St):"",[St]),Gn=(0,w.useRef)(St);Gn.current=St,(0,w.useEffect)(()=>{fn(e??"")},[e]),(0,w.useEffect)(()=>{z.current=!1,Ct(Re),Xe(null),bn(!1),ct(null)},[Cn,Re,e]);async function Jn(U,j,re){let oe=pa(ce,o,_e),We=new Dr.PaymentAPI(ce,{telemetry:!1}),ee=!1;try{let J=U.idempotencyKey===void 0?void 0:(0,Pe.resolveIdempotencyKey)(U.idempotencyKey),E=Bs(j,re),B=Fs(j,re);E?.canonicalIdentity===re&&B&&B.canonicalIdentity===void 0&&(ei(j,re,B.idempotencyKey),B={...B,canonicalIdentity:re});let X=J??(B?.canonicalIdentity===re?B.idempotencyKey:void 0),vt,et=!1;oe.log({name:E?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let pe=E?.sid??null,at=null,T,m,M=!1;if(pe)try{at=await We.getUnifiedCheckoutSession(pe,E?.nonce),E&&E.canonicalIdentity===void 0&&(uc(at.data.session,U)?(Qa(j,re,pe,E.nonce??at.data.session?.clientSecret),B&&B.canonicalIdentity===void 0&&(ei(j,re,B.idempotencyKey),X??(X=B.idempotencyKey))):(ti(j,re),B=null,X=J,pe=null,at=null));let b=at?.data.session?.status,H=at?.data.session,Ye=H?.clientSecret||E?.nonce;if(pe&&H?.buyerIdentified===!1&&Ye&&(m=Yr(We,pe,Ye,U.account)),pe&&at&&b==="complete"){if(Oa(pe))return{sid:pe,result:at};ti(j,re),pe=null,at=null,et=!0}}catch{oe.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),E?.canonicalIdentity===void 0?(ti(j,re),X=J):ai(j,re),pe=null}if(!pe){!J&&(et||!X)&&(X=(0,Pe.resolveIdempotencyKey)(),vt=X),X&&ei(j,re,X);let b=oe.now(),H=0;oe.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let Ye={...U,idempotencyKey:X,avsCheck:!!ae,avsConfig:typeof ae=="object"?ae:void 0,checkoutType:"embedded_checkout",checkoutLayout:ni(ve,de)};Object.defineProperty(Ye,Dr.SESSION_CREATE_TELEMETRY,{configurable:!1,enumerable:!1,value:{onAttempt:st=>{H=Math.max(H,st)}}});let ln=()=>{oe.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:"2xx"}),oe.performance({stage:"session_create",durationMs:oe.now()-b,durationMode:"machine",requestCategory:"session_create",attempt:H,statusClass:"2xx"})},it=st=>{let me=(0,Pe.classifyTelemetryFailure)(st,"CHECKOUT_SESSION_CREATE_FAILED","unknown");oe.performance({stage:"session_create",durationMs:oe.now()-b,durationMode:"machine",requestCategory:"session_create",attempt:H,statusClass:me.statusClass}),st instanceof Pe.FloPayError&&st.type==="validation_error"?oe.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown"}):me.statusClass==="4xx"?oe.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create",statusClass:"4xx"}):(oe.error({...me,stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create"}),A({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_create"}))};try{if((0,Pe.isDetachedSessionEligible)(Ye)){let st=await We.createDetachedSession(Ye);st.claimed.catch(()=>{}),at=st.shell,pe=st.sessionId,m=st.claim,T=st.claimed.then(me=>{let be=me.data.session?.id??st.sessionId;return be&&Qa(j,re,be,me.data.session?.clientSecret??st.nonce),ln(),me},me=>{throw ai(j,re),it(me),me}).finally(()=>Fo(oe)),T.catch(()=>{}),ee=!0,oe.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),oe.performance({stage:"session_shell",durationMs:oe.now()-b,durationMode:"machine",requestCategory:"session_create",attempt:H,statusClass:"2xx",paymentMethodCategory:"card"})}else at=await We.createAndFetchSession(Ye),ln()}catch(st){throw it(st),st}pe=at.data.session?.id??pe??"",pe&&!T&&Qa(j,re,pe,at.data.session?.clientSecret)}let K=at?.data.session;return!m&&pe&&K?.buyerIdentified===!1&&K.clientSecret&&(m=Yr(We,pe,K.clientSecret,U.account)),{sid:pe??"",result:at,sdkGeneratedIdempotencyKey:vt,...T?{claimed:T}:{},...m?{claim:m}:{},...M?{claimRequiresIdentity:!0}:{}}}finally{ee||Fo(oe)}}let dt=(0,w.useRef)(Jn);wo(()=>{dt.current=Jn},[Jn]);let Tn=(0,w.useCallback)(async(U,j)=>{let re=Gn.current;if(!re)throw new Pe.FloPayError("createSession is required to bootstrap checkout.","validation_error");let oe=Ba(re,U),We=Do(oe),ee=dc(oe),J=ma.get(We);if(!J){let X={canonicalIdentity:We,promise:dt.current(oe,ee,We),consumers:0,settled:!1};J=X,ma.set(We,X);let vt=()=>{X.settled=!0,Ts(We,X)};X.promise.then(vt,vt)}J.consumers+=1;let E=!1,B=()=>{E||(E=!0,J.consumers-=1,Ts(We,J))};j?.(B);try{let X=await J.promise;Yn.current=We,U&&(en(En),Kt(H=>$i(H,U)));let{sid:vt,result:et,claimed:pe,claim:at,claimRequiresIdentity:T}=X;if(Et.current=at,P(T===!0),Y(et),et.data.session&&tt(et.data.session),vt&&fn(vt),pe){ft.current+=1;let H=ft.current;sn(!0),pe.then(Ye=>{ft.current===H&&(Y(Ye),Ye.data.session&&tt(Ye.data.session),sn(!1),P(!1))},Ye=>{ft.current===H&&(sn(!1),P(!1),gn(Ye instanceof Pe.FloPayError?Ye:new Pe.FloPayError(Ye instanceof Error?Ye.message:"Failed to create session","api_error")))})}else ft.current+=1,sn(!1),P(!1);let{publishableKey:m,paypalPublishableKey:M}=oa(et),{flopay:K,paypalFlopay:b}=await aa({publishableKey:m,paypalPublishableKey:M,billingApiUrl:ce,locale:d,telemetry:o});return Qe.current=K,Ue(K),ne.current=b,ot(b),lt(!1),X}catch(X){throw Yn.current===We&&(Yn.current=null),X}finally{j||B()}},[En,d,ce,o]),Nn=(0,w.useRef)(_n);Nn.current=_n;let xn=(0,w.useRef)(Tn);xn.current=Tn;let Xn=(0,w.useCallback)(async U=>{if(!lc(U)||Xt)return{sessionId:Yt,session:h};Rn(!0);try{let j=await Tn(U);return{sessionId:j.sid,session:j.result.data.session??null}}finally{Rn(!1)}},[Tn,Xt,Yt,h]),qe=(0,w.useCallback)(async U=>{let j=Et.current;if(!j)return;let re=ft.current,oe=await j(U);ft.current===re&&(Y(oe),oe.data.session&&tt(oe.data.session))},[]);(0,w.useEffect)(()=>{let U=!1,j;gn(null);let re=Gn.current;if(Cn&&re)return hn(Ln),lt(!1),Yn.current===Cn?()=>{U=!0}:(tt(ji(re,x)),(async()=>{let ee=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),J=Ln==="auto"&&!z.current&&!ee;J&&(Ct(null),Xe(null),ct("processing"));try{let E=await xn.current(void 0,et=>{j=et}),B=E.result.data.session??null;dn.current=oa(E.result);let X=Xa(E.result),vt=Oa(E.sid||B?.id);if(!U&&J&&B&&!X&&!vt){z.current=!0,await rc(Cn,E.sdkGeneratedIdempotencyKey,()=>Nn.current(B,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:E.result.autoProcessingError,initialAutoProcessingPending:E.result.autoProcessingPending,autoProcessingAttempted:E.result.autoProcessingAttempted,sessionId:E.sid||B.id}));return}!U&&J&&((X||vt)&&(z.current=!0),ct(null),Xe(null))}catch(E){if(U)return;let B=Yo(E);if(J&&B==="session_auto_completed"){z.current=!0,ct("success"),await Bo(1200),U||(nt(()=>{Hn.current?.({status:"succeeded"})}),ct(null),Xe(null));return}J&&(ct(null),Xe(null));let X=E instanceof Pe.FloPayError?E:new Pe.FloPayError(E instanceof Error?E.message:"Failed to create session","api_error");gn(X)}finally{j?.(),j=void 0}})(),()=>{U=!0,j?.()});lt(!0);async function oe(){let ee=!1;try{let J=new Dr.PaymentAPI(ce,{telemetry:!1}),E=await J.getUnifiedCheckoutSession(L,t);if(U)return;Y(E);let B=E.data.session??null;if(tt(B),!B)throw new Pe.FloPayError("No session data returned","api_error");let X=B.checkoutMode;if(X==="setup")throw new Pe.FloPayError("This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.","validation_error",{code:"InvalidCardSetupSurface",param:"sessionId"});if(B.status==="authorized"){lt(!1),nt(()=>{Hn.current?.(Ar(B,L)),un.current?.(B.successUrl??"")});return}if(B.status==="complete"){lt(!1),nt(()=>{un.current?.(B.successUrl??"")});return}if(B.status==="expired")throw Wo(B);ee=!0;let vt=x??X??"full";hn(vt),ft.current+=1;let et=B.clientSecret||t;Et.current=B.buyerIdentified===!1&&et?Yr(J,L,et,{...B.customer?.id?{userId:B.customer.id}:{}}):void 0,sn(!1),P(!1);let pe=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),at=Xa(E);if(vt==="auto"&&!z.current&&!pe&&!at){z.current=!0;let T=We(E);try{if(await Nn.current(B,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>T,sessionId:L||B.id}),U)return;await T,U||lt(!1);return}catch{if(U)return;await T,U||lt(!1);return}}await We(E),U||lt(!1)}catch(J){if(U)return;ee&&A({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"}),J instanceof Pe.FloPayError?!ee&&!oc(J)&&Ja(ce,o,_e,"NETWORK_REQUEST_FAILED","session_read"):Ja(ce,o,_e,"INTERNAL_SDK_ERROR","checkout_mount");let E=J instanceof Pe.FloPayError?J:new Pe.FloPayError(J instanceof Error?J.message:"Failed to initialize checkout","api_error");gn(E),lt(!1)}}async function We(ee){let{publishableKey:J,paypalPublishableKey:E}=oa(ee);dn.current={publishableKey:J,paypalPublishableKey:E};let{flopay:B,paypalFlopay:X}=await aa({publishableKey:J,paypalPublishableKey:E,billingApiUrl:ce,locale:d,telemetry:o});Qe.current=B,Ue(B),ne.current=X,ot(X)}return oe(),()=>{U=!0}},[x,Cn,Ln,jt,t]);let pn=(0,w.useCallback)(async()=>{if(!(Nt||!h)){He(!0),Ct(null);try{await _n(h,{attempt3DS:!0,fallbackToFull:!0,sessionId:L||h.id})}finally{He(!1)}}},[L,Nt,_n,h]),Mt=oi(ie),pr=Xa(ie),mr=(0,w.useMemo)(()=>{if(!(!ie||!h||!ie.data.stripe?.publishableKey))return{billingApiUrl:ce}},[ie,h,ce]),yr=!!(n&&!ve&&de==="buttons"&&le&&Ln==="full"),Mn=(0,w.useMemo)(()=>({session:h,loading:Gt,error:Lt,checkoutMode:In,inlineSessionDraft:St,applyInlineSessionPatch:yr?Xn:void 0,inlineSessionPatchProcessing:Xt,claimPending:xt,claimRequiresIdentity:Pt,claimBuyerIdentity:qe}),[h,Gt,Lt,In,St,yr,Xn,Xt,xt,Pt,qe]),Zn=!!n&&de==="buttons"&&!pr&&(!$||!mr),Ht=on?(0,k.jsx)(jn,{status:on,errorMessage:vn,authorized:Jt}):null;if(Gt){if(c)return(0,k.jsxs)(k.Fragment,{children:[c,Ht]});if(de==="buttons"){let U=ze?.buttonsLayout?.cardButton?.borderRadius??ze?.appearance.variables?.borderRadius??8,j=re=>(0,k.jsx)("div",{style:{height:re,borderRadius:U,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:[N&&j(Lr),ge&&(S||se)&&j(Lr),ge&&j(Lr),(0,k.jsx)("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),Ht]})}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); } }"})]}),Ht]})}return Lt?v?(0,k.jsx)(tr.Provider,{value:Mn,children:v(Lt)}):(0,k.jsx)(tr.Provider,{value:Mn,children:(0,k.jsx)("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:Lt.message})}):Zn?(0,k.jsxs)(k.Fragment,{children:[(0,k.jsx)(tr.Provider,{value:Mn,children:(0,k.jsx)(mc,{onButtonClick:Be,showPayPal:N,showStripe:ge,showApplePay:S,showGooglePay:se,theme:G,buttonsTheme:he,buttonsStyles:Ke,cardButtonContent:Se,cardBackButtonContent:Rt,cardTitleContent:$e})}),Ht]}):pr&&h&&Mt?(0,k.jsxs)(k.Fragment,{children:[(0,k.jsx)(tr.Provider,{value:Mn,children:(0,k.jsxs)("div",{className:te,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[yt&&(0,k.jsx)(eo,{icon:!1,children:yt}),_t==="retrying"&&(0,k.jsx)("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),_t==="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:Er,children:"Retry PayPal"})]}),xt?c??(0,k.jsx)("div",{role:"status","data-testid":"flopay-paypal-catalog-loading","aria-label":"Preparing PayPal",style:{height:Lr,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; } }"})}):_t!=="exhausted"&&(0,k.jsx)("div",{"aria-hidden":_t==="retrying"?!0:void 0,style:_t==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:(0,k.jsx)(ns,{sessionId:L,nonce:h.clientSecret||void 0,billingApiUrl:ce,email:h.customer?.email||St?.account?.email,billingName:[h.customer?.firstName,h.customer?.lastName].filter(Boolean).join(" ")||[St?.account?.firstName,St?.account?.lastName].filter(Boolean).join(" ")||void 0,onBuyerIdentityReady:qe,clientId:Mt.clientId,environment:Mt.environment,currency:(h.currency??"usd").toUpperCase(),isSubscription:h.mode==="subscription",providerObjectType:Mt.providerObjectType,onComplete:y,onErrorChange:Ct,onDecline:p,onButtonClick:Be,onInitializationStateChange:Rr,allowAutomaticRetry:dr===0,session:h,telemetry:o,telemetryContext:_e,onInstrument:Je,debug:q},`${O}:paypal-init-${dr}`)})]})}),Ht]}):!$||!mr?(0,k.jsx)(k.Fragment,{children:Ht}):In==="confirm"?(0,k.jsxs)(k.Fragment,{children:[(0,k.jsx)(tr.Provider,{value:Mn,children:(0,k.jsx)(Eo,{flopay:$,paypalFlopay:ye,options:mr,onInstrument:Je,children:(0,k.jsxs)("div",{className:te,children:[yt&&(0,k.jsx)("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:yt}),we?we({onConfirm:pn,isProcessing:Nt}):(0,k.jsx)("button",{type:"button",onClick:pn,disabled:Nt,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:Nt?"not-allowed":"pointer",opacity:Nt?.6:1},children:Nt?"Processing...":Q??"Confirm Purchase"})]})},O)}),Ht]}):(0,k.jsxs)(k.Fragment,{children:[(0,k.jsx)(tr.Provider,{value:Mn,children:(0,k.jsx)(Eo,{flopay:$,paypalFlopay:ye,options:mr,onInstrument:Je,children:ve?(0,k.jsxs)(k.Fragment,{children:[yt&&(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:yt}),(0,k.jsx)(pc,{sessionId:L,nonce:h?.clientSecret||void 0,billingApiUrl:ce,session:h,children:ve})]}):(0,k.jsx)(da,{sessionId:L,nonce:h?.clientSecret||void 0,email:h?.customer?.email||St?.account?.email,userId:h?.customer?.id||St?.account?.userId,firstName:h?.customer?.firstName||St?.account?.firstName,lastName:h?.customer?.lastName||St?.account?.lastName,totalAmount:h?Math.round((0,Pe.buildCheckoutDisplayData)(h).total*100):0,currency:h?.currency?.toLowerCase()??"usd",onComplete:y,onError:f,onDecline:p,error:yt,onErrorChange:Ct,showPayPal:N,showStripe:ge,enabledPaymentMethods:V??ie?.data.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:ie?.data.stripe?.enabledPaymentMethodCountries,showApplePay:S,showGooglePay:se,layout:de,theme:G,buttonsTheme:he,buttonsStyles:Ke,appearance:rt,cardButtonContent:Se,cardBackButtonContent:Rt,cardTitleContent:$e,onButtonClick:Be,onBeforeButtonClick:le,onBuyerIdentityReady:qe,enableAVS:ae,...D?{cardFieldOrder:D}:{},...Fe?{cardPreFormSlot:Fe}:{},avsLayout:De,country:h?.customer?.country,city:h?.customer?.city,state:h?.customer?.state,onCountryChange:I,onZipChange:F,avsCheck:!!ae,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:ni(ve,de),className:te,directPaypal:oi(ie),isSubscription:h?.mode==="subscription",session:h,dataAttachmentPending:xt,dataAttachmentRequiresIdentity:Pt,debug:q})},O)}),Ht]})}function pc({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 mc({onButtonClick:e,showPayPal:t,showStripe:n=!0,showApplePay:r,showGooglePay:o,theme:i,buttonsTheme:d,buttonsStyles:c,cardButtonContent:v,cardBackButtonContent:y,cardTitleContent:f}){let[g,p]=(0,w.useState)(!1),I=(0,w.useMemo)(()=>(0,Pe.resolveTheme)(i),[i]),F=(0,w.useMemo)(()=>{let S=I?.buttonsLayout??(0,Pe.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},[I,d,c]),N=I?.buttonsLayout?.cardButton?.borderRadius??I?.appearance.variables?.borderRadius??8,ge=S=>(0,k.jsx)("div",{style:{height:S,borderRadius:N,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),V=v===void 0?{boxSizing:"border-box",height:Lr,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(g){let S=F.cardInputBorder??"#e5e7eb",se=F.cardInputBackground??"white",q=Kr(y),de=Kr(f);return(0,k.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,k.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,k.jsxs)("button",{type:"button",onClick:()=>p(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:q?0:"0.5rem",background:"none",border:"none",color:"#4b5563",fontSize:"0.85rem",fontWeight:500,padding:0,flexShrink:0,opacity:1,cursor:"pointer",...F.backButton},children:[(0,k.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...F.backButtonIcon},children:(0,k.jsx)("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,k.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,k.jsx)(Wr,{content:y})]}),de?(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,...F.title},children:(0,k.jsx)(vo,{content:f})})]}),(0,k.jsx)("div",{style:{backgroundColor:se,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:se,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:se,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:se,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",...F.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,S.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&he(Lr),n&&(r||o)&&he(Lr),n&&(0,S.jsx)("button",{type:"button",onClick:()=>{e?.("card"),p(!0)},style:{width:"100%",...q,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:P=>{P.currentTarget.style.transform="scale(0.985)"},onMouseUp:P=>{P.currentTarget.style.transform="scale(1)"},children:(0,S.jsx)(Hr,{content:h})}),(0,S.jsx)("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}var Zn=require("react/jsx-runtime"),pc=44;function Fs(e){return new Promise(t=>setTimeout(t,e))}function mc(e,t){return e instanceof zn.FloPayError?e:new zn.FloPayError(e instanceof Error?e.message:t,"api_error")}function yc(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function fc(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 Ds({sessionId:e,nonce:t,createSession:n,paymentMethodId:r,checkoutMethod:o,clientId:i,products:d,items:c,subscriptions:h,account:y,successUrl:f,cancelUrl:g,couponCodes:p,tagsData:w,utmMetadata:F,billingApiUrl:L,locale:he,theme:q,appearance:P,buttonsTheme:ie,buttonsStyles:O,onSuccess:de,onError:G,onDecline:ve,children:Ve,disabled:we=!1,type:wt="button",style:qe,...Me}){let Ae=(0,je.useMemo)(()=>(0,zn.resolveBillingApiUrl)(L),[L]),se=(0,je.useMemo)(()=>fc({createSession:n,clientId:i,products:d,items:c,subscriptions:h,account:y,successUrl:f,cancelUrl:g,couponCodes:p,tagsData:w,utmMetadata:F}),[y,g,i,p,n,d,c,h,f,w,F]),[re,D]=(0,je.useState)(!1),[Be,Fe]=(0,je.useState)(null),[Q,Ee]=(0,je.useState)(null),[be,x]=(0,je.useState)(!1),[Y,ke]=(0,je.useState)(null),ge=(0,je.useRef)(!0),ne=(0,je.useRef)(null),Ne=(0,je.useRef)(Y),ot=(0,je.useRef)(de),ft=(0,je.useRef)(G),Ye=(0,je.useRef)(ve);(0,je.useEffect)(()=>{Ne.current=Y},[Y]),(0,je.useEffect)(()=>{ot.current=de},[de]),(0,je.useEffect)(()=>{ft.current=G},[G]),(0,je.useEffect)(()=>{Ye.current=ve},[ve]),(0,je.useEffect)(()=>(ge.current=!0,()=>{ge.current=!1,ne.current?.abort()}),[]),(0,je.useEffect)(()=>{if(typeof window>"u")return;let I=ee=>{ee.key==="Escape"&&ke(null)};return window.addEventListener("keydown",I),()=>{window.removeEventListener("keydown",I)}},[]);let oe=(0,je.useCallback)((I,ee=To)=>{Ye.current?.(Vt(ee,I,{code:I.code,declineCode:I.declineCode}))},[]),$=(0,je.useCallback)(async I=>{ge.current&&(Ee(null),x(I.result.status==="authorized"),Fe("success"),await Fs(1200),ge.current&&nt(()=>ot.current?.(I)))},[]),z=(0,je.useCallback)(async(I,ee)=>{ge.current&&(ft.current?.(I),ee?.emitDecline&&oe(I,ee.method),Ee(I.message),x(!1),Fe("error"),await Fs(1500))},[oe]),We=(0,je.useCallback)(async(I,ee,vt)=>{let Ze=I.data.session??null;if(!Ze)throw new zn.FloPayError("No session data returned","api_error");let Jt=Ze.clientSecret||t;if(Gr(Ze)){await $({result:Ar(Ze,ee),session:Ze,sessionId:Ze.id||ee,autoCompleted:!1});return}if(Ze.status==="expired")throw Yo(Ze);try{if(I.autoProcessingPending){let Rt=(await new ga.PaymentAPI(Ae).waitForCheckoutSessionCompletion(I.autoProcessingPending.sessionId,{initialDelayMs:I.autoProcessingPending.retryAfterMs})).data.session;if(!Gr(Rt))throw Go(Rt);await $({result:Ar(Rt,ee),session:Rt,sessionId:Rt.id||ee,autoCompleted:!1});return}if(I.autoProcessingError){if(I.autoProcessingError.type==="3ds_required"&&I.autoProcessingError.nextActionRedirectUrl&&ee&&Jt){let M=new AbortController;ne.current=M;let pt;try{pt=await is({billingApiUrl:Ae,sessionId:ee,nonce:Jt,nextActionRedirectUrl:I.autoProcessingError.nextActionRedirectUrl,signal:M.signal})}finally{ne.current===M&&(ne.current=null)}if(pt.status==="declined")throw wr({type:pt.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:pt.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:I.autoProcessingError.checkoutMethod});let kt=(await new ga.PaymentAPI(Ae).waitForCheckoutSessionCompletion(ee,{initialDelayMs:0,nonce:Jt})).data.session;if(!Gr(kt))throw wr({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:I.autoProcessingError.checkoutMethod});await $({result:Ar(kt,ee),session:kt,sessionId:kt.id||ee,autoCompleted:!1});return}throw wr(I.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:I.autoProcessingError.checkoutMethod})}if(vt?.fromCreateSession&&I.autoProcessingAttempted===!0)throw wr({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let Kt=await ro({billingApiUrl:Ae,sessionId:ee??Ze.id,session:Ze,nonce:Jt});if(Kt.type!=="success")throw wr({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await $({result:Kt.result,session:Ze,sessionId:Ze.id||ee,autoCompleted:!1})}catch(Kt){let M=xo(Kt),pt=Ze.id||ee;await z(M,{emitDecline:!0,method:M.checkoutMethod??To}),yc(M,pt)&&pt&&ge.current&&ke({sessionId:pt,errorMessage:M.message,nonce:Jt||void 0})}},[t,Ae,z,$]),Je=(0,je.useCallback)(async I=>{if(Me.onClick?.(I),!(I.defaultPrevented||we||re)){if(ke(null),e&&se){let ee=new zn.FloPayError("Provide either sessionId or create-session props, not both.","validation_error");await z(ee),ge.current&&(Fe(null),Ee(null));return}if(!e&&!se){let ee=new zn.FloPayError("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await z(ee),ge.current&&(Fe(null),Ee(null));return}D(!0),Ee(null),x(!1),Fe("processing");try{let ee=new ga.PaymentAPI(Ae);if(e){let vt=await ee.getUnifiedCheckoutSession(e,t);await We(vt,e);return}try{let vt=await ee.createAndFetchSession({...se});await We(vt,vt.data.session?.id??null,{fromCreateSession:!0})}catch(vt){if(Wo(vt)==="session_auto_completed"){await $({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw vt}}catch(ee){await z(mc(ee,"Automatic payment failed. Please try again."))}finally{ge.current&&(Fe(null),Ee(null),D(!1))}}},[Me.onClick,se,we,re,t,We,Ae,e,z,$]),ye=(0,je.useCallback)(I=>{let ee=Ne.current;ke(null),ot.current?.({result:I,session:null,sessionId:ee?.sessionId??null,autoCompleted:!1})},[]),at=(0,je.useCallback)(I=>{ft.current?.(I)},[]),k=(0,je.useCallback)(I=>{Ye.current?.(I)},[]),E=(0,je.useMemo)(()=>(0,zn.resolveTheme)(q),[q]),Oe=(0,je.useMemo)(()=>{let I=E?.buttonsLayout??(0,zn.resolveButtonsLayoutTheme)(ie);return O?{...I,...O,cardButton:{...I.cardButton,...O.cardButton}}:I},[E,ie,O]),pe=(0,je.useMemo)(()=>{let I=E?.appearance;return P?I?{...I,...P,variables:{...I.variables,...P.variables}}:P:I},[P,E]),le=pe?.variables,rt=le?.colorPrimary??"#4A49FF",ze=le?.colorPrimaryHover??ao(rt,.12),Xe=le?.borderRadius??"8px";return(0,Zn.jsxs)(Zn.Fragment,{children:[(0,Zn.jsx)("button",{...Me,type:wt,onClick:Je,disabled:we||re,"aria-busy":re,style:{width:"100%",...Ve===void 0?{boxSizing:"border-box",height:pc,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...Oe.cardButton,...Ya({themeBundle:E,resolvedPrimaryColor:rt,resolvedBorderRadius:Xe,submitButtonStyle:Oe.submitButton,explicitPrimaryColor:le?.colorPrimary}),fontSize:Oe.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,...qe},onMouseEnter:I=>{Me.onMouseEnter?.(I),!I.defaultPrevented&&!we&&!re&&(E||le?.colorPrimary)&&(I.currentTarget.style.backgroundColor=ze)},onMouseLeave:I=>{Me.onMouseLeave?.(I),!I.defaultPrevented&&(E||le?.colorPrimary)&&(I.currentTarget.style.backgroundColor=rt)},onMouseDown:I=>{Me.onMouseDown?.(I),I.defaultPrevented||(I.currentTarget.style.transform="scale(0.985)")},onMouseUp:I=>{Me.onMouseUp?.(I),I.defaultPrevented||(I.currentTarget.style.transform="scale(1)")},children:(0,Zn.jsx)(Hr,{content:Ve})}),Be&&(0,Zn.jsx)(Nn,{status:Be,errorMessage:Q,authorized:be}),Y&&(0,Zn.jsx)("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:I=>{I.target===I.currentTarget&&ke(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,Zn.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,Zn.jsx)(fa,{sessionId:Y.sessionId,nonce:Y.nonce,checkoutMode:"full",billingApiUrl:Ae,locale:he,theme:q,...pe?{appearance:pe}:{},buttonsTheme:ie,buttonsStyles:O,initialErrorMessage:Y.errorMessage,cardTitleContent:null,onComplete:ye,onError:at,onDecline:k})})})]})}var ha=require("@flopay/js/card-setup"),En=require("@flopay/shared"),St=require("react");var sr=require("react/jsx-runtime"),Lo=class extends En.FloPayError{constructor(t,n,r){super(t,n,r),this.name="FloPayCardSetupError",this.retryable=r.retryable}};function Ls(e,t={}){let n=e instanceof En.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 Lo(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 Ns({sessionId:e,nonce:t,billingApiUrl:n,telemetry:r,theme:o="modern-light",containerStyle:i,loading:d=null,onReady:c,onComplete:h,onDecline:y,onCancel:f,onValidation:g,onError:p}){let[w,F]=(0,St.useState)(null),[L,he]=(0,St.useState)(null),[q,P]=(0,St.useState)(null),[ie,O]=(0,St.useState)(null),[de,G]=(0,St.useState)(null),ve=(0,St.useRef)(!1),Ve=(0,St.useRef)(!1),we=(0,St.useMemo)(()=>{if(typeof o=="object")return o;let Q=(0,En.resolveTheme)(o);if(Q)return ia({appearance:Q.appearance,buttonsStyles:Q.buttonsLayout,layout:"default"})},[o]),wt=(0,St.useRef)(c),qe=(0,St.useRef)(p),Me=(0,St.useRef)(h),Ae=(0,St.useRef)(y),se=(0,St.useRef)(f),re=(0,St.useRef)(g),D=(0,St.useRef)(!1),Be=(0,St.useRef)(!1),Fe=(0,St.useRef)(0);return wt.current=c,qe.current=p,Me.current=h,Ae.current=y,se.current=f,re.current=g,(0,St.useEffect)(()=>{let Q=Fe.current+1;return Fe.current=Q,()=>{queueMicrotask(()=>{Fe.current===Q&&(D.current||Be.current||(Be.current=!0,nt(()=>{se.current?.({status:"cancelled",sessionId:e})})))})}},[e]),(0,St.useEffect)(()=>{let Q=!0,Ee=new ha.PaymentAPI((0,En.resolveBillingApiUrl)(n),{telemetry:r});return F(null),he(null),P(null),D.current=!1,Be.current=!1,(async()=>{try{if(!e.trim())throw new En.FloPayError("FloPayCardSetup requires a sessionId.","validation_error",{code:"MissingCheckoutSessionId",param:"sessionId"});if(!t.trim())throw new En.FloPayError("FloPayCardSetup requires a session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let be=await Ee.getUnifiedCheckoutSession(e,t);if(!Q)return;let x=be.data.session;if(!x||!(0,En.isCardSetupCheckoutSession)(x))throw new En.FloPayError("FloPayCardSetup only accepts a zero-amount, productless setup session.","validation_error",{code:"InvalidCardSetupSession",param:"sessionId"});let Y=x.vault;if(Y?.html?.trim()||(Y=await Ee.getVaultCapture(e,t)),!Y.html?.trim())throw new En.FloPayError("FloPay: this setup session has no vault card capability. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});if(!Q)return;he(Y),F(new ha.PciVaultCardCapture({sessionId:e,operation:"card_setup",telemetry:r}))}catch(be){if(!Q)return;let x=Ls(be);D.current=!0,P(x),nt(()=>qe.current?.(x))}})(),()=>{Q=!1,Ee.destroy()}},[n,t,e,r]),(0,St.useEffect)(()=>{if(!w)return;let Q=!1;Ve.current=!1,ve.current=!1;let Ee=w.on("submitting",()=>{ve.current=!0,G(null),O("processing")}),be=w.on("complete",Y=>{D.current=!0,ve.current=!1,O("success"),(async()=>(await new Promise(ke=>setTimeout(ke,1200)),!Ve.current&&(Ve.current=!0,nt(()=>{Me.current?.({status:"succeeded",sessionId:e,...Y.paymentMethod?{paymentMethod:Y.paymentMethod}:{}})}),Q||O(null))))()}),x=w.on("decline",Y=>{D.current=!0,ve.current=!1,G(Y.message??null),O("error"),nt(()=>{Ae.current?.({status:"declined",sessionId:e,...Y.declineReason?{reason:Y.declineReason}:{},...Y.message?{message:Y.message}:{}})}),(async()=>(await new Promise(ke=>setTimeout(ke,1500)),Q||O(null)))()});return()=>{Q=!0,Ee(),be(),x()}},[w,e]),q?(0,sr.jsx)("div",{role:"alert",children:q.message}):!w||!L?.html?(0,sr.jsx)(sr.Fragment,{children:d}):(0,sr.jsxs)(sr.Fragment,{children:[ie&&(0,sr.jsx)(Nn,{status:ie,errorMessage:de,processingLabel:"SAVING CARD...",successLabel:"CARD SAVED",errorLabel:"CARD NOT SAVED",successNote:null}),(0,sr.jsx)(oo,{capture:w,html:L.html,messageToken:L.messageToken,expectedOrigin:L.expectedOrigin,theme:we,containerStyle:i,onReady:()=>{nt(()=>wt.current?.())},onValidation:Q=>{nt(()=>re.current?.(Q))},onError:Q=>{if(!Q)return;ve.current&&(ve.current=!1,G(Q),O("error"),setTimeout(()=>O(null),1500));let Ee=Ls(new Error(Q),{code:"card_setup_widget_failed",retryable:!0});nt(()=>qe.current?.(Ee))}})]})}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&&ge(Lr),n&&(r||o)&&ge(Lr),n&&(0,k.jsx)("button",{type:"button",onClick:()=>{e?.("card"),p(!0)},style:{width:"100%",...V,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,k.jsx)(Hr,{content:v})}),(0,k.jsx)("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}var rr=require("react/jsx-runtime"),yc=44;function Ds(e){return new Promise(t=>setTimeout(t,e))}function fc(e,t){return e instanceof Kn.FloPayError?e:new Kn.FloPayError(e instanceof Error?e.message:t,"api_error")}function gc(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function hc(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 Ls({sessionId:e,nonce:t,createSession:n,paymentMethodId:r,checkoutMethod:o,clientId:i,products:d,items:c,subscriptions:v,account:y,successUrl:f,cancelUrl:g,couponCodes:p,tagsData:I,utmMetadata:F,billingApiUrl:N,locale:ge,theme:V,appearance:S,buttonsTheme:se,buttonsStyles:q,onSuccess:de,onError:G,onDecline:he,children:Ke,disabled:Se=!1,type:Rt="button",style:$e,...Ae}){let Be=(0,Ve.useMemo)(()=>(0,Kn.resolveBillingApiUrl)(N),[N]),le=(0,Ve.useMemo)(()=>hc({createSession:n,clientId:i,products:d,items:c,subscriptions:v,account:y,successUrl:f,cancelUrl:g,couponCodes:p,tagsData:I,utmMetadata:F}),[y,g,i,p,n,d,c,v,f,I,F]),[ae,D]=(0,Ve.useState)(!1),[Fe,De]=(0,Ve.useState)(null),[te,Re]=(0,Ve.useState)(null),[ve,x]=(0,Ve.useState)(!1),[Q,we]=(0,Ve.useState)(null),ue=(0,Ve.useRef)(!0),ce=(0,Ve.useRef)(null),ze=(0,Ve.useRef)(Q),rt=(0,Ve.useRef)(de),gt=(0,Ve.useRef)(G),Ge=(0,Ve.useRef)(he);(0,Ve.useEffect)(()=>{ze.current=Q},[Q]),(0,Ve.useEffect)(()=>{rt.current=de},[de]),(0,Ve.useEffect)(()=>{gt.current=G},[G]),(0,Ve.useEffect)(()=>{Ge.current=he},[he]),(0,Ve.useEffect)(()=>(ue.current=!0,()=>{ue.current=!1,ce.current?.abort()}),[]),(0,Ve.useEffect)(()=>{if(typeof window>"u")return;let R=A=>{A.key==="Escape"&&we(null)};return window.addEventListener("keydown",R),()=>{window.removeEventListener("keydown",R)}},[]);let ie=(0,Ve.useCallback)((R,A=To)=>{Ge.current?.(Qt(A,R,{code:R.code,declineCode:R.declineCode}))},[]),Y=(0,Ve.useCallback)(async R=>{ue.current&&(Re(null),x(R.result.status==="authorized"),De("success"),await Ds(1200),ue.current&&nt(()=>rt.current?.(R)))},[]),$=(0,Ve.useCallback)(async(R,A)=>{ue.current&&(gt.current?.(R),A?.emitDecline&&ie(R,A.method),Re(R.message),x(!1),De("error"),await Ds(1500))},[ie]),Ue=(0,Ve.useCallback)(async(R,A,ht)=>{let Je=R.data.session??null;if(!Je)throw new Kn.FloPayError("No session data returned","api_error");let Yt=Je.clientSecret||t;if(Gr(Je)){await Y({result:Ar(Je,A),session:Je,sessionId:Je.id||A,autoCompleted:!1});return}if(Je.status==="expired")throw Wo(Je);try{if(R.autoProcessingPending){let Gt=(await new fa.PaymentAPI(Be).waitForCheckoutSessionCompletion(R.autoProcessingPending.sessionId,{initialDelayMs:R.autoProcessingPending.retryAfterMs})).data.session;if(!Gr(Gt))throw Go(Gt);await Y({result:Ar(Gt,A),session:Gt,sessionId:Gt.id||A,autoCompleted:!1});return}if(R.autoProcessingError){if(R.autoProcessingError.type==="3ds_required"&&R.autoProcessingError.nextActionRedirectUrl&&A&&Yt){let L=new AbortController;ce.current=L;let jt;try{jt=await ss({billingApiUrl:Be,sessionId:A,nonce:Yt,nextActionRedirectUrl:R.autoProcessingError.nextActionRedirectUrl,signal:L.signal})}finally{ce.current===L&&(ce.current=null)}if(jt.status==="declined")throw Ir({type:jt.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:jt.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:R.autoProcessingError.checkoutMethod});let Lt=(await new fa.PaymentAPI(Be).waitForCheckoutSessionCompletion(A,{initialDelayMs:0,nonce:Yt})).data.session;if(!Gr(Lt))throw Ir({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:R.autoProcessingError.checkoutMethod});await Y({result:Ar(Lt,A),session:Lt,sessionId:Lt.id||A,autoCompleted:!1});return}throw Ir(R.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:R.autoProcessingError.checkoutMethod})}if(ht?.fromCreateSession&&R.autoProcessingAttempted===!0)throw Ir({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let fn=await ro({billingApiUrl:Be,sessionId:A??Je.id,session:Je,nonce:Yt});if(fn.type!=="success")throw Ir({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await Y({result:fn.result,session:Je,sessionId:Je.id||A,autoCompleted:!1})}catch(fn){let L=xo(fn),jt=Je.id||A;await $(L,{emitDecline:!0,method:L.checkoutMethod??To}),gc(L,jt)&&jt&&ue.current&&we({sessionId:jt,errorMessage:L.message,nonce:Yt||void 0})}},[t,Be,$,Y]),Qe=(0,Ve.useCallback)(async R=>{if(Ae.onClick?.(R),!(R.defaultPrevented||Se||ae)){if(we(null),e&&le){let A=new Kn.FloPayError("Provide either sessionId or create-session props, not both.","validation_error");await $(A),ue.current&&(De(null),Re(null));return}if(!e&&!le){let A=new Kn.FloPayError("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await $(A),ue.current&&(De(null),Re(null));return}D(!0),Re(null),x(!1),De("processing");try{let A=new fa.PaymentAPI(Be);if(e){let ht=await A.getUnifiedCheckoutSession(e,t);await Ue(ht,e);return}try{let ht=await A.createAndFetchSession({...le});await Ue(ht,ht.data.session?.id??null,{fromCreateSession:!0})}catch(ht){if(Yo(ht)==="session_auto_completed"){await Y({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw ht}}catch(A){await $(fc(A,"Automatic payment failed. Please try again."))}finally{ue.current&&(De(null),Re(null),D(!1))}}},[Ae.onClick,le,Se,ae,t,Ue,Be,e,$,Y]),ye=(0,Ve.useCallback)(R=>{let A=ze.current;we(null),rt.current?.({result:R,session:null,sessionId:A?.sessionId??null,autoCompleted:!1})},[]),ot=(0,Ve.useCallback)(R=>{gt.current?.(R)},[]),ne=(0,Ve.useCallback)(R=>{Ge.current?.(R)},[]),h=(0,Ve.useMemo)(()=>(0,Kn.resolveTheme)(V),[V]),tt=(0,Ve.useMemo)(()=>{let R=h?.buttonsLayout??(0,Kn.resolveButtonsLayoutTheme)(se);return q?{...R,...q,cardButton:{...R.cardButton,...q.cardButton}}:R},[h,se,q]),Ee=(0,Ve.useMemo)(()=>{let R=h?.appearance;return S?R?{...R,...S,variables:{...R.variables,...S.variables}}:S:R},[S,h]),O=Ee?.variables,Le=O?.colorPrimary??"#4A49FF",xe=O?.colorPrimaryHover??ao(Le,.12),pt=O?.borderRadius??"8px";return(0,rr.jsxs)(rr.Fragment,{children:[(0,rr.jsx)("button",{...Ae,type:Rt,onClick:Qe,disabled:Se||ae,"aria-busy":ae,style:{width:"100%",...Ke===void 0?{boxSizing:"border-box",height:yc,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...tt.cardButton,...Ga({themeBundle:h,resolvedPrimaryColor:Le,resolvedBorderRadius:pt,submitButtonStyle:tt.submitButton,explicitPrimaryColor:O?.colorPrimary}),fontSize:tt.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:Se||ae?"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||ae?.6:1,...$e},onMouseEnter:R=>{Ae.onMouseEnter?.(R),!R.defaultPrevented&&!Se&&!ae&&(h||O?.colorPrimary)&&(R.currentTarget.style.backgroundColor=xe)},onMouseLeave:R=>{Ae.onMouseLeave?.(R),!R.defaultPrevented&&(h||O?.colorPrimary)&&(R.currentTarget.style.backgroundColor=Le)},onMouseDown:R=>{Ae.onMouseDown?.(R),R.defaultPrevented||(R.currentTarget.style.transform="scale(0.985)")},onMouseUp:R=>{Ae.onMouseUp?.(R),R.defaultPrevented||(R.currentTarget.style.transform="scale(1)")},children:(0,rr.jsx)(Hr,{content:Ke})}),Fe&&(0,rr.jsx)(jn,{status:Fe,errorMessage:te,authorized:ve}),Q&&(0,rr.jsx)("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:R=>{R.target===R.currentTarget&&we(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,rr.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,rr.jsx)(ya,{sessionId:Q.sessionId,nonce:Q.nonce,checkoutMode:"full",billingApiUrl:Be,locale:ge,theme:V,...Ee?{appearance:Ee}:{},buttonsTheme:se,buttonsStyles:q,initialErrorMessage:Q.errorMessage,cardTitleContent:null,onComplete:ye,onError:ot,onDecline:ne})})})]})}var ga=require("@flopay/js/card-setup"),Bn=require("@flopay/shared"),It=require("react");var cr=require("react/jsx-runtime"),Lo=class extends Bn.FloPayError{constructor(t,n,r){super(t,n,r),this.name="FloPayCardSetupError",this.retryable=r.retryable}};function Ns(e,t={}){let n=e instanceof Bn.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 Lo(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 Os({sessionId:e,nonce:t,billingApiUrl:n,telemetry:r,theme:o="modern-light",containerStyle:i,loading:d=null,onReady:c,onComplete:v,onDecline:y,onCancel:f,onValidation:g,onError:p}){let[I,F]=(0,It.useState)(null),[N,ge]=(0,It.useState)(null),[V,S]=(0,It.useState)(null),[se,q]=(0,It.useState)(null),[de,G]=(0,It.useState)(null),he=(0,It.useRef)(!1),Ke=(0,It.useRef)(!1),Se=(0,It.useMemo)(()=>{if(typeof o=="object")return o;let te=(0,Bn.resolveTheme)(o);if(te)return ia({appearance:te.appearance,buttonsStyles:te.buttonsLayout,layout:"default"})},[o]),Rt=(0,It.useRef)(c),$e=(0,It.useRef)(p),Ae=(0,It.useRef)(v),Be=(0,It.useRef)(y),le=(0,It.useRef)(f),ae=(0,It.useRef)(g),D=(0,It.useRef)(!1),Fe=(0,It.useRef)(!1),De=(0,It.useRef)(0);return Rt.current=c,$e.current=p,Ae.current=v,Be.current=y,le.current=f,ae.current=g,(0,It.useEffect)(()=>{let te=De.current+1;return De.current=te,()=>{queueMicrotask(()=>{De.current===te&&(D.current||Fe.current||(Fe.current=!0,nt(()=>{le.current?.({status:"cancelled",sessionId:e})})))})}},[e]),(0,It.useEffect)(()=>{let te=!0,Re=new ga.PaymentAPI((0,Bn.resolveBillingApiUrl)(n),{telemetry:r});return F(null),ge(null),S(null),D.current=!1,Fe.current=!1,(async()=>{try{if(!e.trim())throw new Bn.FloPayError("FloPayCardSetup requires a sessionId.","validation_error",{code:"MissingCheckoutSessionId",param:"sessionId"});if(!t.trim())throw new Bn.FloPayError("FloPayCardSetup requires a session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let ve=await Re.getUnifiedCheckoutSession(e,t);if(!te)return;let x=ve.data.session;if(!x||!(0,Bn.isCardSetupCheckoutSession)(x))throw new Bn.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 Re.getVaultCapture(e,t)),!Q.html?.trim())throw new Bn.FloPayError("FloPay: this setup session has no vault card capability. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});if(!te)return;ge(Q),F(new ga.PciVaultCardCapture({sessionId:e,operation:"card_setup",telemetry:r}))}catch(ve){if(!te)return;let x=Ns(ve);D.current=!0,S(x),nt(()=>$e.current?.(x))}})(),()=>{te=!1,Re.destroy()}},[n,t,e,r]),(0,It.useEffect)(()=>{if(!I)return;let te=!1;Ke.current=!1,he.current=!1;let Re=I.on("submitting",()=>{he.current=!0,G(null),q("processing")}),ve=I.on("complete",Q=>{D.current=!0,he.current=!1,q("success"),(async()=>(await new Promise(we=>setTimeout(we,1200)),!Ke.current&&(Ke.current=!0,nt(()=>{Ae.current?.({status:"succeeded",sessionId:e,...Q.paymentMethod?{paymentMethod:Q.paymentMethod}:{}})}),te||q(null))))()}),x=I.on("decline",Q=>{D.current=!0,he.current=!1,G(Q.message??null),q("error"),nt(()=>{Be.current?.({status:"declined",sessionId:e,...Q.declineReason?{reason:Q.declineReason}:{},...Q.message?{message:Q.message}:{}})}),(async()=>(await new Promise(we=>setTimeout(we,1500)),te||q(null)))()});return()=>{te=!0,Re(),ve(),x()}},[I,e]),V?(0,cr.jsx)("div",{role:"alert",children:V.message}):!I||!N?.html?(0,cr.jsx)(cr.Fragment,{children:d}):(0,cr.jsxs)(cr.Fragment,{children:[se&&(0,cr.jsx)(jn,{status:se,errorMessage:de,processingLabel:"SAVING CARD...",successLabel:"CARD SAVED",errorLabel:"CARD NOT SAVED",successNote:null}),(0,cr.jsx)(oo,{capture:I,html:N.html,messageToken:N.messageToken,expectedOrigin:N.expectedOrigin,theme:Se,containerStyle:i,onReady:()=>{nt(()=>Rt.current?.())},onValidation:te=>{nt(()=>ae.current?.(te))},onError:te=>{if(!te)return;he.current&&(he.current=!1,G(te),q("error"),setTimeout(()=>q(null),1500));let Re=Ns(new Error(te),{code:"card_setup_widget_failed",retryable:!0});nt(()=>$e.current?.(Re))}})]})}0&&(module.exports={DirectPayPalButton,FloPayAutomaticPaymentButton,FloPayCardSetup,FloPayCardSetupError,FloPayCheckout,FloPayProvider,SplitCardForm,VaultCardFields,dropThirdPartyOnlyError,useCheckout,useFloPay,usePayPalFloPay});