@flopay/react 1.9.5 → 1.9.7

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 ll=Object.create;var Ho=Object.defineProperty;var cl=Object.getOwnPropertyDescriptor;var dl=Object.getOwnPropertyNames;var ul=Object.getPrototypeOf,pl=Object.prototype.hasOwnProperty;var ml=(e,t)=>{for(var n in t)Ho(e,n,{get:t[n],enumerable:!0})},Vi=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of dl(t))!pl.call(e,o)&&o!==n&&Ho(e,o,{get:()=>t[o],enumerable:!(r=cl(t,o))||r.enumerable});return e};var Ki=(e,t,n)=>(n=e!=null?ll(ul(e)):{},Vi(t||!e||!e.__esModule?Ho(n,"default",{value:e,enumerable:!0}):n,e)),yl=e=>Vi(Ho({},"__esModule",{value:!0}),e);var Cc={};ml(Cc,{DirectPayPalButton:()=>Ro,FloPayAutomaticPaymentButton:()=>Us,FloPayCardSetup:()=>$s,FloPayCardSetupError:()=>Lo,FloPayCheckout:()=>ba,FloPayProvider:()=>_o,SplitCardForm:()=>fa,VaultCardFields:()=>ao,dropThirdPartyOnlyError:()=>js.dropThirdPartyOnlyError,useCheckout:()=>Qi,useFloPay:()=>vr,usePayPalFloPay:()=>Jo});module.exports=yl(Cc);var js=require("@flopay/shared");var Ca=require("@flopay/js"),Kn=require("@flopay/shared"),Ve=require("react");var Tt=require("react/jsx-runtime");function fl(){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 gl(){return(0,Tt.jsx)(Tt.Fragment,{children:"Go back"})}function hl(){return(0,Tt.jsx)(Tt.Fragment,{children:"Secure card checkout"})}function Vr(e){return e!==void 0&&(e===""||e===null||e===!1)}function Kr({content:e}){return(0,Tt.jsx)(Tt.Fragment,{children:e===void 0?(0,Tt.jsx)(fl,{}):e})}function Hr({content:e}){return(0,Tt.jsx)(Tt.Fragment,{children:e===void 0?(0,Tt.jsx)(gl,{}):e})}function bo({content:e}){return(0,Tt.jsx)(Tt.Fragment,{children:e===void 0?(0,Tt.jsx)(hl,{}):e})}var An=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()},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 Hi(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 Oa(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 Wi(e,t){let n=e.products??[...(e.subscriptions??[]).map(i=>({type:"subscription",code:i.code??i.providerPlanId,name:i.subscriptionName??i.providerPlanName??i.code??i.providerPlanId??null,quantity:i.quantity??1,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount,currency:i.currency,metadata:i.metadata})),...(e.items??[]).map(i=>({type:"item",code:i.code??i.providerItemId,name:i.itemName??i.providerItemName??i.code??i.providerItemId??null,quantity:i.quantity??1,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount,currency:i.currency,metadata:i.metadata}))],r=n.reduce((i,d)=>i+(d.overrideAmount??d.totalAmount??0),0),o=e.currency??n.find(i=>i.currency)?.currency??"USD";return{id:"",clientSecret:"",mode:n.some(i=>i.type==="subscription")?"subscription":"payment",amount:Math.round(r*100),currency:o,status:"open",captureMethod:e.captureMethod,customer:{id:e.account.userId,email:e.account.email??"",firstName:e.account.firstName,lastName:e.account.lastName,gender:e.account.gender??void 0,city:e.account.city??void 0,state:e.account.state??void 0,country:e.account.country??void 0,zip:e.account.zip??void 0},successUrl:e.successUrl,cancelUrl:e.cancelUrl,checkoutMode:t??e.checkoutMode??"full",products:n.map((i,d)=>({uuid:`synthetic-${i.type??"item"}-${d}`,checkoutSessionId:"",type:i.type??"item",code:i.code,name:i.name??null,quantity:i.quantity??1,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount??null,currency:i.currency??o,metadata:i.metadata??null}))}}function xr(e){if((0,An.isCardHolderNamePlaceholder)(e))return{};let[t,...n]=e?.trim().split(/\s+/)??[];return t?{firstName:t,lastName:n.join(" ")||void 0}:{}}function za(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 vl=[{match:/^paypal authorization required\.?$/i,replacement:"For your additional security, please re-authenticate this payment via PayPal."}];function Sr(e){if(typeof e!="string")return e??void 0;let t=e.trim();if(!t)return e;for(let{match:n,replacement:r}of vl)if(n.test(t))return r;return e}function Mr(e,t){return e.status!=="authorized"?{status:"succeeded"}:{status:"authorized",paymentId:e.paymentId,sessionId:e.id||t||void 0,authorizationExpiresAt:e.authorizationExpiresAt}}function Yr(e){return e?.status==="authorized"||e?.status==="complete"}function Yi(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function Wo(e){let t=Yi(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=Yi(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 Co(e,t){return e==="processing"||(0,An.isMoneySettledOutcome)(e,t)}function Gi(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}function Ji(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 Ua(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 Fr=require("@flopay/js"),Me=require("@flopay/shared"),w=Ki(require("react"),1);var qa=require("react"),qn=(0,qa.createContext)({flopay:null,paypalFlopay:null,billingApiUrl:""}),tr=(0,qa.createContext)({session:null,loading:!1,error:null});var Qo=require("@flopay/js"),qt=require("@flopay/shared"),os=require("@paypal/paypal-js"),_=require("react");var Xi=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 Gr(){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 Jr({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,Xi.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 bl(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 Ar(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 Ar(t.code)??Ar(t.type)??Ar(t.name)}function Xr(e){if(!(typeof e!="object"||e===null))return Ar(e.decline_code)}function So(e){return typeof e!="object"||e===null?!1:Ar(e.type)?.toLowerCase()==="card_error"||Xr(e)!==void 0}function wr(e){let t=bl(e)?.toLowerCase()??"",r=`${hr(e)?.toLowerCase()??""} ${t}`;return r.includes("popup")&&r.includes("block")}var Zi=require("@flopay/shared"),wo=require("react");function vr(){return(0,wo.useContext)(qn).flopay}function Jo(){return(0,wo.useContext)(qn).paypalFlopay??null}function Qi(){return(0,wo.useContext)(tr)}function es(){return(0,wo.useContext)(qn).billingApiUrl||(0,Zi.resolveBillingApiUrl)()}var ts=require("@flopay/shared"),Br=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"),ko=typeof window>"u"?Xo.useEffect:Xo.useLayoutEffect;var Cl={"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 Pl(e){return e==="stripe"||e==="paypal"?e:void 0}function Sl(e){let t=Pl(e.provider),n={schemaVersion:ts.FLO_INSTRUMENT_SCHEMA_VERSION,...t?{gateway:t}:{}};if(e.class==="lifecycle"){let r=Cl[e.name];return r?{...n,name:r}:null}return e.class==="card_surface"?{...n,name:"card_expanded"}:e.errorCode==="CHECKOUT_SESSION_CREATE_FAILED"?{...n,name:"checkout_error",phase:"session_create"}:e.errorCode==="SDK_INITIALIZATION_FAILED"||e.errorCode==="PROVIDER_LOAD_FAILED"?{...n,name:"checkout_error",phase:"sdk_load"}:e.errorCode==="PAYMENT_PROCESSING_FAILED"?{...n,name:"checkout_error",phase:e.requestCategory==="intent_create"?"wallets":"process"}:null}var $a=new Set(["checkout_mount","sdk_loaded","form_rendered","card_expanded"]);function Zr(e,t){let n=(0,Br.useRef)(e);n.current=e;let r=(0,Br.useRef)(new Set),o=(0,Br.useRef)(t),i=(0,Br.useRef)(t);return ko(()=>{i.current=t,o.current!==t&&(o.current=t,r.current.clear())},[t]),(0,Br.useCallback)(d=>{if(i.current!==t)return;let c=Sl(d);if(c){if($a.has(c.name)){if(r.current.has(c.name))return;r.current.add(c.name)}nt(()=>n.current?.(c))}},[t])}var wl=Symbol.for("@flopay/js.telemetry.bridge.v1"),kl=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function Il(){return{error:()=>{},log:()=>{},performance:()=>{},terminal:()=>{},now:()=>globalThis.performance?.now()??0,elapsed:e=>Math.max(0,(globalThis.performance?.now()??e)-e),setCheckoutContext:()=>{},beginCheckout:()=>globalThis.performance?.now()??0,disable:()=>{},subscribe:()=>()=>{},flush:async()=>{},destroy:()=>{}}}function Rl(e){let t=Il(),n=(o,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[kl];return Rl(t?.(e)??{})}function Wt(e){if(e)return e[wl]}var yn=require("react");function Io(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,El=1e3,_l=11e3,Tl=["https://www.paypal.com","https://www.sandbox.paypal.com"],ns="We couldn't open PayPal. Try again or choose another payment method.",xl={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 rs(e){return e.includes("No ack for postMessage init()")&&Tl.some(t=>e.includes(t))&&e.includes("10000ms")}function Ml(e){return e?`${ns} Allow pop-ups for this site, then try again.`:ns}function Al(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 Bl(e){return e>=500?"5xx":e>=400?"4xx":e>=300?"3xx":"unknown"}function as({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:Pe,onInstrument:Rt,debug:$e=!1}){let Ae=vr(),Be=Zr(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(Pe??{}),z.beginCheckout(Pe??{}),z},[n,Ae,Ke,Pe?.checkoutMode,Pe?.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),Ie=(0,_.useRef)(!1),[ve,x]=(0,_.useState)(!1),[Q,Se]=(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}=Gr(),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,Re=(0,_.useMemo)(()=>n.replace(/\/+$/,""),[n]),Le=G?.gateways?.paypal?.providerObjectType??f,Te=Le??(y?"subscription":"order"),pt=Le==="order"||Le==="setup_token",mt=(0,_.useMemo)(()=>JSON.stringify([Re,d,v,c??"",Te,pt,e,he??""]),[Re,d,v,c,he,Te,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(we=>[...we,`${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||!Ie.current||(Ie.current=!1,en())},[en,ve,ue]);let Xt=(0,_.useCallback)((z,we)=>{let tn=gn.current;if(tn){tn("paypal",z,we);return}lt.current?.(Ml(we?.popupBlocked??wr(z)))},[]),Rn=(0,_.useCallback)((z,we,tn)=>{Xt(we,tn),gt(!0),Ot(),Kt()},[Kt,Xt,Ot]),{finishAttempt:xt,invalidateAttempt:sn,isAttemptCurrent:Pt,isAttemptInvalidated:P,startAttempt:ft}=Io(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 we=Xe.current;return we&&bn.current.set(z,we),z};(0,_.useEffect)(()=>{R.current!==mt&&(R.current=mt,Ge.current=!1,ie.current=!1,x(!1),Se(!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)",we=typeof navigator>"u"?"(no navigator)":navigator.userAgent;if(L(`mount clientId=${z} env=${c??"(unset)"}\u2192${dr??"live"} ccy=${v} sub=${y}`),L(`ua=${we.slice(0,80)}${we.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,Ee=()=>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,Ir=!1,Rr=null,En=!1,ur=()=>{!Rr||En||(En=!0,Rr.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(Ee())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(Ee())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||Ee()||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(!Ee())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(Ee()||re(T))return;let m=Sr(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(Ir)return;Ir=!0,dn=!0,U(),ur();let b=m||rs(T);if(b&&se&&!Ge.current){Ge.current=!0,x(!1),Qe(!1),Se(!0),Nt.current?.("retrying"),un=setTimeout(()=>{tn||ce(H=>H+1)},El);return}if(b||K){if(x(!1),Qe(!1),Se(!1),$(!0),(!b||M===!0)&&We(M),Nt.current?.("exhausted"),!ie.current){ie.current=!0;let H="paypal_init_failure";rs(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(Ee())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(Re,{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(Ee())return;let Ze=await be.json().catch(()=>null),Ne=Ze?.message??"PayPal payment failed.",_e=Sr(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:Bl(be.status),failureCategory:be.status>=500?"server_error":void 0}),oe(_e),nt(()=>Lt.current?.(Qt("paypal",_e,{code:Ze?.code,declineCode:Ze?.declineCode})));return}catch(H){if(Ee())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=Sr(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=>Ee()?Promise.reject(E()):Promise.resolve(T),X=async T=>{if(Ee())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(Re,{telemetry:!1}).createSessionIntent(M,K??"",pt?{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:qt.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE,paymentMethodId:null,intentKind:Te==="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(Ee())throw E();if(b.provider!=="paypal"||b.providerObjectType!==Te)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=Xr(T)??hr(T)??"provider_declined";new Qo.PaymentAPI(Re,{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={};Te==="subscription"?m={intent:"subscription",vault:!0}:Te==="order"&&(m={intent:"capture"}),pe=(0,os.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=${Ee()} ns=${!!K} buttons=${!!K?.Buttons}`),Ee())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(Ee()||ze.current!==et)return;let Ne=be.vaultSetupToken??be.subscriptionID??be.orderID??"",_e=Ne?bn.current.get(Ne):Jt.current.get(et);if(!(!_e||!Pt(_e.generation))&&xt(_e.generation)){bn.current.delete(Ne),Jt.current.delete(_e.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=xr(ct.current??[bt?.customer?.firstName,bt?.customer?.lastName].filter(Boolean).join(" ")),xe=kn({email:_e.accountPatch?.email?.trim()||on.current?.trim()||bt?.customer?.email?.trim(),firstName:_e.accountPatch?.firstName?.trim()||nn.firstName,lastName:_e.accountPatch?.lastName?.trim()||nn.lastName});if(!(0,qt.isValidEmail)(xe.email)||!(xe.firstName||xe.lastName))try{let On=Al(await Ze?.order?.get?.());xe=kn({email:On.email||xe.email,firstName:On.firstName||xe.firstName,lastName:On.lastName||xe.lastName})}catch{}if((He.current||tt)&&!(0,qt.isValidEmail)(xe.email)){let On=await ot("PayPal",xe);if(!On)return;xe=On}(0,qt.isValidEmail)(xe.email)&&(_e.accountPatch=kn({..._e.accountPatch,...xe}),await He.current?.(xe));let Pn;Te==="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,_e)}catch(bt){oe(bt instanceof Error?bt.message:"PayPal capture failed.")}finally{Ee()||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(Ee()){await Ze.reject();return}zt();let Ne=yt.current,_e={};if(Ne)try{let xe=await Ne("paypal");if(Ee()){await Ze.reject();return}if(!xe.proceed){Xe.current=null,Jt.current.delete(et),await Ze.reject();return}_e={sessionId:xe.sessionId,accountPatch:xe.accountPatch,nonce:xe.nonce}}catch(xe){L(`onClick:runBeforeButtonClick rejected msg=${(xe instanceof Error?xe.message:String(xe)).slice(0,120)}`),Xe.current=null,Jt.current.delete(et),await Ze.reject();return}nt(()=>In.current?.("paypal"));let nn={generation:Et(),surfaceKey:et,..._e};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:Te==="order"?H("Failed to create PayPal order."):void 0,createSubscription:Te==="subscription"?H("Failed to create PayPal subscription."):void 0,createVaultSetupToken:Te==="setup_token"?async()=>cn(await X("Failed to create PayPal setup token.")):void 0,onApprove:b,onCancel:()=>{if(Ee())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"}),Ie.current=!0,_t({generation:be?.generation,remount:!0,focus:!1})},onError:be=>{if(Ee()||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(),So(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 _e=Ze.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"}),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,Rr=Ye,Nn=()=>{if(!dt||Tn||Ee()||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(!Ee()){for(let Ne of Ze)if(Ne.type==="childList")Ne.addedNodes.forEach(_e=>{if(!(_e instanceof Element))return;let bt=_e.tagName.toLowerCase(),nn=(_e.getAttribute("title")??"").slice(0,40),xe=bt==="iframe"?` ${qe(_e)}`:"";L(`child+ ${bt}${nn?` title="${nn}"`:""}${xe} dims=${xn(_e)}`)});else if(Ne.type==="attributes"&&Ne.target instanceof Element){let _e=Ne.target;if(_e.tagName.toLowerCase()!=="iframe")continue;let bt=Ne.attributeName;(bt==="src"||bt==="srcdoc")&&L(`attr~ iframe ${bt}=${bt==="srcdoc"?`[${(_e.getAttribute("srcdoc")??"").length}ch]`:Xn(_e.getAttribute("src"))} dims=${xn(_e)}`)}}}),Yn.observe(_n,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let be=Ze=>{if(Ee()||St)return;let Ne=_n.querySelectorAll("iframe"),_e=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=${_e} paypalNetRequests=${yr.value}`),Ne.forEach((bt,nn)=>{let xe=(bt.getAttribute("title")??"").slice(0,40);L(` iframe[${nn}] ${xn(bt)}${xe?` title="${xe}"`:""} ${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(()=>{Ee()||St||(L("watchdog:11s retryable render timeout"),ee("PayPal Buttons render did not settle within 11000ms.",!0,!0))},_l);let me=Ye.render(_n);(async()=>{try{if(await me,L(`render:resolved inactive=${Ee()}`),U(),Ee()){ur();return}St=!0,x(!0),Se(!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,Re,d,v,c,Te,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?`
1
+ "use strict";var wl=Object.create;var Yo=Object.defineProperty;var kl=Object.getOwnPropertyDescriptor;var Il=Object.getOwnPropertyNames;var Rl=Object.getPrototypeOf,El=Object.prototype.hasOwnProperty;var _l=(e,t)=>{for(var n in t)Yo(e,n,{get:t[n],enumerable:!0})},Gi=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Il(t))!El.call(e,o)&&o!==n&&Yo(e,o,{get:()=>t[o],enumerable:!(r=kl(t,o))||r.enumerable});return e};var Yi=(e,t,n)=>(n=e!=null?wl(Rl(e)):{},Gi(t||!e||!e.__esModule?Yo(n,"default",{value:e,enumerable:!0}):n,e)),Tl=e=>Gi(Yo({},"__esModule",{value:!0}),e);var Qc={};_l(Qc,{DirectPayPalButton:()=>Eo,FloPayAutomaticPaymentButton:()=>Qs,FloPayCardSetup:()=>rl,FloPayCardSetupError:()=>zo,FloPayCheckout:()=>wa,FloPayProvider:()=>To,SplitCardForm:()=>va,VaultCardFields:()=>so,dropThirdPartyOnlyError:()=>ol.dropThirdPartyOnlyError,useCheckout:()=>rs,useFloPay:()=>vr,usePayPalFloPay:()=>Qo});module.exports=Tl(Qc);var ol=require("@flopay/shared");var ka=require("@flopay/js"),Hn=require("@flopay/shared"),je=require("react");var _t=require("react/jsx-runtime");function xl(){return(0,_t.jsxs)(_t.Fragment,{children:[(0,_t.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,_t.jsx)("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),(0,_t.jsx)("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",(0,_t.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,_t.jsx)("path",{d:"M9 18l6-6-6-6"})})]})}function Ml(){return(0,_t.jsx)(_t.Fragment,{children:"Go back"})}function Al(){return(0,_t.jsx)(_t.Fragment,{children:"Secure card checkout"})}function Kr(e){return e!==void 0&&(e===""||e===null||e===!1)}function Wr({content:e}){return(0,_t.jsx)(_t.Fragment,{children:e===void 0?(0,_t.jsx)(xl,{}):e})}function Gr({content:e}){return(0,_t.jsx)(_t.Fragment,{children:e===void 0?(0,_t.jsx)(Ml,{}):e})}function Po({content:e}){return(0,_t.jsx)(_t.Fragment,{children:e===void 0?(0,_t.jsx)(Al,{}):e})}var An=require("@flopay/shared");function Yr(e,t,n,r={}){let o;return(a={})=>{if(o)return o;let l={...r,...a,email:a.email?.trim()||r.email?.trim()},c=(0,An.isCardHolderNamePlaceholder)(l.firstName,l.lastName);if(!(0,An.isValidEmail)(l.email))return Promise.reject(new An.FloPayError("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}));let y={};for(let[m,p]of Object.entries(l)){if(c&&m.endsWith("Name")||typeof p!="string")continue;let g=p.trim();g&&(y[m]=g)}return o=e.claimCheckoutSession(t,n,{accountData:y}),o.catch(()=>{}),o}}function Ji(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 qa(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 Xi(e,t){let n=e.products??[...(e.subscriptions??[]).map(a=>({type:"subscription",code:a.code??a.providerPlanId,name:a.subscriptionName??a.providerPlanName??a.code??a.providerPlanId??null,quantity:a.quantity??1,totalAmount:a.totalAmount,overrideAmount:a.overrideAmount,currency:a.currency,metadata:a.metadata})),...(e.items??[]).map(a=>({type:"item",code:a.code??a.providerItemId,name:a.itemName??a.providerItemName??a.code??a.providerItemId??null,quantity:a.quantity??1,totalAmount:a.totalAmount,overrideAmount:a.overrideAmount,currency:a.currency,metadata:a.metadata}))],r=n.reduce((a,l)=>a+(l.overrideAmount??l.totalAmount??0),0),o=e.currency??n.find(a=>a.currency)?.currency??"USD";return{id:"",clientSecret:"",mode:n.some(a=>a.type==="subscription")?"subscription":"payment",amount:Math.round(r*100),currency:o,status:"open",captureMethod:e.captureMethod,customer:{id:e.account.userId,email:e.account.email??"",firstName:e.account.firstName,lastName:e.account.lastName,gender:e.account.gender??void 0,city:e.account.city??void 0,state:e.account.state??void 0,country:e.account.country??void 0,zip:e.account.zip??void 0},successUrl:e.successUrl,cancelUrl:e.cancelUrl,checkoutMode:t??e.checkoutMode??"full",products:n.map((a,l)=>({uuid:`synthetic-${a.type??"item"}-${l}`,checkoutSessionId:"",type:a.type??"item",code:a.code,name:a.name??null,quantity:a.quantity??1,totalAmount:a.totalAmount,overrideAmount:a.overrideAmount??null,currency:a.currency??o,metadata:a.metadata??null}))}}function xr(e){if((0,An.isCardHolderNamePlaceholder)(e))return{};let[t,...n]=e?.trim().split(/\s+/)??[];return t?{firstName:t,lastName:n.join(" ")||void 0}:{}}function ja(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,a=typeof t=="string"?n?.declineCode:n?.declineCode??t.declineCode;return{method:e,message:r,...o?{code:o}:{},...a?{declineCode:a}:{}}}var Bl=[{match:/^paypal authorization required\.?$/i,replacement:"For your additional security, please re-authenticate this payment via PayPal."}];function Sr(e){if(typeof e!="string")return e??void 0;let t=e.trim();if(!t)return e;for(let{match:n,replacement:r}of Bl)if(n.test(t))return r;return e}function Mr(e,t){return e.status!=="authorized"?{status:"succeeded"}:{status:"authorized",paymentId:e.paymentId,sessionId:e.id||t||void 0,authorizationExpiresAt:e.authorizationExpiresAt}}function Jr(e){return e?.status==="authorized"||e?.status==="complete"}function Zi(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function Jo(e){let t=Zi(e);return new An.FloPayError(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function Xo(e){return e instanceof An.FloPayError||typeof e=="object"&&e!==null&&"code"in e?e.code:void 0}function Zo(e){let t=Zi(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 So(e,t){return e==="processing"||(0,An.isMoneySettledOutcome)(e,t)}function Qi(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}function es(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 Va(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 wo(e){let t=[e?.id,e?.originalPaymentMethodId];for(let n of t)if(typeof n=="string"&&n.startsWith("pm_"))return n}var Nr=require("@flopay/js"),Me=require("@flopay/shared"),I=Yi(require("react"),1);var Ha=require("react"),$n=(0,Ha.createContext)({flopay:null,paypalFlopay:null,billingApiUrl:""}),tr=(0,Ha.createContext)({session:null,loading:!1,error:null});var na=require("@flopay/js"),$t=require("@flopay/shared"),ls=require("@paypal/paypal-js"),T=require("react");var ts=require("@flopay/shared"),nr=require("react"),hr=require("react/jsx-runtime");function kn(e,t=!1){let{firstName:n,lastName:r,...o}=e,a=n?.trim(),l=r?.trim();return{...o,...a||t?{firstName:a??""}:{},...l||t?{lastName:l??""}:{}}}function Xr(){let[e,t]=(0,nr.useState)(null),n=(0,nr.useRef)(null),r=(0,nr.useRef)(0),o=(0,nr.useCallback)((l,c)=>(n.current?.(null),r.current+=1,t({id:r.current,methodLabel:l,identity:c}),new Promise(y=>{n.current=y})),[]),a=(0,nr.useCallback)(l=>{let c=n.current;n.current=null,t(null),c?.(l)},[]);return(0,nr.useEffect)(()=>()=>{n.current?.(null),n.current=null},[]),{request:e,collect:o,finish:a}}function Zr({identity:e,methodLabel:t,onComplete:n,onCancel:r,submitting:o=!1,testId:a="flopay-buyer-identity-pane"}){let[l,c]=(0,nr.useState)(e.email?.trim()??""),y=(0,ts.isValidEmail)(l.trim());return(0,hr.jsxs)("div",{"data-testid":a,style:{display:"flex",flexDirection:"column",gap:"0.75rem",padding:"0.875rem",border:"1px solid #d1d5db",borderRadius:8,background:"#fff",color:"#262833"},children:[(0,hr.jsxs)("div",{style:{fontWeight:700},children:["Continue with ",t]}),(0,hr.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",(0,hr.jsx)("input",{type:"email",autoComplete:"email","data-testid":"flopay-email",required:!0,value:l,onChange:m=>c(m.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]}),(0,hr.jsxs)("div",{style:{display:"flex",gap:"0.5rem"},children:[r&&(0,hr.jsx)("button",{type:"button",onClick:r,style:{flex:1,minHeight:42},children:"Cancel"}),(0,hr.jsxs)("button",{type:"button",disabled:!y||o,onClick:()=>{n(kn({...e,email:l.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 Ar(e){if(typeof e!="string")return;let t=e.trim();return/^[a-z0-9_.-]{1,64}$/i.test(t)?t:void 0}function br(e){if(typeof e!="object"||e===null)return;let t=e;return Ar(t.code)??Ar(t.type)??Ar(t.name)}function Qr(e){if(!(typeof e!="object"||e===null))return Ar(e.decline_code)}function ko(e){return typeof e!="object"||e===null?!1:Ar(e.type)?.toLowerCase()==="card_error"||Qr(e)!==void 0}function wr(e){let t=Fl(e)?.toLowerCase()??"",r=`${br(e)?.toLowerCase()??""} ${t}`;return r.includes("popup")&&r.includes("block")}var ns=require("@flopay/shared"),Io=require("react");function vr(){return(0,Io.useContext)($n).flopay}function Qo(){return(0,Io.useContext)($n).paypalFlopay??null}function rs(){return(0,Io.useContext)(tr)}function os(){return(0,Io.useContext)($n).billingApiUrl||(0,ns.resolveBillingApiUrl)()}var as=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 ea=require("react"),Br=typeof window>"u"?ea.useEffect:ea.useLayoutEffect;var Dl={"checkout.mount":"checkout_mount","sdk.initialize.ready":"sdk_loaded","provider.ready":"sdk_loaded","checkout.rendered":"form_rendered","vault.widget.ready":"form_rendered","vault.submission.started":"tokenize","payment.tokenization.started":"tokenize","payment.processing.started":"process_attempt","payment.intent.started":"process_attempt","vault.action.required":"3ds_challenge","payment.three_ds.handoff":"3ds_challenge"};function Nl(e){return e==="stripe"||e==="paypal"?e:void 0}function Ll(e){let t=Nl(e.provider),n={schemaVersion:as.FLO_INSTRUMENT_SCHEMA_VERSION,...t?{gateway:t}:{}};if(e.class==="lifecycle"){let r=Dl[e.name];return r?{...n,name:r}:null}return e.class==="card_surface"?{...n,name:"card_expanded"}:e.errorCode==="CHECKOUT_SESSION_CREATE_FAILED"?{...n,name:"checkout_error",phase:"session_create"}:e.errorCode==="SDK_INITIALIZATION_FAILED"||e.errorCode==="PROVIDER_LOAD_FAILED"?{...n,name:"checkout_error",phase:"sdk_load"}:e.errorCode==="PAYMENT_PROCESSING_FAILED"?{...n,name:"checkout_error",phase:e.requestCategory==="intent_create"?"wallets":"process"}:null}var Ka=new Set(["checkout_mount","sdk_loaded","form_rendered","card_expanded"]);function eo(e,t){let n=(0,Fr.useRef)(e);n.current=e;let r=(0,Fr.useRef)(new Set),o=(0,Fr.useRef)(t),a=(0,Fr.useRef)(t);return Br(()=>{a.current=t,o.current!==t&&(o.current=t,r.current.clear())},[t]),(0,Fr.useCallback)(l=>{if(a.current!==t)return;let c=Ll(l);if(c){if(Ka.has(c.name)){if(r.current.has(c.name))return;r.current.add(c.name)}nt(()=>n.current?.(c))}},[t])}var Ol=Symbol.for("@flopay/js.telemetry.bridge.v1"),zl=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function Ul(){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 $l(e){let t=Ul(),n=(o,a)=>o?o.bind(e):a,r=n(e.now,t.now);return{error:n(e.error,t.error),log:n(e.log,t.log),performance:n(e.performance,t.performance),terminal:n(e.terminal,t.terminal),now:r,elapsed:e.elapsed?e.elapsed.bind(e):o=>Math.max(0,r()-o),setCheckoutContext:n(e.setCheckoutContext,t.setCheckoutContext),beginCheckout:n(e.beginCheckout,t.beginCheckout),disable:n(e.disable,t.disable),subscribe:n(e.subscribe,t.subscribe),flush:n(e.flush,t.flush),destroy:n(e.destroy,t.destroy)}}function ta(e){let t=globalThis[zl];return $l(t?.(e)??{})}function Wt(e){if(e)return e[Ol]}var yn=require("react");function Ro(e){let t=(0,yn.useRef)(0),n=(0,yn.useRef)(null),r=(0,yn.useRef)(null),o=(0,yn.useCallback)((f=r.current)=>{f?.timer&&(clearTimeout(f.timer),f.timer=null)},[]),a=(0,yn.useCallback)(f=>{o();let P=t.current+1;return t.current=P,n.current=null,r.current={generation:P,method:f,timer:null,yieldedControl:!1},P},[o]),l=(0,yn.useCallback)(f=>{let P=r.current;return f!==void 0&&P?.generation!==f?!1:(o(P),r.current=null,(f===void 0||n.current===f)&&(n.current=null),!0)},[o]),c=(0,yn.useCallback)(f=>{let P=r.current,A=f??P?.generation??t.current;(f===void 0||P?.generation===f)&&(o(P),r.current=null),n.current=A},[o]),y=(0,yn.useCallback)(f=>n.current===(f??t.current),[]),m=(0,yn.useCallback)(f=>r.current?.generation===f&&n.current!==f,[]),p=(0,yn.useCallback)(()=>{let f=r.current;f&&(f.yieldedControl=!0,o(f))},[o]),g=(0,yn.useCallback)(()=>{let f=r.current;!f?.yieldedControl||document.visibilityState!=="visible"||(o(f),f.timer=setTimeout(()=>{f.timer=null,r.current?.generation===f.generation&&(r.current=null,n.current=f.generation,e(f.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}))},600))},[o,e]);return(0,yn.useEffect)(()=>{let f=()=>{document.visibilityState==="visible"?g():p()};return document.addEventListener("visibilitychange",f),window.addEventListener("blur",p),window.addEventListener("focus",g),()=>{document.removeEventListener("visibilitychange",f),window.removeEventListener("blur",p),window.removeEventListener("focus",g),o()}},[o,p,g]),{startAttempt:a,finishAttempt:l,invalidateAttempt:c,isAttemptInvalidated:y,isAttemptCurrent:m,generationRef:t}}var qn=require("react/jsx-runtime"),ra=45,ql=1e3,jl=11e3,Vl=["https://www.paypal.com","https://www.sandbox.paypal.com"],is="We couldn't open PayPal. Try again or choose another payment method.",Hl={width:"100%",minHeight:ra,margin:"0 0 0.5rem",padding:"0.75rem 0.875rem",border:"1px solid #2563eb",borderRadius:8,background:"#eff6ff",color:"#1d4ed8",fontSize:"0.95rem",fontWeight:700,cursor:"pointer"};function ss(e){return e.includes("No ack for postMessage init()")&&Vl.some(t=>e.includes(t))&&e.includes("10000ms")}function Kl(e){return e?`${is} Allow pop-ups for this site, then try again.`:is}function Wl(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 Gl(e){return e>=500?"5xx":e>=400?"4xx":e>=300?"3xx":"unknown"}function cs({sessionId:e,nonce:t,billingApiUrl:n,email:r,billingName:o,onBuyerIdentityReady:a,clientId:l,environment:c,currency:y,isSubscription:m,providerObjectType:p,onTokenizedBody:g,onComplete:f,onErrorChange:P,onDecline:A,onTechnicalFailure:D,isProcessing:he=!1,onLoadStateChange:H,onInitializationStateChange:S,allowAutomaticRetry:le=!0,onButtonClick:q,runBeforeButtonClick:pe,session:oe,existingOrderId:ce,telemetry:Ve,telemetryContext:de,onInstrument:Tt,debug:Ge=!1}){let Ae=vr(),Be=eo(Tt,e),ae=(0,T.useMemo)(()=>{if(Ae)return null;let U=ta({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:$t.SDK_VERSION,enabled:Ve!==!1});return U.setCheckoutContext(de??{}),U.beginCheckout(de??{}),U},[n,Ae,Ve,de?.checkoutMode,de?.layout]),ie=(0,T.useMemo)(()=>Wt(Ae),[Ae]);(0,T.useEffect)(()=>()=>{ae&&ae.flush().catch(()=>{}).finally(()=>ae.destroy())},[ae]);let O=(0,T.useMemo)(()=>({error:U=>{ie?ie.error(U):ae?.error(U),Be({class:"technical_error",errorCode:U.requestCategory==="intent_create"?"PAYMENT_PROCESSING_FAILED":U.errorCode,requestCategory:U.requestCategory,provider:U.provider})},log:U=>{ie?ie.log(U):ae?.log(U),Be({class:"lifecycle",name:U.name,provider:U.provider})},performance:U=>{ie?ie.performance(U):ae?.performance(U)},terminal:U=>{ie?ie.terminal(U):ae?.terminal(U)},startTiming:()=>ie?.now()??ae?.now()??0,elapsed:U=>ie?.elapsed(U)??Math.max(0,(ae?.now()??U)-U)}),[Be,ie,ae]),Le=(0,T.useRef)(null),Oe=(0,T.useRef)(0),_e=(0,T.useRef)(null),ze=(0,T.useRef)(!1),[Pe,w]=(0,T.useState)(!1),[ue,be]=(0,T.useState)(!1),[Y,L]=(0,T.useState)(0),Se=(0,T.useRef)(0),[rt,ht]=(0,T.useState)(!1),Ye=(0,T.useRef)(!1),se=(0,T.useRef)(!1),[J,j]=(0,T.useState)(!1),[Ue,Qe]=(0,T.useState)(!1),{request:fe,collect:ot,finish:te}=Xr(),b=(0,T.useRef)({sessionId:e,required:!(0,$t.isValidEmail)(r?.trim()||oe?.customer?.email?.trim())});b.current.sessionId!==e&&(b.current={sessionId:e,required:!(0,$t.isValidEmail)(r?.trim()||oe?.customer?.email?.trim())});let tt=b.current.required,Ie=(0,T.useMemo)(()=>n.replace(/\/+$/,""),[n]),Fe=oe?.gateways?.paypal?.providerObjectType??p,Te=Fe??(m?"subscription":"order"),mt=Fe==="order"||Fe==="setup_token",yt=(0,T.useMemo)(()=>JSON.stringify([Ie,l,y,c??"",Te,mt,e,ce??""]),[Ie,l,y,c,ce,Te,mt,e]),E=(0,T.useRef)(yt),B=E.current!==yt,bt=(0,T.useRef)(Ge),Je=(0,T.useRef)(null),[Gt,fn]=(0,T.useState)([]),N=(0,T.useCallback)(U=>{bt.current&&fn(we=>[...we,`${new Date().toISOString().slice(11,23)} ${U}`])},[]);(0,T.useEffect)(()=>{bt.current=Ge,Ge&&N("debug:enabled"),Je.current?.setEnabled(Ge)},[N,Ge]);let jt=(0,T.useRef)(g),Yt=(0,T.useRef)(f),lt=(0,T.useRef)(P),Nt=(0,T.useRef)(A),gn=(0,T.useRef)(D),In=(0,T.useRef)(q),hn=(0,T.useRef)(H),Lt=(0,T.useRef)(S),He=(0,T.useRef)(a),ft=(0,T.useRef)(pe),Pt=(0,T.useRef)(oe),on=(0,T.useRef)(r),ct=(0,T.useRef)(o),bn=(0,T.useRef)(t),Xe=(0,T.useRef)(null),Jt=(0,T.useRef)(new Map),vn=(0,T.useRef)(new Map),an=(0,T.useRef)(!1);(0,T.useEffect)(()=>(an.current=!0,()=>{an.current=!1}),[]),(0,T.useEffect)(()=>{jt.current=g},[g]),(0,T.useEffect)(()=>{He.current=a},[a]),(0,T.useEffect)(()=>{Yt.current=f},[f]),(0,T.useEffect)(()=>{lt.current=P},[P]),(0,T.useEffect)(()=>{Nt.current=A},[A]),(0,T.useEffect)(()=>{gn.current=D},[D]),(0,T.useEffect)(()=>{In.current=q},[q]),(0,T.useEffect)(()=>{hn.current=H},[H]),(0,T.useEffect)(()=>{Lt.current=S},[S]),(0,T.useEffect)(()=>{ft.current=pe},[pe]),(0,T.useEffect)(()=>{Pt.current=oe},[oe]),(0,T.useEffect)(()=>{on.current=r},[r]),(0,T.useEffect)(()=>{ct.current=o},[o]),(0,T.useEffect)(()=>{bn.current=t},[t]),(0,T.useEffect)(()=>{Se.current=Y},[Y]),(0,T.useEffect)(()=>{rt&&_e.current?.focus()},[rt,Y]);let Ht=(0,T.useCallback)(()=>{window.setTimeout(()=>{_e.current?.focus()},0)},[]),Ot=(0,T.useCallback)(()=>{w(!1),L(U=>U+1)},[]),en=(0,T.useCallback)(()=>{ht(!1),(Le.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??Le.current)?.focus?.()},[]);(0,T.useEffect)(()=>{!Pe||!ze.current||(ze.current=!1,en())},[en,Pe,Y]);let Xt=(0,T.useCallback)((U,we)=>{let tn=gn.current;if(tn){tn("paypal",U,we);return}lt.current?.(Kl(we?.popupBlocked??wr(U)))},[]),Rn=(0,T.useCallback)((U,we,tn)=>{Xt(we,tn),ht(!0),Ot(),Ht()},[Ht,Xt,Ot]),{finishAttempt:xt,invalidateAttempt:sn,isAttemptCurrent:St,isAttemptInvalidated:k,startAttempt:gt}=Ro(Rn),Rt=(0,T.useCallback)(()=>(ht(!1),gt("paypal")),[gt]),Et=(0,T.useCallback)(U=>{sn(U?.generation),U?.showRetry&&ht(!0),U?.remount&&Ot(),U?.focus!==!1&&Ht()},[Ht,sn,Ot]),cn=U=>{let we=Xe.current;return we&&vn.current.set(U,we),U};(0,T.useEffect)(()=>{E.current!==yt&&(E.current=yt,Ye.current=!1,se.current=!1,w(!1),be(!1),j(!1),Lt.current?.("loading"))},[yt]),(0,T.useEffect)(()=>{nt(()=>hn.current?.(Pe&&!J))},[Pe,J]);let ur=(0,$t.normalizeGatewayEnvironment)(c);(0,T.useEffect)(()=>{let U=l?`${l.slice(0,6)}\u2026(len ${l.length})`:"(empty)",we=typeof navigator>"u"?"(no navigator)":navigator.userAgent;if(N(`mount clientId=${U} env=${c??"(unset)"}\u2192${ur??"live"} ccy=${y} sub=${m}`),N(`ua=${we.slice(0,80)}${we.length>80?"\u2026":""}`),!l){N("FAIL: clientId empty \u2014 gateway misconfigured"),j(!0),O.error({errorCode:"CONFIGURATION_INVALID",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),console.error("[FloPay] DirectPayPal: clientId empty \u2014 gateway misconfigured");return}if(!Le.current){N("FAIL: containerRef not attached");return}Oe.current=O.startTiming(),O.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let tn=!1,dn=!1,Re=()=>tn||dn,Kn,Dn=!1,zt=()=>{Kn=(0,$t.generateIdempotencyKey)(),Kn||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),Dn=!0},un=null,Ir=!1,Rr=null,En=!1,pr=()=>{!Rr||En||(En=!0,Rr.close().catch(()=>{}))},Wn=null,Nn=()=>{Wn!==null&&(O.log({name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal"}),O.performance({stage:"overlay_return",durationMs:O.elapsed(Wn),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal"}),Wn=null)},wt=!1,or=!1,_n=Le.current,Gn=null,Cn=null,Yn=[],Jn=null,dt=!1,Tn=!1,Ln=null,xn=x=>{if(!x||typeof x.getBoundingClientRect!="function")return"(no rect)";let h=x.getBoundingClientRect();return`${Math.round(h.width)}\xD7${Math.round(h.height)}`},Xn=x=>{if(!x)return"(empty)";try{let h=new URL(x,typeof window>"u"?"https://localhost":window.location.href),M=h.pathname.toLowerCase();return M.includes("checkcaptcha")||M.includes("captcha")?`CAPTCHA(${h.host}${M})`:M.includes("risk")||M.includes("challenge")?`RISK(${h.host}${M})`:M.includes("smart/buttons")?`smart-buttons(${h.host})`:`${h.host}${M}`.slice(0,100)}catch{return x.slice(0,80)}},$e=x=>{let h=x.getAttribute("src"),M=x.getAttribute("srcdoc"),K=x.getAttribute("name"),v=x.getAttribute("sandbox"),W=[];return h&&W.push(`src=${Xn(h)}`),M&&W.push(`srcdoc[${M.length}ch]`),!h&&!M&&W.push("src=(empty) srcdoc=(empty)"),K&&W.push(`name=${K.slice(0,40)}`),v!==null&&W.push(`sandbox="${v.slice(0,40)}"`),W.join(" ")},pn=x=>{if(!(x instanceof HTMLIFrameElement))return"";try{let h=x.contentDocument;if(!h)return"cd=null";let M=h.body?.children.length??0,K=h.body?.innerHTML.length??0,v=h.head?.innerHTML.length??0;return`cd=same-origin readyState=${h.readyState} body[${M}children,${K}ch] head[${v}ch]`}catch(h){return`cd=cross-origin(${h.message.slice(0,30)})`}},Mt=[],mr=x=>{if(Re())return;let h=x.message??String(x.error??"(no message)");h&&(h.toLowerCase().includes("paypal")||h.toLowerCase().includes("zoid")||h.toLowerCase().includes("postrobot")||h.toLowerCase().includes("storage"))&&(N(`window:error ${h.slice(0,140)}`),Mt.push(h))},yr=x=>{if(Re())return;let h=x.reason instanceof Error?x.reason.message:String(x.reason??"(no reason)");h&&(h.toLowerCase().includes("paypal")||h.toLowerCase().includes("zoid")||h.toLowerCase().includes("postrobot")||h.toLowerCase().includes("storage"))&&(N(`window:rejection ${h.slice(0,140)}`),Mt.push(h))},fr={value:0},Mn=()=>{Gn?.disconnect(),Gn=null,Cn?.disconnect(),Cn=null;for(let x of Yn.splice(0))clearTimeout(x);Tn=!1,dt&&typeof window<"u"&&(window.removeEventListener("error",mr),window.removeEventListener("unhandledrejection",yr)),dt=!1},Zn=()=>{if(!(dt||Re()||wt)){if(dt=!0,Mt.length=0,fr.value=0,typeof window<"u"&&(window.addEventListener("error",mr),window.addEventListener("unhandledrejection",yr)),typeof PerformanceObserver<"u")try{Cn=new PerformanceObserver(x=>{if(!Re())for(let h of x.getEntries()){if(!h.name.toLowerCase().includes("paypal"))continue;fr.value+=1;let M=Math.round(h.duration);N(`net ${M}ms ${h.name.slice(0,90)}`)}}),Cn.observe({type:"resource",buffered:!0})}catch{}Ln?.()}},Kt=()=>{Jn&&(clearTimeout(Jn),Jn=null)},$=()=>{Mn(),Kt()},V={setEnabled:x=>{x?Zn():Mn()}};Je.current=V,bt.current&&Zn();let ne=x=>{if(!x)return!1;let h=x.toLowerCase();return h.includes("zoid destroyed")||h.includes("destroyed all components")||h.includes("window closed")||h.includes("detected container element removed")},re=x=>{if(Re()||ne(x))return;let h=Sr(x)??x;nt(()=>lt.current?.(h))},Ke=x=>{x!==null&&O.error({errorCode:x?"PROVIDER_RUNTIME_FAILED":"PROVIDER_LOAD_FAILED",stage:x?"provider_ready":"provider_load",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime"})},ee=(x,h=!1,M=!1)=>{if(tn)return;let K=Ye.current||!le;if(Ir)return;Ir=!0,dn=!0,$(),pr();let v=h||ss(x);if(v&&le&&!Ye.current){Ye.current=!0,w(!1),Qe(!1),be(!0),Lt.current?.("retrying"),un=setTimeout(()=>{tn||L(W=>W+1)},ql);return}if(v||K){if(w(!1),Qe(!1),be(!1),j(!0),(!v||M===!0)&&Ke(M),Lt.current?.("exhausted"),!se.current){se.current=!0;let W="paypal_init_failure";ss(x)?W="paypal_init_timeout":h&&(W="paypal_render_timeout"),console.error("[FloPay] Direct PayPal initialization failed:",W)}return}j(!0),Ke(M),console.error("[FloPay] DirectPayPal load/render failure:",x)};j(!1);let X=async(x,h=Xe.current)=>{if(Re())return;let M=h?.sessionId??e;if(jt.current){await jt.current(x,{sessionId:M,accountPatch:h?.accountPatch,nonce:h?.nonce});return}let K=O.startTiming();O.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let v=()=>{O.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),O.performance({stage:"processing",durationMs:O.elapsed(K),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})};try{let W=Pt.current,We=h?.accountPatch?.email??on.current,ln=h?.accountPatch?.userId??W?.customer?.id??W?.accountData?.userId??"",it=h?.accountPatch?.firstName??W?.customer?.firstName??W?.accountData?.firstName,st=h?.accountPatch?.lastName??W?.customer?.lastName??W?.accountData?.lastName,ve=await new na.PaymentAPI(Ie,{telemetry:!1}).processPayment(ln,{sessionId:M,nonce:h?.nonce??bn.current,paymentMethodCategory:"paypal",tokenizedData:x,accountData:{userId:ln,email:We??W?.customer?.email??"",...it?{firstName:it}:{},...st?{lastName:st}:{},country:h?.accountPatch?.country??W?.customer?.country??W?.accountData?.country??void 0,zip:h?.accountPatch?.zip??W?.customer?.zip??W?.accountData?.zip??void 0}});if(ve.ok){if(dn||tn&&an.current)return;v(),O.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),nt(()=>Yt.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(Re())return;let Ze=await ve.json().catch(()=>null),De=Ze?.message??"PayPal payment failed.",Ee=Sr(De)??De;v(),ve.status===400&&(typeof Ze?.declineCode=="string"||!Array.isArray(Ze?.fields))?O.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):ve.status===400||ve.status===422?O.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx"}):O.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:Gl(ve.status),failureCategory:ve.status>=500?"server_error":void 0}),re(Ee),nt(()=>Nt.current?.(Qt("paypal",Ee,{code:Ze?.code,declineCode:Ze?.declineCode})));return}catch(W){if(Re())return;v(),O.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let We=W instanceof Error?W.message:"PayPal payment failed.",ln=Sr(We)??We;re(ln),nt(()=>Nt.current?.(Qt("paypal",ln)));return}},_=()=>new $t.FloPayError("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),F=x=>Re()?Promise.reject(_()):Promise.resolve(x),Z=async x=>{if(Re())throw _();Dn||zt();let h=Xe.current,M=h?.sessionId??e,K=h?.nonce??bn.current;O.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let v;try{v=await new na.PaymentAPI(Ie,{telemetry:!1}).createSessionIntent(M,K??"",mt?{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:$t.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE,paymentMethodId:null,intentKind:Te==="setup_token"?"setup":"payment"}:{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"},{idempotencyKey:Kn})}catch(W){throw O.error({...(0,$t.classifyTelemetryFailure)(W,"PAYMENT_PROCESSING_FAILED","unknown"),stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"}),W}if(Re())throw _();if(v.provider!=="paypal"||v.providerObjectType!==Te)throw new Error(x);return O.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),v.providerObjectId},vt=(x,h)=>{let M=h?.nonce??bn.current;if(!M)return;let K=h?.sessionId??e,v=Qr(x)??br(x)??"provider_declined";new na.PaymentAPI(Ie,{telemetry:!1}).reportSessionIntentDecline(K,M,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:v}).catch(()=>{})},et=Y;N("loadScript:scheduled (deferred 1 tick)");let me=null,at=setTimeout(()=>{if(tn){N("loadScript:skipped (cancelled before defer ran)");return}N("loadScript:start");let x=ur==="live"?"production":ur,h={};Te==="subscription"?h={intent:"subscription",vault:!0}:Te==="order"&&(h={intent:"capture"}),me=(0,ls.loadScript)({clientId:l,currency:y,...h,...x?{environment:x}:{},...x==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}});let M=!1;me.then(K=>{if(M=!0,N(`loadScript:resolved inactive=${Re()} ns=${!!K} buttons=${!!K?.Buttons}`),Re())return;if(!K?.Buttons){N("FAIL: namespace missing Buttons factory"),ee("PayPal SDK did not expose the Buttons factory.");return}O.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),O.performance({stage:"provider_ready",durationMs:O.elapsed(Oe.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),O.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let v=async(ve,Ze)=>{if(Re()||Se.current!==et)return;let De=ve.vaultSetupToken??ve.subscriptionID??ve.orderID??"",Ee=De?vn.current.get(De):Jt.current.get(et);if(!(!Ee||!St(Ee.generation))&&xt(Ee.generation)){vn.current.delete(De),Jt.current.delete(Ee.surfaceKey),Nn();try{if(Qe(!0),nt(()=>lt.current?.(null)),!De)throw new $t.FloPayError("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});let Ct=Pt.current,nn=xr(ct.current??[Ct?.customer?.firstName,Ct?.customer?.lastName].filter(Boolean).join(" ")),xe=kn({email:Ee.accountPatch?.email?.trim()||on.current?.trim()||Ct?.customer?.email?.trim(),firstName:Ee.accountPatch?.firstName?.trim()||nn.firstName,lastName:Ee.accountPatch?.lastName?.trim()||nn.lastName});if(!(0,$t.isValidEmail)(xe.email)||!(xe.firstName||xe.lastName))try{let On=Wl(await Ze?.order?.get?.());xe=kn({email:On.email||xe.email,firstName:On.firstName||xe.firstName,lastName:On.lastName||xe.lastName})}catch{}if((He.current||tt)&&!(0,$t.isValidEmail)(xe.email)){let On=await ot("PayPal",xe);if(!On)return;xe=On}(0,$t.isValidEmail)(xe.email)&&(Ee.accountPatch=kn({...Ee.accountPatch,...xe}),await He.current?.(xe));let Pn;Te==="setup_token"?Pn={id:De,type:"paypal_setup_token",isPaypal:!0,gateway:"paypal",paymentMethodType:$t.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE}:mt?Pn={id:De,isPaypal:!0,gateway:"paypal",paymentMethodType:$t.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE}:Pn={id:De,isPaypal:!0},await X(Pn,Ee)}catch(Ct){re(Ct instanceof Error?Ct.message:"PayPal capture failed.")}finally{Re()||Qe(!1)}}},W=ve=>{let Ze=ce?()=>F(ce):()=>Z(ve);return async()=>cn(await Ze())},We=K.Buttons({style:{layout:"horizontal",height:ra,tagline:!1},onClick:async(ve,Ze)=>{if(Re()){await Ze.reject();return}zt();let De=ft.current,Ee={};if(De)try{let xe=await De("paypal");if(Re()){await Ze.reject();return}if(!xe.proceed){Xe.current=null,Jt.current.delete(et),await Ze.reject();return}Ee={sessionId:xe.sessionId,accountPatch:xe.accountPatch,nonce:xe.nonce}}catch(xe){N(`onClick:runBeforeButtonClick rejected msg=${(xe instanceof Error?xe.message:String(xe)).slice(0,120)}`),Xe.current=null,Jt.current.delete(et),await Ze.reject();return}nt(()=>In.current?.("paypal"));let nn={generation:Rt(),surfaceKey:et,...Ee};Xe.current=nn,Jt.current.set(et,nn),await Ze.resolve(),O.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),O.log({name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),O.log({name:"provider.overlay.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),Wn=O.startTiming()},createOrder:Te==="order"?W("Failed to create PayPal order."):void 0,createSubscription:Te==="subscription"?W("Failed to create PayPal subscription."):void 0,createVaultSetupToken:Te==="setup_token"?async()=>cn(await Z("Failed to create PayPal setup token.")):void 0,onApprove:v,onCancel:()=>{if(Re())return;let ve=Jt.current.get(et)??Xe.current;ve&&Jt.current.delete(ve.surfaceKey),Xe.current=null,Nn(),O.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),ze.current=!0,Et({generation:ve?.generation,remount:!0,focus:!1})},onError:ve=>{if(Re()||Se.current!==et)return;let Ze=ve instanceof Error?ve.message:"PayPal failed to render.";if(N(`onError rendered=${wt} msg=${Ze.slice(0,120)}`),wt){let De=Jt.current.get(et)??Xe.current;if(De&&!St(De.generation)||!De&&k())return;if(ne(Ze)){xt(De?.generation);return}if(Nn(),ko(ve)){O.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),vt(ve,De),nt(()=>Nt.current?.(Qt("paypal",Ze))),De&&Jt.current.delete(De.surfaceKey),Xe.current=null,xt(De?.generation);return}let Ee=Ze.toLowerCase();O.error({errorCode:Ee.includes("popup")&&Ee.includes("block")?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),De&&Jt.current.delete(De.surfaceKey),Xe.current=null,Et({generation:De?.generation,remount:!0,showRetry:!0,focus:!0}),Xt(ve,{code:"paypal_runtime_failed"});return}ee(Ze,!1,ne(Ze)?null:or)}}),ln=We.isEligible();if(N(`isEligible=${ln}`),O.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!ln){w(!1),ee("PayPal buttons are not eligible to render in this context (paypal_ineligible).",!1,null);return}or=!0,Rr=We,Ln=()=>{if(!dt||Tn||Re()||wt)return;Tn=!0,N(`container:dims ${xn(_n)} visibility=${typeof document>"u"?"(no document)":document.visibilityState}`),typeof MutationObserver<"u"&&(Gn=new MutationObserver(Ze=>{if(!Re()){for(let De of Ze)if(De.type==="childList")De.addedNodes.forEach(Ee=>{if(!(Ee instanceof Element))return;let Ct=Ee.tagName.toLowerCase(),nn=(Ee.getAttribute("title")??"").slice(0,40),xe=Ct==="iframe"?` ${$e(Ee)}`:"";N(`child+ ${Ct}${nn?` title="${nn}"`:""}${xe} dims=${xn(Ee)}`)});else if(De.type==="attributes"&&De.target instanceof Element){let Ee=De.target;if(Ee.tagName.toLowerCase()!=="iframe")continue;let Ct=De.attributeName;(Ct==="src"||Ct==="srcdoc")&&N(`attr~ iframe ${Ct}=${Ct==="srcdoc"?`[${(Ee.getAttribute("srcdoc")??"").length}ch]`:Xn(Ee.getAttribute("src"))} dims=${xn(Ee)}`)}}}),Gn.observe(_n,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let ve=Ze=>{if(Re()||wt)return;let De=_n.querySelectorAll("iframe"),Ee=typeof document<"u"&&"hasStorageAccess"in document;N(`watchdog:${Ze} container=${xn(_n)} children=${_n.childElementCount} iframes=${De.length} visibility=${typeof document>"u"?"(no document)":document.visibilityState} cookies=${typeof navigator>"u"?"?":navigator.cookieEnabled} hasStorageAccessApi=${Ee} paypalNetRequests=${fr.value}`),De.forEach((Ct,nn)=>{let xe=(Ct.getAttribute("title")??"").slice(0,40);N(` iframe[${nn}] ${xn(Ct)}${xe?` title="${xe}"`:""} ${$e(Ct)}`);let Pn=pn(Ct);Pn&&N(` ${Pn}`)}),Mt.length===0&&N(" (no PayPal/zoid window errors captured)")};Yn.push(setTimeout(()=>ve("3s"),3e3)),Yn.push(setTimeout(()=>ve("8s"),8e3)),Yn.push(setTimeout(()=>ve("15s"),15e3))},Ln(),N("render:start");let st=O.startTiming();Jn=setTimeout(()=>{Re()||wt||(N("watchdog:11s retryable render timeout"),ee("PayPal Buttons render did not settle within 11000ms.",!0,!0))},jl);let ye=We.render(_n);(async()=>{try{if(await ye,N(`render:resolved inactive=${Re()}`),$(),Re()){pr();return}wt=!0,w(!0),be(!1),Lt.current?.("ready"),O.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),O.performance({stage:"checkout_render",durationMs:O.elapsed(st),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}catch(ve){let Ze=ve instanceof Error?ve.message:"PayPal failed to render.";N(`render:rejected msg=${Ze.slice(0,120)}`),$(),ee(Ze,!1,ne(Ze)?null:!0)}})()}).catch(K=>{let v=K instanceof Error?K.message:"PayPal operation failed.";N(`provider:failed msg=${v.slice(0,120)}`),ee(v,!1,M&&ne(v)?null:or)})},0);return()=>{tn=!0,clearTimeout(at),un&&clearTimeout(un),$(),Je.current===V&&(Je.current=null),pr()}},[le,Ie,l,y,c,Te,mt,e,ce,Y,O,ot,tt,N]);let Fn=Ge?(0,qn.jsxs)("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:J?"#fef2f2":"#f3f4f6",border:`1px solid ${J?"#fca5a5":"#d1d5db"}`,borderRadius:6,color:"#111827",font:"11px/1.35 ui-monospace, SFMono-Regular, Menlo, monospace",whiteSpace:"pre-wrap",wordBreak:"break-word",maxHeight:220,overflowY:"auto"},children:[`FloPay/DirectPayPal-debug (ready=${Pe} failed=${J})`,Gt.length===0?`
2
2
  (waiting for first lifecycle event\u2026)`:`
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)(Jr,{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:xl,children:"Try PayPal again"})]})}function Ro(e){return(0,$n.jsx)(as,{...e})}function is(e){return(0,$n.jsx)(as,{...e})}var Eo=require("react/jsx-runtime");function Qr({children:e,margin:t,icon:n=!0,styleOverride:r}){return(0,Eo.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,Eo.jsx)("svg",{"aria-hidden":"true",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:(0,Eo.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 ta=require("@flopay/shared");function eo(){return typeof window<"u"&&typeof window.sessionStorage<"u"}var Va=":idempotency-key";function Ka(e,t){if(!eo())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 Ha(e,t){if(!eo())return null;try{let n=window.sessionStorage.getItem(e+Va);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 na(e,t){if(eo())try{Ka(e,t)&&window.sessionStorage.removeItem(e)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout session cache.",n)}}function ra(e,t){if(na(e,t),!!eo())try{Ha(e,t)&&window.sessionStorage.removeItem(e+Va)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout idempotency key.",n)}}function oa(e,t,n,r){if(eo())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 aa(e,t,n){if(eo())try{window.sessionStorage.setItem(e+Va,JSON.stringify({canonicalIdentity:t,idempotencyKey:n}))}catch(r){console.warn("[FloPayCheckout] Failed to persist checkout idempotency key.",r)}}function ja(e,t){return`${e}:${t.totalAmount??""}:${t.overrideAmount??""}:${t.quantity??1}:${t.currency??""}`}function Fl(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 to(e,t=!1){let n=e?.account?.email?.trim().toLowerCase()??"",r={c:e?.clientId,cur:e?.currency??"",captureMethod:e?.captureMethod??"",a:{e:n,u:n?"":e?.account?.userId??"",country:e?.account?.country??""},successUrl:e?.successUrl,cancelUrl:e?.cancelUrl,p:e?.products?.map(o=>ja(`${o.type??""}:${o.code??o.providerItemId??o.providerPlanId??""}`,o)).sort(),i:e?.items?.map(o=>ja(o.code??o.providerItemId??"",o)).sort(),s:e?.subscriptions?.map(o=>ja(o.code??o.providerPlanId??"",o)).sort(),couponCodes:e?.couponCodes?[...e.couponCodes].sort():void 0,checkoutMetadata:Fl(e?.checkoutMetadata),...t?{tagsData:e?.tagsData,utmMetadata:e?.utmMetadata,tokenizedData:e?.tokenizedData,checkoutMode:e?.checkoutMode??"full"}:{}};return JSON.stringify(r)}function ss(e,t=!1){let n=to(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 ls(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,ta.resolveSessionCurrency)(t.currency,t.items,t.subscriptions,t.products);if(!o||e.currency.toUpperCase()!==o.toUpperCase())return!1;let i=(t.products??(0,ta.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])}var Vt=require("react/jsx-runtime");var Dl={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:Dl[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:`
3
+ ${Gt.join(`
4
+ `)}`]}):null;return J&&!B?Ge?(0,qn.jsx)("div",{children:Fn}):null:(0,qn.jsxs)("div",{children:[Fn,fe&&(0,qn.jsx)(Zr,{identity:fe.identity,methodLabel:fe.methodLabel,testId:"flopay-direct-paypal-identity-pane",onComplete:te,onCancel:()=>te(null)}),(0,qn.jsxs)("div",{"aria-hidden":ue||fe?!0:void 0,style:ue||fe?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:ra},children:[!Pe&&!ue&&(0,qn.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,qn.jsx)("div",{ref:Le,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,role:"group","aria-label":"PayPal payment method",style:{minHeight:ra,display:"flex",opacity:Pe?1:0},"aria-busy":Ue||he},Y)]},Y),rt&&(0,qn.jsx)("button",{ref:_e,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:en,style:Hl,children:"Try PayPal again"})]})}function Eo(e){return(0,qn.jsx)(cs,{...e})}function ds(e){return(0,qn.jsx)(cs,{...e})}var _o=require("react/jsx-runtime");function to({children:e,margin:t,icon:n=!0,styleOverride:r}){return(0,_o.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,_o.jsx)("svg",{"aria-hidden":"true",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:(0,_o.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 oa=require("@flopay/shared");function no(){return typeof window<"u"&&typeof window.sessionStorage<"u"}var Ga=":idempotency-key";function Ya(e,t){if(!no())return null;let n=window.sessionStorage.getItem(e);if(!n)return null;try{let r=JSON.parse(n);return!r||typeof r.sid!="string"||!r.sid||"canonicalIdentity"in r&&r.canonicalIdentity!==t?null:{..."canonicalIdentity"in r?{canonicalIdentity:t}:{},sid:r.sid,nonce:typeof r.nonce=="string"?r.nonce:void 0}}catch{return{sid:n}}}function Ja(e,t){if(!no())return null;try{let n=window.sessionStorage.getItem(e+Ga);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 aa(e,t){if(no())try{Ya(e,t)&&window.sessionStorage.removeItem(e)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout session cache.",n)}}function ia(e,t){if(aa(e,t),!!no())try{Ja(e,t)&&window.sessionStorage.removeItem(e+Ga)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout idempotency key.",n)}}function sa(e,t,n,r){if(no())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 la(e,t,n){if(no())try{window.sessionStorage.setItem(e+Ga,JSON.stringify({canonicalIdentity:t,idempotencyKey:n}))}catch(r){console.warn("[FloPayCheckout] Failed to persist checkout idempotency key.",r)}}function Wa(e,t){return`${e}:${t.totalAmount??""}:${t.overrideAmount??""}:${t.quantity??1}:${t.currency??""}`}function Yl(e){if(e==null)return e;let t=JSON.stringify(Object.entries(e).sort(([l],[c])=>l<c?-1:l>c?1:0)),n=1779033703,r=3144134277,o=1013904242,a=2773480762;for(let l=0;l<t.length;l++){let c=t.charCodeAt(l);n=r^Math.imul(n^c,597399067),r=o^Math.imul(r^c,2869860233),o=a^Math.imul(o^c,951274213),a=n^Math.imul(a^c,2716044179)}return n=Math.imul(o^n>>>18,597399067),r=Math.imul(a^r>>>22,2869860233),o=Math.imul(n^o>>>17,951274213),a=Math.imul(r^a>>>19,2716044179),n^=r^o^a,r^=n,o^=n,a^=n,[n,r,o,a].map(l=>(l>>>0).toString(16).padStart(8,"0")).join("")}function ro(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=>Wa(`${o.type??""}:${o.code??o.providerItemId??o.providerPlanId??""}`,o)).sort(),i:e?.items?.map(o=>Wa(o.code??o.providerItemId??"",o)).sort(),s:e?.subscriptions?.map(o=>Wa(o.code??o.providerPlanId??"",o)).sort(),couponCodes:e?.couponCodes?[...e.couponCodes].sort():void 0,checkoutMetadata:Yl(e?.checkoutMetadata),...t?{tagsData:e?.tagsData,utmMetadata:e?.utmMetadata,tokenizedData:e?.tokenizedData,checkoutMode:e?.checkoutMode??"full"}:{}};return JSON.stringify(r)}function us(e,t=!1){let n=ro(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 ps(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,oa.resolveSessionCurrency)(t.currency,t.items,t.subscriptions,t.products);if(!o||e.currency.toUpperCase()!==o.toUpperCase())return!1;let a=(t.products??(0,oa.foldIntoProducts)(t.items,t.subscriptions)).map(m=>({type:m.type,code:m.code??m.providerItemId??m.providerPlanId??"",quantity:m.quantity??1,totalAmount:m.totalAmount,overrideAmount:m.overrideAmount??null,currency:(m.currency??o).toUpperCase()})).sort((m,p)=>`${m.code}:${m.type??""}`.localeCompare(`${p.code}:${p.type??""}`)),l=e.products.map(m=>({type:m.type,code:m.code??"",quantity:m.quantity??1,totalAmount:m.totalAmount,overrideAmount:m.overrideAmount??null,currency:(m.currency??e.currency).toUpperCase()})).sort((m,p)=>`${m.code}:${m.type??""}`.localeCompare(`${p.code}:${p.type??""}`));if(a.length!==l.length)return!1;for(let[m,p]of a.entries()){let g=l[m];if(g===void 0||p.code!==g.code||p.type!==void 0&&p.type!==g.type||p.quantity!==g.quantity||p.totalAmount!==g.totalAmount||p.overrideAmount!==g.overrideAmount||p.currency!==g.currency)return!1}let c=[...t.couponCodes??[]].sort(),y=[...e.coupons??[]].sort();return c.length===y.length&&c.every((m,p)=>m===y[p])}var Vt=require("react/jsx-runtime");var Jl={panel:{background:"white"},spinnerTrackColor:"#e5e7eb",spinnerAccentColor:"#4A49FF",labelColors:{processing:"#374151",success:"#16a34a",error:"#dc2626"},noteColor:"#6b7280"};function jn({status:e,errorMessage:t,authorized:n=!1,processingLabel:r="PROCESSING...",successLabel:o,errorLabel:a="PAYMENT FAILED",successNote:l="You will be automatically redirected, do not close or navigate away from this window.",theme:c=Jl}){let y={fontSize:13,color:c.noteColor,fontWeight:400,maxWidth:260,lineHeight:1.4,margin:0};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",{"data-testid":"flopay-processing-overlay-panel",style:{borderRadius:12,boxShadow:"0 8px 32px rgba(0,0,0,0.18)",...c.panel,padding:"2rem 2.5rem",textAlign:"center",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:c.spinnerTrackColor,strokeWidth:"3"}),(0,Vt.jsx)("path",{d:"M4 12a8 8 0 018-8v3a5 5 0 00-5 5H4z",fill:c.spinnerAccentColor})]}),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:c.labelColors[e]},children:[e==="processing"&&r,e==="success"&&(o??(n?"PAYMENT AUTHORISED":"PAYMENT SUCCESSFUL")),e==="error"&&a]}),e==="success"&&l!==null&&(0,Vt.jsx)("p",{style:y,children:l}),e==="error"&&t&&(0,Vt.jsx)("p",{style:y,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 cs=require("@flopay/shared"),rn=require("react");var ds=require("react/jsx-runtime");function _o({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=Zr(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,cs.resolveBillingApiUrl)(n?.billingApiUrl),I=(0,rn.useMemo)(()=>({flopay:i,paypalFlopay:c,billingApiUrl:p,emitInstrument:g}),[i,c,p,g]);return(0,ds.jsx)(qn.Provider,{value:I,children:o})}var ia="flopay_recent_completion_";function no(e){if(!(!e||typeof window>"u"))try{let t={expiresAt:Date.now()+6e4};window.sessionStorage.setItem(ia+e,JSON.stringify(t))}catch{}}function Wa(e){if(!e||typeof window>"u")return!1;try{let t=window.sessionStorage.getItem(ia+e);if(!t)return!1;let n=JSON.parse(t);return typeof n?.expiresAt!="number"||n.expiresAt<=Date.now()?(window.sessionStorage.removeItem(ia+e),!1):!0}catch{return!1}}var ro=require("@flopay/js"),je=require("@flopay/shared");var xo="card";async function Ll(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 Nl(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 Ga(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 To(e,t){try{return await e()}catch(n){throw br(n,t)}}function ps(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 Ol(e){return e.status==="succeeded"||e.status==="declined"}async function ms(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 zl(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||!Ol(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 zl(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 kr(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=Sr(o)??o;return Ga(new je.FloPayError(i,"api_error",{code:(0,je.normalizeCheckoutFailureOutcome)(e?.outcome)??(0,je.normalizeCheckoutFailureOutcome)(e?.type)??e?.gatewayErrorCode}),r)}function Ya(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function sa(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}function ys(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let o of n)if(typeof o=="string"&&o.length>0&&(!t?.requirePaymentIntentClientSecret||sa(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||sa(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||sa(f)))return f}}}}async function Ul({billingApiUrl:e,sessionId:t,nonce:n,responseJson:r}){let o=ys(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 ro.PaymentAPI(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(sa(c))return{type:"3ds_required",threeDSecureToken:c}}catch{}return null}async function oo({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 ro.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??Ya(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:Po(o),checkoutMethod:us(o)}}:{type:"success",result:{status:"succeeded",paymentIntentId:o?.threeDSecureActionResultTokenId,paymentMethodId:Po(o),checkoutMethod:us(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=ys(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 Ul({billingApiUrl:c,sessionId:v,nonce:y,responseJson:S});if(q)return q;throw Ga(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 la(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 Ga(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 To(()=>Ll(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 To(()=>Nl(y,e.threeDSecureToken,{payment_method:p,return_url:c??Ya(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 To(()=>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 oo({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}:la(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 To(()=>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 To(()=>f.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:c??Ya(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 Mo(e){if(e instanceof je.FloPayError){let r=Sr(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=Sr(t)??t;return new je.FloPayError(n,"api_error")}function ca(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 us(e){if(e)return e.isPaypal?"paypal":"card"}async function da({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,ro.loadFloPay)(e,{billingApiUrl:n,locale:r,telemetry:o}),i?(0,ro.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=Ki(require("react"),1);function fs(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 gs={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"),hs=require("react/jsx-runtime");function ao({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,hs.jsx)("div",{ref:y,"data-testid":"flopay-vault-card-fields",style:i})}function io(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 Ja(e){if(typeof e=="number"||typeof e=="string")return e}function ua({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)??io(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(Ja(v?.fontWeight)??400),borderRadius:o(r?.borderRadius)??"8px"}}var l=require("react/jsx-runtime"),sr="flopay_stripe_resume",vs="flopay_wallet_resume",_s="fw1",ql=300*1e3,$l=900,jl=25e3,Vl=25e3,Xa={},Za={};function Ts(e){return e instanceof u.FloPayError&&(e.type==="validation_error"||e.statusCode===400||e.statusCode===422)}async function ma(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 Ts(o)||t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"intent_create",provider:r}),o}}var Ao="flopay_paypal_resume",Kl=250,bs="Just a moment \u2014 we are finalizing your order. Please press pay again.";function ri(e,t,n){e?.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:"provider_runtime",stage:"provider_load",provider:t,paymentMethodCategory:n,requestCategory:"provider_sdk"})}async function ya({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 Hl(e){return e instanceof u.FloPayError&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function Qa(e){return e?.html?{html:e.html,...e.messageToken?{messageToken:e.messageToken}:{},...e.expectedOrigin?{expectedOrigin:e.expectedOrigin}:{}}:null}function xs({event:e,fallbackEmail:t,fallbackName:n}){let r=e.billingDetails,o=t?.trim(),i=xr(n),d=i.firstName?i:xr(r?.name);return kn({email:(0,u.isValidEmail)(o)?o:r?.email?.trim(),firstName:d.firstName,lastName:d.lastName})}async function Wl({event:e,prepared:t,email:n,billingName:r,methodLabel:o,collect:i}){let d=xs({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 Yl=`
9
+ `})]})})}var ms=require("@flopay/shared"),rn=require("react");var ys=require("react/jsx-runtime");function To({flopay:e,paypalFlopay:t,options:n,onInstrument:r,children:o}){let[a,l]=(0,rn.useState)(e instanceof Promise?null:e),[c,y]=(0,rn.useState)(t instanceof Promise||!t?null:t),m=(0,rn.useRef)(null),p=(0,rn.useRef)(null),g=eo(r);(0,rn.useEffect)(()=>{g({class:"lifecycle",name:"checkout.mount"})},[g]),(0,rn.useEffect)(()=>{a&&g({class:"lifecycle",name:"sdk.initialize.ready"})},[g,a]),(0,rn.useEffect)(()=>{if(a)return Wt(a)?.subscribe?.(g)},[g,a]),(0,rn.useEffect)(()=>{if(!(!c||c===a))return Wt(c)?.subscribe?.(g)},[g,a,c]),(0,rn.useEffect)(()=>{if(!a)return;let A=Wt(a);return m.current=A?.beginCheckout()??A?.now()??0,A?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{A?.log({name:"checkout.unmount",stage:"unmount"})}},[a]),(0,rn.useEffect)(()=>{let A=!1;return e instanceof Promise?e.then(D=>{A||l(D)},()=>{A||g({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"})}):l(e),()=>{A=!0}},[g,e]),(0,rn.useEffect)(()=>{let A=!1;if(!t){y(null);return}return t instanceof Promise?t.then(D=>{A||y(D)},()=>{A||g({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED",provider:"paypal"})}):y(t),()=>{A=!0}},[g,t]),(0,rn.useEffect)(()=>{if(!a||p.current===a)return;p.current=a;let A=Wt(a);A?.log({name:"checkout.rendered",stage:"checkout_render"}),g({class:"lifecycle",name:"checkout.rendered"}),A?.performance({stage:"checkout_render",durationMs:A.elapsed(m.current??0),durationMode:"machine"})},[g,a]);let f=(0,ms.resolveBillingApiUrl)(n?.billingApiUrl),P=(0,rn.useMemo)(()=>({flopay:a,paypalFlopay:c,billingApiUrl:f,emitInstrument:g}),[a,c,f,g]);return(0,ys.jsx)($n.Provider,{value:P,children:o})}var ca="flopay_recent_completion_";function oo(e){if(!(!e||typeof window>"u"))try{let t={expiresAt:Date.now()+6e4};window.sessionStorage.setItem(ca+e,JSON.stringify(t))}catch{}}function Xa(e){if(!e||typeof window>"u")return!1;try{let t=window.sessionStorage.getItem(ca+e);if(!t)return!1;let n=JSON.parse(t);return typeof n?.expiresAt!="number"||n.expiresAt<=Date.now()?(window.sessionStorage.removeItem(ca+e),!1):!0}catch{return!1}}var ao=require("@flopay/js"),qe=require("@flopay/shared");var Mo="card";async function Xl(e,t,n){if(n){if(typeof e.retrieveSetupIntent!="function")return null;let{setupIntent:a,error:l}=await e.retrieveSetupIntent(t);return{error:l,intent:a??null}}if(typeof e.retrievePaymentIntent!="function")return null;let{paymentIntent:r,error:o}=await e.retrievePaymentIntent(t);return{error:o,intent:r??null}}async function Zl(e,t,n,r){if(r){if(typeof e.confirmCardSetup!="function")return null;let{setupIntent:l,error:c}=await e.confirmCardSetup(t,n);return{error:c,intent:l??null}}if(typeof e.confirmCardPayment!="function")return null;let{paymentIntent:o,error:a}=await e.confirmCardPayment(t,n);return{error:a,intent:o??null}}function Qa(e,t){return Object.assign(e,{checkoutMethod:t})}function Cr(e,t){let n=e instanceof qe.FloPayError?e:new qe.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 xo(e,t){try{return await e()}catch(n){throw Cr(n,t)}}function gs(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 Ql(e){return e.status==="succeeded"||e.status==="declined"}async function hs(e){if(typeof document>"u"||typeof window>"u")throw new qe.FloPayError("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});if(e.signal?.aborted)throw new qe.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`,a=async()=>{let p=new AbortController,g=()=>p.abort();e.signal?.aborted?p.abort():e.signal?.addEventListener("abort",g);let f=window.setTimeout(()=>p.abort(),r);try{let P=await fetch(o,{method:"POST",headers:{"x-checkout-session-token":e.nonce,"content-type":"application/json"},body:"{}",signal:p.signal});if(!P.ok)return{status:"unknown"};let A=await P.json().catch(()=>null);return ec(A)}catch{return{status:"unknown"}}finally{window.clearTimeout(f),e.signal?.removeEventListener("abort",g)}},l=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 y=document.createElement("iframe");y.setAttribute("title","Card authentication"),y.setAttribute("allow","payment"),y.tabIndex=0,y.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(";"),y.src=e.nextActionRedirectUrl,c.appendChild(y),document.body.appendChild(c),y.focus();let m=null;try{m=new URL(e.billingApiUrl,window.location.href).origin}catch{m=null}try{let p=await new Promise((g,f)=>{let P=!1,A=0,D=0,he=0,H=!1,S=()=>{window.clearTimeout(A),window.clearInterval(D),window.clearTimeout(he),window.removeEventListener("message",oe),y.removeEventListener("load",q),e.signal?.removeEventListener("abort",pe)},le=async()=>{if(!(P||H)){H=!0;try{let ce=await a();if(P||!Ql(ce))return;P=!0,S(),g(ce)}finally{H=!1}}},q=()=>{window.clearTimeout(he),he=window.setTimeout(()=>{le()},250)},pe=()=>{P||(P=!0,S(),f(new qe.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"})))},oe=ce=>{if(ce.source!==y.contentWindow||m&&ce.origin!==m)return;let Ve=ce.data;!Ve||typeof Ve!="object"||Ve.source!=="flopay-vault-3ds-return"||P||(P=!0,S(),g(null))};A=window.setTimeout(()=>{P||(P=!0,S(),f(new qe.FloPayError("Card authentication timed out.","api_error",{code:"three_ds_timeout"})))},t),D=window.setInterval(()=>{le()},n),y.addEventListener("load",q),window.addEventListener("message",oe),e.signal?.addEventListener("abort",pe),e.signal?.aborted&&pe()});return p||await a()}finally{c.parentNode?.removeChild(c),l?.isConnected&&l.focus()}}function ec(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 kr(e,t="Payment failed. Please try again.",n){let r=n?.checkoutMethod??e?.checkoutMethod??(e?.type==="paypal_redirect_required"?"paypal":"card"),o=e?.message??t,a=Sr(o)??o;return Qa(new qe.FloPayError(a,"api_error",{code:(0,qe.normalizeCheckoutFailureOutcome)(e?.outcome)??(0,qe.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 da(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}function bs(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let o of n)if(typeof o=="string"&&o.length>0&&(!t?.requirePaymentIntentClientSecret||da(o)))return o;let r=e?.data;if(r&&typeof r=="object"){let o=r,a=[o.threeDSecureToken,o.clientSecret,o.stripeClientSecret,o.id];for(let c of a)if(typeof c=="string"&&c.length>0&&(!t?.requirePaymentIntentClientSecret||da(c)))return c;let l=o.gateways;if(l&&typeof l=="object"){let c=l.stripe;if(c&&typeof c=="object"){let y=c,m=[y.stripeClientSecret,y.clientSecret];for(let p of m)if(typeof p=="string"&&p.length>0&&(!t?.requirePaymentIntentClientSecret||da(p)))return p}}}}async function tc({billingApiUrl:e,sessionId:t,nonce:n,responseJson:r}){let o=bs(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 ao.PaymentAPI(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(da(c))return{type:"3ds_required",threeDSecureToken:c}}catch{}return null}async function io({billingApiUrl:e,sessionId:t,session:n,nonce:r,tokenizedData:o,returnUrl:a,telemetry:l}){let c=e.replace(/\/+$/,""),y=t??n.id,m=r??n.clientSecret,p=n.customer?.id??n.accountData?.userId??"",g=n.customer?.email??n.accountData?.email??"",f=n.customer?.firstName??n.accountData?.firstName??"",P=n.customer?.lastName??n.accountData?.lastName??"",A=n.customer?.country??n.accountData?.country??void 0,D=n.customer?.zip??n.accountData?.zip??void 0,H=await new ao.PaymentAPI(c,l===!1?{telemetry:!1}:void 0).processPayment(p,{sessionId:y,nonce:m,paymentMethodCategory:"saved",tokenizedData:o,accountData:{userId:p,email:g,firstName:f,lastName:P,country:A,zip:D},returnUrl:a??Za(n)});if(H.ok){let q=typeof H.json=="function"?await H.json().catch(()=>null):null;return(0,qe.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:y,authorizationExpiresAt:typeof q?.authorizationExpiresAt=="string"?q.authorizationExpiresAt:n.authorizationExpiresAt,paymentMethodId:wo(o),checkoutMethod:fs(o)}}:{type:"success",result:{status:"succeeded",paymentIntentId:o?.threeDSecureActionResultTokenId,paymentMethodId:wo(o),checkoutMethod:fs(o)}}}let S;try{S=await H.json()}catch(q){throw new qe.FloPayError("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:H.status,cause:q})}if(S?.type==="paypal_redirect_required"||S?.type==="3ds_required"){let q=bs(S);if(!q)throw new qe.FloPayError("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:H.status});return{type:S.type,threeDSecureToken:q,paymentMethodId:S.paymentMethodId}}if(S?.gatewayErrorCode==="authentication_required"){let q=await tc({billingApiUrl:c,sessionId:y,nonce:m,responseJson:S});if(q)return q;throw Qa(new qe.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}let le=new qe.FloPayError(S?.message??"Payment failed. Please try again.","api_error",{code:S?.code??S?.gatewayErrorCode,declineCode:S?.declineCode??S?.gatewayDeclineReason,statusCode:H.status});throw Object.assign(le,{telemetryOutcome:(0,qe.classifyPaymentRejection)(H.status,S)})}async function ua(e,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:a,session:l,returnUrl:c,telemetry:y}){let m=t?.getRawProvider();if(!m)throw Cr(new qe.FloPayError("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!r||!e.threeDSecureToken)throw Qa(new qe.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let p=(0,qe.isSetupIntentClientSecret)(e.threeDSecureToken),g=null,f=e.paymentMethodId,P=await xo(()=>Xl(m,e.threeDSecureToken,p),"card");if(P){if(P.error)throw Cr(new qe.FloPayError(P.error.message??`Failed to retrieve 3DS ${p?"setup":"payment"} status.`,"api_error",{code:P.error.code}),"card");let D=P.intent;!f&&D?.payment_method&&(typeof D.payment_method=="string"?f=D.payment_method:"id"in D.payment_method&&(f=D.payment_method.id??void 0))}let A=f?await xo(()=>Zl(m,e.threeDSecureToken,{payment_method:f,return_url:c??Za(l)??window.location.href},p),"card"):null;if(A){if(A.error)throw Cr(new qe.FloPayError(A.error.message??"3DS authentication failed.","api_error",{code:A.error.code}),"card");g=A.intent}else{let D=await xo(()=>m.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(D.error)throw Cr(new qe.FloPayError(D.error.message??"3DS authentication failed.","api_error",{code:D.error.code}),"card");g=(p?D.setupIntent:D.paymentIntent)??null}if(g&&(g.status==="requires_capture"||g.status==="succeeded"||g.status==="processing")){let D=await io({billingApiUrl:o,sessionId:a,session:l,telemetry:y,tokenizedData:{id:g.id,type:"card",threeDSecureActionResultTokenId:g.id},returnUrl:c});return D.type==="success"?{...D.result,paymentIntentId:D.result.paymentIntentId??g.id,paymentMethodId:D.result.paymentMethodId??f}:ua(D,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:a,session:l,returnUrl:c,telemetry:y})}throw Cr(new qe.FloPayError("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let p=(n??t)?.getRawProvider();if(!p)throw Cr(new qe.FloPayError("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:f}=await xo(()=>p.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(f)throw Cr(new qe.FloPayError(f.message??"PayPal authorization failed.","api_error",{code:f.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:g}=await xo(()=>p.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:c??Za(l)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(g)throw Cr(new qe.FloPayError(g.message??"PayPal authorization failed.","api_error",{code:g.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new qe.FloPayError("Unsupported payment redirect state.","api_error")}function Ao(e){if(e instanceof qe.FloPayError){let r=Sr(e.message);return r&&r!==e.message?Object.assign(new qe.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=Sr(t)??t;return new qe.FloPayError(n,"api_error")}function pa(e){let t=e.data.stripe?.publishableKey,n=!!e.data.paypal?.publishableKey;if(!t&&!n)throw new qe.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 fs(e){if(e)return e.isPaypal?"paypal":"card"}async function ma({publishableKey:e,paypalPublishableKey:t,billingApiUrl:n,locale:r,telemetry:o}){if(!e)return{flopay:null,paypalFlopay:null};let a=t&&t!==e?t:void 0,[l,c]=await Promise.all([(0,ao.loadFloPay)(e,{billingApiUrl:n,locale:r,telemetry:o}),a?(0,ao.loadFloPay)(a,{billingApiUrl:n,locale:r,telemetry:o}).catch(m=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",m),null)):Promise.resolve(null)]),y=null;return a?y=c:t&&(y=l),{flopay:l,paypalFlopay:y}}var Pr=require("@flopay/js"),u=require("@flopay/shared"),qt=require("@stripe/react-stripe-js"),s=Yi(require("react"),1);function vs(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 sr=require("react");function Ps(e,t){if(!e)return t;let n=t??{},r=Object.keys(n),o=r.some(l=>l.startsWith("background")),a={};for(let[l,c]of Object.entries(e))l in n||o&&l.startsWith("background")||(a[l]=c);for(let l of r)a[l]=n[l];return a}var nc=new Set(["animationIterationCount","aspectRatio","borderImageOutset","borderImageSlice","borderImageWidth","boxFlex","boxFlexGroup","boxOrdinalGroup","columnCount","columns","flex","flexGrow","flexPositive","flexShrink","flexNegative","flexOrder","gridArea","gridRow","gridRowEnd","gridRowSpan","gridRowStart","gridColumn","gridColumnEnd","gridColumnSpan","gridColumnStart","fontWeight","lineClamp","lineHeight","opacity","order","orphans","scale","tabSize","widows","zIndex","zoom","fillOpacity","floodOpacity","stopOpacity","strokeDasharray","strokeDashoffset","strokeMiterlimit","strokeOpacity","strokeWidth"]);function rc(e){let t=e.replace(/^(Webkit|Moz|ms)(?=[A-Z])/,"");return nc.has(t.charAt(0).toLowerCase()+t.slice(1))}function oc(e,t){return typeof t=="number"&&t!==0&&!rc(e)?`${t}px`:String(t).trim()}function Ss(e,t){if(e.style.cssText="",!!t){for(let[n,r]of Object.entries(t))if(!(r==null||r==="")){if(n.startsWith("--")){e.style.setProperty(n,String(r));continue}e.style[n]=oc(n,r)}}}var ws=require("react/jsx-runtime");function so({capture:e,html:t,messageToken:n,expectedOrigin:r,theme:o,containerStyle:a,onReady:l,onError:c,onValidation:y}){let m=(0,sr.useRef)(null),p=(0,sr.useRef)(l),g=(0,sr.useRef)(c),f=(0,sr.useRef)(y);p.current=l,g.current=c,f.current=y;let P=(0,sr.useRef)(o);P.current=o;let A=(0,sr.useRef)(null);return(0,sr.useEffect)(()=>{let D=m.current;if(!D)return;let he=!0,H=!1,S=()=>{!he||H||(H=!0,p.current?.())},le=e.on("ready",()=>{S()}),q=e.on("error",ce=>{g.current?.(ce.message??"There was a problem loading the secure card form.")}),pe=e.on("validation",ce=>{f.current?.(ce.message??null)}),oe={html:t,...n?{messageToken:n}:{},...r?{expectedOrigin:r}:{},...P.current?{theme:P.current}:{}};return A.current=P.current??null,e.mount(D,oe).then(()=>{S()}).catch(ce=>{he&&g.current?.(ce instanceof Error?ce.message:"Failed to load the secure card form.")}),()=>{he=!1,le(),q(),pe(),e.unmount()}},[e,t,n,r]),Br(()=>{let D=m.current;D&&Ss(D,a)},[a]),(0,sr.useEffect)(()=>{o!==void 0&&(o===null&&A.current===null||(A.current=o,e.applyTheme?.(o)))},[e,o]),(0,ws.jsx)("div",{ref:m,"data-testid":"flopay-vault-card-fields"})}var Is=/^#([0-9a-f]{6})$/i,ac=/^#([0-9a-f]{3})$/i,Rs=/^rgb\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)$/i,Es=/^rgba\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(0|1|0?\.\d+|1\.0+)\s*\)$/i,ic=/^linear-gradient\(\s*(-?\d+(?:\.\d+)?)deg\s*,\s*(.+)\)$/i,sc=/^(-?\d+(?:\.\d+)?)(?:px)?$/,lc=/^(-?\d+(?:\.\d+)?)em$/,cc=/^blur\(\s*(\d+(?:\.\d+)?)(?:px)?\s*\)$/i,dc=/^[a-z][a-z0-9 -]{0,31}$/i,uc=new Set(["none","uppercase","lowercase","capitalize"]);function _s(e){if(typeof e!="string")return null;let t=e.trim(),n=Is.exec(t);if(n){let p=Number.parseInt(n[1],16);return{r:p>>16&255,g:p>>8&255,b:p&255,a:null}}let r=ac.exec(t);if(r){let[p,g,f]=r[1].split("").map(P=>Number.parseInt(P+P,16));return{r:p,g,b:f,a:null}}let o=Rs.exec(t),a=o?null:Es.exec(t),l=o??a;if(!l)return null;let c=Number(l[1]),y=Number(l[2]),m=Number(l[3]);return c>255||y>255||m>255?null:{r:c,g:y,b:m,a:a?Number(a[4]):null}}function Ts({r:e,g:t,b:n,a:r}){return r===null?`#${(1<<24|e<<16|t<<8|n).toString(16).slice(1)}`:`rgba(${e},${t},${n},${r})`}function Bo(e){if(typeof e!="string")return;let t=e.trim();if(Is.test(t)||Rs.test(t))return t;let n=Es.exec(t);if(n&&/^\d/.test(n[4]))return t;let r=_s(t);return r?Ts(r):void 0}function ya(e,t=.12){let n=_s(e);if(!n)return e;let r=Math.max(0,Math.min(1,1-t));return Ts({r:Math.round(n.r*r),g:Math.round(n.g*r),b:Math.round(n.b*r),a:n.a})}function Fo(e,t){let n=[],r=0,o="";for(let a of e){if(a==="("&&(r+=1),a===")"&&(r-=1),a===t&&r===0){o.trim()&&n.push(o.trim()),o="";continue}o+=a}return o.trim()&&n.push(o.trim()),n}function Dr(e,t,n){if(typeof e!="number"&&typeof e!="string")return;let r=sc.exec(String(e).trim());if(!r)return;let o=Number(r[1]);return Number.isFinite(o)&&o>=t&&o<=n?o:void 0}function pc(e,t,n){if(typeof e!="string")return;let r=lc.exec(e.trim());if(!r)return;let o=Number(r[1]);return Number.isFinite(o)&&o>=t&&o<=n?o:void 0}function mc(e){let t=Fo(e,",");if(t.length<2||t.length>5)return;let n=[];for(let[r,o]of t.entries()){let a=Fo(o," "),l=Bo(a[0]);if(!l)return;let c=r/(t.length-1)*100,y=a[1]===void 0?c:Number(/^(\d+(?:\.\d+)?)%$/.exec(a[1])?.[1]),m=n[n.length-1]?.position??-1;if(!Number.isFinite(y)||y<0||y>100||y<m)return;n.push({color:l,position:y})}return{type:"linearGradient",angle:0,stops:n}}function yc(e){if(typeof e!="string")return;let t=e.trim(),n=Bo(t);if(n)return{type:"solid",color:n};let r=ic.exec(t);if(!r)return;let o=Number(r[1]);if(!Number.isFinite(o)||o<0||o>360)return;let a=mc(r[2]);return a&&a.type==="linearGradient"?{...a,angle:o}:void 0}function fc(e){return e.type==="solid"?{type:"solid",color:ya(e.color)}:{...e,stops:e.stops.map(t=>({...t,color:ya(t.color)}))}}function gc(e){let t=!1,n,r=[];for(let y of Fo(e," ")){if(y.toLowerCase()==="inset"){t=!0;continue}let m=Bo(y);if(m){n=m;continue}let p=Dr(y,-128,128);if(p===void 0)return;r.push(p)}if(!n||r.length<2||r.length>4)return;let[o,a,l=0,c=0]=r;if(!(Math.abs(o)>64||Math.abs(a)>64||l>128||Math.abs(c)>32))return{color:n,inset:t,offsetX:o,offsetY:a,blur:l,spread:c}}function hc(e){if(typeof e!="string")return;let t=e.trim();if(t.toLowerCase()==="none")return[];let n=Fo(t,",").map(gc);if(!(n.length===0||n.length>4))return n.every(r=>r!==void 0)?n:void 0}function ks(e){if(typeof e!="string")return;let t=Fo(e,",").map(n=>n.replace(/^['"]|['"]$/g,"").trim()).filter(n=>dc.test(n)).slice(0,4);return t.length>0?t:void 0}function bc(e){let t=typeof e=="string"?e.trim().split(/\s+/):[e],n=Dr(t[0],0,64),r=Dr(t[1]??t[0],0,64);if(!(n===void 0||r===void 0))return{paddingBlock:n,paddingInline:r}}function vc(e){if(e==="bold")return 700;if(e==="normal")return 400;let t=Number(e);return Number.isInteger(t)&&t>=100&&t<=900?t:void 0}function xs({appearance:e,buttonsStyles:t,fontFamily:n}){let r=t.submitButton;if(!r)return;let o=e?.variables,a=yc(r.background??r.backgroundColor),l=Bo(o?.colorPrimaryHover),c=l?{type:"solid",color:l}:a&&fc(a),y={fontFamilies:ks(r.fontFamily)??ks(n),fontSize:Dr(r.fontSize??t.submitButtonFontSize,10,32)??16,fontWeight:vc(r.fontWeight)??600,letterSpacing:pc(r.letterSpacing,-.1,.5)??.01,lineHeight:Dr(r.lineHeight,.8,2)??1,textTransform:uc.has(String(r.textTransform))?r.textTransform:"uppercase"},m=bc(r.padding),p=hc(r.boxShadow),g=Dr(r.borderRadius,0,9999),f=typeof r.backdropFilter=="string"?Dr(cc.exec(r.backdropFilter.trim())?.[1],0,40):void 0;return{foregroundColor:Bo(r.color)??"#FFFFFF",...a?{background:a,disabledBackground:a}:{},...c?{hoverBackground:c}:{},typography:y,...m?{spacing:m}:{},...p?{shadow:p}:{},...g===void 0?{}:{borderRadius:g},disabledOpacity:e?.theme==="night"?.8:.6,...f===void 0?{}:{backdropBlur:f}}}function lo(e,t=.12){let n=e.trim(),r=/^[0-9a-fA-F]{6}$/.test(n)?`#${n}`:n;return/^#[0-9a-fA-F]{6}$/.test(r)?ya(r,t):e}function ei(e){if(typeof e=="number"||typeof e=="string")return e}function fa({appearance:e,buttonsStyles:t,layout:n="default"}){let r=e?.variables,o=g=>typeof g=="string"&&g?g:void 0,a=t.submitButton,l=o(r?.colorPrimary)??o(a?.backgroundColor)??"#4A49FF",c=n==="buttons",y=t.nameInput,m=o(y?.fontFamily)??o(r?.fontFamily)??"Poppins, sans-serif",p=xs({appearance:e,buttonsStyles:t,fontFamily:m});return{primaryColor:l,primaryHoverColor:o(r?.colorPrimaryHover)??lo(l,.12),inputBackgroundColor:o(t.cardInputBackground)??o(r?.colorBackground)??"#ffffff",textColor:o(t.cardInputColor)??o(y?.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:m,fontSize:o(t.cardInputFontSize)??o(r?.fontSizeBase)??"16px",fontWeight:String(ei(y?.fontWeight)??400),borderRadius:o(r?.borderRadius)??"8px",...p?{submitButton:p}:{}}}var d=require("react/jsx-runtime"),lr="flopay_stripe_resume",Ms="flopay_wallet_resume",$s="fw1",Cc=300*1e3,Pc=900,Sc=25e3,wc=25e3,ti={},ni={};function qs(e){return e instanceof u.FloPayError&&(e.type==="validation_error"||e.statusCode===400||e.statusCode===422)}async function ha(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 qs(o)||t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"intent_create",provider:r}),o}}var Do="flopay_paypal_resume",kc=250,As="Just a moment \u2014 we are finalizing your order. Please press pay again.";function si(e,t,n){e?.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:"provider_runtime",stage:"provider_load",provider:t,paymentMethodCategory:n,requestCategory:"provider_sdk"})}async function ba({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 Ic(e){return e instanceof u.FloPayError&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function ri(e){return e?.html?{html:e.html,...e.messageToken?{messageToken:e.messageToken}:{},...e.expectedOrigin?{expectedOrigin:e.expectedOrigin}:{}}:null}function js({event:e,fallbackEmail:t,fallbackName:n}){let r=e.billingDetails,o=t?.trim(),a=xr(n),l=a.firstName?a:xr(r?.name);return kn({email:(0,u.isValidEmail)(o)?o:r?.email?.trim(),firstName:l.firstName,lastName:l.lastName})}async function Rc({event:e,prepared:t,email:n,billingName:r,methodLabel:o,collect:a}){let l=js({event:e,fallbackEmail:t?.accountPatch?.email??n,fallbackName:[t?.accountPatch?.firstName,t?.accountPatch?.lastName].join(" ").trim()||r});return(0,u.isValidEmail)(l.email)?l:a(o,l)}var Ec=`
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 @@ ${Yt.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
- `,pa=44,Bo=280,Cs=`flopay-card-enter ${Bo}ms cubic-bezier(0, 0, 0.2, 1) both`,Ps=`flopay-card-exit ${Bo}ms cubic-bezier(0.4, 0, 0.2, 1) both`,Gl=`flopay-buttons-enter ${Bo}ms cubic-bezier(0, 0, 0.2, 1) both`,Jl=`flopay-buttons-exit ${Bo}ms cubic-bezier(0.4, 0, 0.2, 1) both`;function Xl(e){return e.gateway==="stripe"?"stripe":e.gateway==="paypal"||e.isPaypal?"paypal":void 0}function oi(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 Zl={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"};function Ql(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 Ms={width:"100%",minHeight:pa,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 ec(e){switch(e){case"paypal":return"PayPal";case"apple_pay":return"Apple Pay";case"google_pay":return"Google Pay";default:return"Card"}}function Ss(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function ti(e){return e==="paypal"?"PayPal":(0,u.getStripeMethodDisplayName)(e)}function tc(e,t){let n=`We couldn't open ${ti(e)}. Try again or choose another payment method.`;return t?`${n} Allow pop-ups for this site, then try again.`:n}function nc(e){let t=(0,u.getPostalCodeExample)(e);return`Enter a valid ${(0,u.getPostalCodeLabel)(e)}${t?` (e.g. ${t})`:""}`}function rc(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 oc(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 ws(e,t){return t instanceof u.FloPayError?t:new u.FloPayError(t instanceof Error?t.message:`${ec(e)} before-click hook failed.`,"validation_error")}function ei(){return(0,l.jsx)("style",{children:Yl})}function ac(e){return typeof e=="number"?`${e}px`:e}function As(e,t){let n=e.availablePaymentMethods;return n&&t.some(r=>n[r])?"ready":"unavailable"}function Bs({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 ks(e){return e!=="unavailable"&&e!=="load_error"}function fa(e){return(0,l.jsx)(sc,{...e})}function Is({sessionId:e,nonce:t,email:n,billingApiUrl:r,onTokenizedBody:o,onErrorChange:i,isProcessing:d=!1,onButtonClick:c,onDecline:v,onTechnicalFailure:y,runBeforeButtonClick: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:Pe,finish:Rt}=Gr(),$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:Ie,finishAttempt:ve,invalidateAttempt:x,isAttemptInvalidated:Q,isAttemptCurrent:Se}=Io((ie,Y,$)=>{y?.(ie,Y,{...$,popupBlocked:$?.popupBlocked??wr(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:wr(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(Ao);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(Ao)}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 $=Ie("paypal");te.current.set(le,{generation:$,accountPatch:Y.accountPatch,sessionId:Y.sessionId,nonce:Y.nonce}),Fe(!1),c?.("paypal"),ie.resolve()},[d,c,f,Ie,de,le]),Ge=(0,s.useCallback)(async ie=>{if(!V||!S)return;let Y=te.current.get(le);if(Y&&!Se(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 Wl({event:ie,prepared:$,email:n,billingName:g,methodLabel:"PayPal",collect:Pe});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:Re}=await h({type:"paypal"});if(tt){ce(tt,"stripe_paypal_create_payment_method_failed",Y?.generation),ie.paymentFailed({reason:"fail"});return}let O=await ma(r,ge,Ue,Qe??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:Re?.id??null,intentKind:"payment"});if(O.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let Le=O.clientSecret,Te={return_url:window.location.href};if(Re?.id&&(Te.payment_method=Re.id),typeof window<"u")try{localStorage.setItem(Ao,JSON.stringify({clientSecret:Le,sessionId:Ue,nonce:Qe,accountPatch:ne}))}catch{}let{error:pt,paymentIntent:mt}=await V.confirmPayment({clientSecret:Le,confirmParams:Te,redirect:"if_required"});if(pt){if(typeof window<"u")try{localStorage.removeItem(Ao)}catch{}if(So(pt)){let A=pt.message??"Your payment was declined.";i?.(A),v?.(Qt("paypal",A,{code:hr(pt),declineCode:Xr(pt)})),await ya({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(Ao)}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,Pe,p,r,ge,o,i,v,f,ce,ve,Se,Q,le]);return(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(Bs,{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:Ms,children:"Try PayPal again"}),Ke&&(0,l.jsx)(Jr,{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(As(ie,["paypal"])),onLoadError:()=>{q("load_error"),ri(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 Rs({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:Pe,collect:Rt,finish:$e}=Gr(),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"),Ie=(0,s.useRef)(!1),ve=(0,s.useRef)("google_pay"),x=(0,s.useRef)("google_pay"),Q=(0,s.useRef)(null),Se=(0,s.useRef)(new Set);(0,s.useEffect)(()=>()=>{for(let h of Se.current)window.clearTimeout(h);Se.current.clear()},[]);let ue=(0,s.useRef)(new Map),{startAttempt:ce,finishAttempt:ze,invalidateAttempt:rt,isAttemptInvalidated:gt,isAttemptCurrent:Ge,generationRef:ie}=Io((h,tt,Re)=>{f?.(h,tt,{...Re,popupBlocked:Re?.popupBlocked??wr(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,Re,O)=>{rt(O),f?.(h,tt,{code:Re,popupBlocked:wr(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)(()=>{Ie.current&&(Ie.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,Re=He=>{tt||(tt=!0,h.paymentFailed({reason:"fail",...He?{message:He}:{}}))};if(!S||!se){Re();return}let O=ue.current.get(le);if(O&&!Ge(O.generation)){ue.current.delete(le),Re();return}if(!O&&gt()){Re();return}if(O&&!ze(O.generation)){Re();return}O||ze();let Le=h.expressPaymentType??O?.method??ve.current,Te=O??null,pt=Ss(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(Xa)},jl),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),!Te&&g){let P=await Nt("processing","other",g(pt));if(!P.proceed){Re();return}Te={accountPatch:P.accountPatch,sessionId:P.sessionId,nonce:P.nonce}}let He=Te?.sessionId??e;jt=He;let yt=Te?.nonce??t,Ct=Q.current??Te?.accountPatch,on=xs({event:h,fallbackEmail:Ct?.email??n,fallbackName:[Ct?.firstName,Ct?.lastName].join(" ").trim()||p});if(!(0,u.isValidEmail)(on.email)){Re("Buyer details are required."),Rt(ti(Le),on).then(P=>{P&&(Q.current=P)});return}Q.current=null;let ct={...Te?.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){Re(),$(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",ma(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&&Se.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(()=>{})},Vl),Se.current.add(L);let Ot=P=>{L!==null&&(window.clearTimeout(L),Se.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":Co(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=`${_s}:${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 Za;sn=Ot(xt.error?"returned_error":"resolved")}catch(P){let ft=P===Za,Et=Ot(ft?"returned_error":"rejected");throw A?.error({...ft?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response"}:Ua(P),...an,operationOutcome:Et.operationOutcome,checkoutSessionId:He,durationMs:Et.durationMs,statusClass:"unknown"}),P}let Pt=xt.error;if(Pt){if(So(Pt)){let P=Pt.message??"Your payment was declined.";Re(P),c?.(P),y?.(Qt(pt,P,{code:hr(Pt),declineCode:Xr(Pt)})),ya({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({...Ua(Pt),...an,operationOutcome:sn.operationOutcome,checkoutSessionId:He,durationMs:sn.durationMs,statusClass:"unknown"}),Re(),$(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===Xa){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(()=>{})}Re(),$(Le,He,He===Xa?"stripe_wallet_authorization_timeout":"stripe_wallet_failed",O?.generation)}finally{if(window.clearTimeout(hn),L!==null&&(window.clearTimeout(L),Se.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"]),Re=new Set(i.map(u.stripeExpressMethodToOptionKey)),O={};for(let Le of h)Re.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)(Bs,{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:Ms,children:["Try ",ti(De)," again"]}),Pe&&(0,l.jsx)(Jr,{identity:Pe.identity,methodLabel:Pe.methodLabel,onComplete:$e,onCancel:()=>$e(null)},Pe.id),(0,l.jsx)("div",{style:{display:Pe?"none":void 0},children:(0,l.jsx)($t.ExpressCheckoutElement,{onReady:h=>{de(As(h,ne))},onLoadError:h=>{de("load_error"),ri(Wt(ge),"stripe","wallet")},onClick:async h=>{ve.current=h.expressPaymentType,x.current=Ss(h.expressPaymentType);let tt=!0,Re=window.setTimeout(()=>{tt=!1,h.reject()},$l),O=g?await g(x.current):{proceed:!0};if(window.clearTimeout(Re),!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),Ie.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 Fs(e,t){return{...e,paymentMethodTypes:[t],...t==="revolut_pay"||t==="sepa_debit"||t==="us_bank_account"?{setupFutureUsage:"off_session"}:null}}function ic({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=gs[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:pa,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 ni({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),[Pe,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||!Pe)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,Ie=De.nonce??n,ve=xr(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,Se=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 ma(d,se,te,Ie??"",{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:Ie,accountPatch:Se,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 ya({billingApiUrl:d,sessionId:te,nonce:Ie,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:Y.code??"provider_declined"}});return}let Ue=$?.status;if(!Co(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:Se,paymentMethodCategory:"apm",sessionId:te,nonce:Ie})}catch(ue){v?.(ue instanceof Error?ue.message:"Payment failed. Please try again.")}finally{Ke.current=!1,he(!1)}},[q,de,I,Pe,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"),ri(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:!Pe||!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:!Pe||!D||G||I||$e!=="ready"?"not-allowed":"pointer",opacity:!Pe||!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)(Qr,{margin:"0.75rem 0 0",children:V})]})}function Es({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,Pe]=(0,s.useState)(null),[Rt,$e]=(0,s.useState)(null),Ae=(0,s.useRef)(!1),{request:Be,collect:le,finish:ae}=Gr();(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 Se=Q.sessionId??e,ue=Q.nonce??t,ce=xr([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),!Se||!(0,u.isValidEmail)(rt))throw new Error("Missing sessionId or email for payment.");await o?.(ze);let Ge=await ma(i,he,Se,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:Se,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 ya({billingApiUrl:i,sessionId:Se,nonce:ue,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:x,providerDeclineReason:Y.code??"provider_declined"}});return}let Ue=$?.status;if(!Co(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:Se,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,Ie=(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?Fs(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)(Jr,{identity:Be.identity,methodLabel:Be.methodLabel,onComplete:ae,onCancel:()=>ae(null)},Be.id):d.map(x=>{let Q=G===x,Se=Rt===x,ue=Rt!==null&&Rt!==x||G!=null&&G!==x;return(0,l.jsxs)(s.default.Fragment,{children:[(0,l.jsx)(ic,{method:x,themeId:q,submitting:Se,disabled:ue,highlighted:Q,hasNextStep:(0,u.needsStripeMethodExplicitConfirm)(x),onClick:()=>Ie(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)(ni,{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 sc({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:Pe,appearance:Rt,cardButtonContent:$e,cardBackButtonContent:Ae,cardTitleContent:Be,showSecurityFooter:le,onButtonClick:ae,onBeforeButtonClick:D,onBuyerIdentityReady:Fe,enableAVS:De,cardFieldOrder:te,cardPreFormSlot:Ie,avsLayout:ve="row",country:x,zip:Q,addressLine1:Se,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:Re=!1}){let O=vr(),Le=Jo(),Te=(0,s.useContext)(tr),{emitInstrument:pt}=(0,s.useContext)(qn),mt=ne??Te.session,R=mt?.gateways?.paypal?.providerObjectType??ye?.providerObjectType,A=h||Te.claimPending===!0,ht=tt||Te.claimRequiresIdentity===!0,Je=A&&!ht,Yt=es(),[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)(Se??""),[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)(Se??""),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 ke=W?.trim();!ke||ke===Oe.current||(Oe.current=ke,Z(ke),Ce?.(ke))};a("country",x,Ot,Lt,rt),a("zip",Q,Kt,In,gt),a("addressLine1",Se,en,Nt),a("addressLine2",ue,Xt,yt),a("city",ce,Rn,on),a("state",ze,xt,vn)},[x,Q,Se,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,we=!!(V&&z&&O&&e),[tn,dn]=(0,s.useState)(()=>G!=="buttons"||Qe?e??null:null),[Ee,Hn]=(0,s.useState)(0),Dn=G!=="buttons"||Qe||!!e&&tn===e,zt=(0,s.useMemo)(()=>!O||!we||!e||!Dn?null:O.cardCapture({sessionId:e,captureMethod:ne?.captureMethod}),[O,we,e,Dn,ne?.captureMethod]),un=(0,s.useMemo)(()=>{let a=lt,C=P?(0,u.isAVSFieldVisible)(P.postal_code,a):!1;return rc(a,gn,C)},[P,lt,gn]),{avsInvalid:Ir,invalidAvsFields:Rr}=(0,s.useMemo)(()=>{let a={line1:!1,city:!1,state:!1,zip:!1};if(!we||!P)return{avsInvalid:!1,invalidAvsFields:a};let C=lt,W=(Ce,ke)=>(0,u.isAVSFieldVisible)(Ce,C)&&!ke.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}},[we,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)(()=>Qa(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()},Bo)},[]);(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||Te.claimBuyerIdentity||ne?.buyerIdentified!==!1||!e||!t)return;let a=`${pe}|${e}|${t}`;at.current?.key!==a&&(at.current={key:a,claim:Wr(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,Te.claimBuyerIdentity,ne?.buyerIdentified,e,t,pe,o,y,f]),m=Fe??Te.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 Pe?{...a,...Pe,cardButton:{...a.cardButton,...Pe.cardButton},cardFormContainer:{...a.cardFormContainer,...Pe.cardFormContainer},backButton:{...a.backButton,...Pe.backButton},backButtonIcon:{...a.backButtonIcon,...Pe.backButtonIcon},submitButton:{...a.submitButton,...Pe.submitButton},title:{...a.title,...Pe.title}}:a},[K,Ke,Pe]),H=Rt??K?.appearance,Ye=(0,s.useMemo)(()=>ua({appearance:H,buttonsStyles:b,layout:G}),[H,b,G]),ln=Te.inlineSessionPatchProcessing??!1,it=(I??fn)||ln,st=pe.replace(/\/+$/,""),me=(0,s.useMemo)(()=>za({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);we&&Ne.current===null&&(Ne.current=Ze);let _e=we&&(Ne.current??Ze),bt=(0,s.useMemo)(()=>oc(Xe,_e),[Xe,_e]),nn=bt.empty||bt.malformed,xe=(0,s.useMemo)(()=>O?O.getRawProvider():null,[O]),Pn=(0,s.useMemo)(()=>Le?Le.getRawProvider():null,[Le]),On=$||100,Lr=Ue.toLowerCase(),Sa=(0,s.useMemo)(()=>H?(0,Pr.toStripeAppearance)(H):null,[H]),Nr=Sa,pi=(0,s.useMemo)(()=>{let a=Sa??{},C=a.rules??{};return{...a,rules:{...C,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...C[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...C[".AccordionItemContents"]??{}}}}},[Sa]),mi=(0,s.useMemo)(()=>({...Ji($,ne?.captureMethod),currency:Lr,...Nr?{appearance:Nr}:null}),[$,Lr,ne?.captureMethod,Nr]),yi=(0,s.useMemo)(()=>({mode:"payment",amount:On,currency:Lr,captureMethod:"manual",setupFutureUsage:"off_session",...Nr?{appearance:Nr}:null}),[On,Lr,Nr]),fe=(0,s.useCallback)(a=>{Gt(a),N?.(a)},[N]),wa=(0,s.useRef)(""),[fi,Vs]=(0,s.useState)(!1),ka=(0,s.useCallback)(()=>{Vs(!0)},[]);(0,s.useEffect)(()=>{if(!we||!_e||!m||!fi||nn||wa.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()});wa.current=JSON.stringify(a),an(C=>({...C,...a})),Promise.resolve(m(a)).catch(C=>{wa.current="",fe(C instanceof Error?C.message:"Failed to attach buyer details.")})},[we,_e,m,fi,nn,me.email,me.firstName,me.lastName,fe]),(0,s.useEffect)(()=>{!we||!zt||zt.setCardFieldOrder?.(te??null,P==null&&!_e)},[we,zt,te,P,_e]),(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]),Or=(0,s.useCallback)((a,C,W)=>{let Oe=W?.popupBlocked??wr(C),Z=tc(a,Oe),Ce=Ar(W?.code)??hr(C)??"external_payment_method_failed",ke=new u.FloPayError(Z,"api_error",{code:"external_payment_method_failed",param:a});ee(null),G==="buttons"&&(pn("buttons"),pr(null)),fe(Z),d?.(ke),console.error("[FloPay] External payment method failed:",{method:a,code:Ce,popupBlocked:Oe})},[G,d,fe]);(0,s.useEffect)(()=>{if(!we||!e){Xn(null);return}let a=Qa(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=Qa(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}},[we,Dn,Ee,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 Ia=(0,s.useRef)(!1),gi=(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",ke=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&&!ke&&Bt?(0,u.getStateFromPostalCode)(Ce,(Kt.current??"").trim()):null,fr=ke?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:ke}}:{}}},[]),hi=(0,s.useRef)(A);hi.current=A,(0,s.useEffect)(()=>{A||M!==bs||ar.current.updateError(null)},[A,M]),(0,s.useEffect)(()=>{!we||!zt||zt.setSubmitGate?.(Ir||A||nn)},[we,zt,Ir,A,nn]),(0,s.useEffect)(()=>{if(!we||!zt)return;Ia.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")},Kl),ee("processing");let ke=ar.current;if(!ke.sessionId||!ke.nonce)return;let wt=gi();if(!wt){ke.updateError("Enter a valid email address."),B.current="idle",ee(null);return}new Pr.PaymentAPI(ke.baseUrl).patchAccountSnapshot(ke.sessionId,ke.nonce,wt,{telemetryMode:"best_effort"}).catch(Bt=>{if(!Hl(Bt))return;let Ft=Bt instanceof Error?Bt.message:"Please check your billing address and try again.";ke.updateError(Ft),B.current="idle",ee(null),ke.onError?.(Bt instanceof u.FloPayError?Bt:new u.FloPayError(Ft,"api_error"))})}),W=zt.on("complete",async ke=>{if(no(ke.sessionId??ar.current.sessionId),B.current="terminal",ee("success"),await new Promise(Ft=>setTimeout(Ft,1200)),Ia.current)return;Ia.current=!0;let wt=ar.current,Bt=(0,u.isAuthorizationOnlySession)(wt)||ke.outcome==="authorized";ar.current.onComplete?.(Bt?{status:"authorized",paymentIntentId:ke.intentId,paymentId:ke.paymentId??wt.paymentId,sessionId:ke.sessionId??wt.sessionId,authorizationExpiresAt:ke.authorizationExpiresAt??wt.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",paymentIntentId:ke.intentId,checkoutMethod:"card"})}),Oe=zt.on("decline",async ke=>{let wt=ar.current,Bt=ke.message??"Your payment was declined. Please try another card or contact your bank.";B.current="terminal",wt.updateError(Bt),ee("error");let Ft=ke.failureOutcome??(0,u.normalizeCheckoutFailureOutcome)(ke.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 ke=>{let wt=ar.current,Bt=ke.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:ke.failureOutcome??"capture_failed"})),await new Promise(Ft=>setTimeout(Ft,1500)),!a&&(B.current="idle",ee(null))}),Ce=zt.on("blocked",()=>{if(!hi.current){ur(!0);return}ka(),ar.current.updateError(bs)});return()=>{a=!0,E.current&&(clearTimeout(E.current),E.current=null),B.current="idle",C(),W(),Oe(),Z(),Ce()}},[we,zt,ka,gi]);let ir=!!ye?.clientId,so=Array.isArray(S),No=so&&S.length>0,Ks=so&&S.includes("paypal"),{expressMethods:Oo,paymentElementMethods:lo}=(0,s.useMemo)(()=>(0,u.partitionStripeMethods)(S,{excludePaypal:ir}),[S,ir]),vi=ir||!!Le,Hs=(0,s.useMemo)(()=>vi?Oo.filter(a=>a!=="paypal"):Oo,[Oo,vi]),Ws=(0,s.useMemo)(()=>{let a=[];return q&&a.push("apple_pay"),de&&a.push("google_pay"),a},[q,de]),zr=so?Hs:Ws,Ys=V&&zr.length>0,Ra=ft?lt:x,zo=(0,s.useMemo)(()=>{let a=Ra?.trim().toUpperCase();return a?se?lo.filter(C=>{let W=se[C];return!W||W.length===0||W.includes(a)}):(0,u.filterStripeMethodsByCountry)(lo,Ra):lo},[lo,Ra,se]),Ea=(0,s.useMemo)(()=>({mode:"payment",amount:On,currency:Lr,paymentMethodCreation:"manual",appearance:pi}),[On,Lr,pi]),[bi,Ci]=(0,s.useState)("loading"),[Pi,Si]=(0,s.useState)("loading"),[wi,ki]=(0,s.useState)("loading"),[Gs,_a]=(0,s.useState)(!1),[Ii,Ta]=(0,s.useState)("loading"),[Uo,Js]=(0,s.useState)();(0,s.useEffect)(()=>{Js(fs())},[]);let Ri=ge&&(ir||(so?Ks:Uo===!1)),Ei=V&&Ys,co=!Je&&Ri&&ir,_i=Ii==="retrying"||Ii==="exhausted",uo=!Je&&Ri&&!!Pn&&(!ir||_i),Ur=!Je&&Ei&&!!xe,po=!Je&&V&&No&&zo.length>0&&!!xe,Xs=co&&!_i?Gs:uo&&ks(bi),Zs=Ur&&ks(Pi),Qs=po&&wi!=="load_error",Ti=a=>a==="loading"||a==="ready",xi=co||uo&&Ti(bi)||Ur&&Ti(Pi)||po&&wi!=="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&&!xi){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,xi,d,fe]);let Mi=(0,s.useRef)(!1);(0,s.useEffect)(()=>{if(Mi.current||!No)return;let a=[];q!==!0&&a.push("showApplePay"),de!==!0&&a.push("showGooglePay"),a.length!==0&&(Mi.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 Ai=(0,s.useCallback)((a,C)=>Te.applyInlineSessionPatch?Te.applyInlineSessionPatch(a).then(W=>({error:null,sessionId:W.sessionId||e,nonce:W.session?.clientSecret||t})).catch(W=>{let Oe=ws(C,W);return fe(Oe.message),d?.(Oe),{error:Oe,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[Te.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:Te.inlineSessionDraft});if(C===!1)return{proceed:!1};if(C&&typeof C=="object"){C.account&&an(Oe=>({...Oe??{},...C.account}));let W=await Ai(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=ws(a,C);return fe(W.message),d?.(W),{proceed:!1}}},[Ai,Te.inlineSessionDraft,D,d,e,fe]),Bi=(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=za(me,C?.accountPatch),Ce=C?.completionPaymentMethodId??Po(a),ke=a.originalPaymentMethodId?{...a,originalPaymentMethodId:void 0}:a,wt=Xl(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??Ql(a),tokenizedData:ke,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),Tr=mn&&!Un&&Dt?(0,u.getStateFromPostalCode)(ut,(Kt.current??"").trim()):null,vo=Un?xt.current:Tr;return{country:ut,...Dt&&Kt.current?{zip:Kt.current}:{},...(0,u.isAVSFieldVisible)(P.city,ut)&&Rn.current?{city:Rn.current}:{},...vo?{state:vo}:{},...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";no(W),ee("success"),vt(null),await new Promise(Tr=>setTimeout(Tr,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:Tr}=await mn.confirmPayment({clientSecret:ut,confirmParams:Dt,redirect:"if_required"});if(Tr){ee("error");let vo=Tr.message??"PayPal payment failed.";fe(vo),Qn("paypal",vo,{code:Tr.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}_a(!1),Ta("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){Ts(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):Bi(a,C)},[v,Bi]),mo=`${_s}:${e}`;(0,s.useEffect)(()=>{if(typeof window>"u")return;let a=localStorage.getItem(mo);if(!a)return;let C;try{C=JSON.parse(a)}catch{localStorage.removeItem(mo);return}if(!C||typeof C.createdAt!="number"||Date.now()-C.createdAt<0||Date.now()-C.createdAt>ql||typeof C.paymentMethodId!="string"||typeof C.providerIntentId!="string"||typeof C.paymentMethodType!="string"||C.sessionId!==e||!t||C.nonce!==t||!zr.includes(C.paymentMethodType)){localStorage.removeItem(mo);return}localStorage.removeItem(mo),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,mo,zr]);let Fi=(0,s.useRef)(!1);(0,s.useEffect)(()=>{if(typeof window>"u"||Fi.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(vs),ke;if(Ce?.clientSecret){if(Ce.clientSecret!==W)return;ke={...Ce.accountPatch?{accountPatch:Ce.accountPatch}:{},...Ce.sessionId?{sessionId:Ce.sessionId}:{},...Ce.nonce?{nonce:Ce.nonce}:{}}}else if(Ce?.sessionId&&Ce.sessionId!==e)return;Fi.current=!0,localStorage.removeItem(sr),localStorage.removeItem(vs);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=Co(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},ke)})()},[e,Sn,O,fe,Qn]);let xa=(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 yo=G==="buttons",wn=H?.variables,el=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),Ma=wn?.colorBackground,tl=Ma&&!el.has(Ma)?Ma:void 0,fo=b.cardInputBorder??(yo?"#e5e7eb":"#A4A4FF"),Di=wn?.colorDanger??"#dc2626",At=a=>Rr[a]&&(_n[a]||En),$o=nn&&(St||En),zn=a=>a?Di:fo,jo=(un.malformed||un.empty)&&(Wn||En),nl=zn(jo),Aa=b.cardFormContainer?.backgroundColor??tl??(yo?"white":"#EDEDFF"),qr=b.cardInputBackground??wn?.colorBackground??"white",Ba=Vr(Ae),Li=Vr(Be),$r=b.nameInput,Ni=b.cardInputFontSize??ac($r?.fontSize)??wn?.fontSizeBase??"16px",Oi=typeof $r?.fontFamily=="string"?$r.fontFamily:wn?.fontFamily??"Poppins, sans-serif",zi=Ja($r?.fontWeight)??400,rl=b.cardInputColor??(typeof $r?.color=="string"?$r.color:void 0)??wn?.colorText??"#262833",ol=b.cardInputPlaceholderColor??"#9ca3af",Ut=wn?.borderRadius??"8px",Er=wn?.borderRadius??b.cardButton?.borderRadius??Ut,_r=wn?.colorPrimary??"#4A49FF",al=wn?.colorPrimaryHover??io(_r,.12),Fa=wn?.colorText??"#262833",Da={fontSize:Ni,fontFamily:Oi,fontWeight:zi,color:rl,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},go={marginTop:"0.375rem",...Da,fontSize:"0.75rem",lineHeight:1.4,color:Di},il={"--flopay-input-placeholder-color":ol,"--flopay-input-font-size":Ni,"--flopay-input-font-family":Oi,"--flopay-input-font-weight":String(zi)},ho=b.cardFormContainer??{},La=ho.padding??(yo?"0":"1rem"),Na=ho.borderRadius??Ut,sl=zt&&xn?(0,l.jsx)(ao,{capture:zt,html:xn.html,messageToken:xn.messageToken,expectedOrigin:xn.expectedOrigin,theme:Ye,onReady:()=>{if(!_e&&!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"}),Ui=(0,l.jsxs)("div",{onFocusCapture:a=>{["INPUT","SELECT","TEXTAREA","IFRAME"].includes(a.target.tagName)&&Mn()},style:{backgroundColor:Aa,borderRadius:Na,...ho,padding:La,...il,display:"flex",flexDirection:"column"},children:[(0,l.jsx)("style",{children:`
30
+ `,ga=44,No=280,Bs=`flopay-card-enter ${No}ms cubic-bezier(0, 0, 0.2, 1) both`,Fs=`flopay-card-exit ${No}ms cubic-bezier(0.4, 0, 0.2, 1) both`,_c=`flopay-buttons-enter ${No}ms cubic-bezier(0, 0, 0.2, 1) both`,Tc=`flopay-buttons-exit ${No}ms cubic-bezier(0.4, 0, 0.2, 1) both`;function xc(e){return e.gateway==="stripe"?"stripe":e.gateway==="paypal"||e.isPaypal?"paypal":void 0}function li(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 Mc={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"};function Ac(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 Vs={width:"100%",minHeight:ga,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 Bc(e){switch(e){case"paypal":return"PayPal";case"apple_pay":return"Apple Pay";case"google_pay":return"Google Pay";default:return"Card"}}function Ds(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function ai(e){return e==="paypal"?"PayPal":(0,u.getStripeMethodDisplayName)(e)}function Fc(e,t){let n=`We couldn't open ${ai(e)}. Try again or choose another payment method.`;return t?`${n} Allow pop-ups for this site, then try again.`:n}function Dc(e){let t=(0,u.getPostalCodeExample)(e);return`Enter a valid ${(0,u.getPostalCodeLabel)(e)}${t?` (e.g. ${t})`:""}`}function Nc(e,t,n){let r=(0,u.isPostalCodeSupported)(e),o=t.trim(),a=n&&r,l=a&&!o,c=a&&!!o&&!(0,u.isValidPostalCode)(e,o);return{visible:n,supported:r,required:a,empty:l,malformed:c}}function Lc(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 Ns(e,t){return t instanceof u.FloPayError?t:new u.FloPayError(t instanceof Error?t.message:`${Bc(e)} before-click hook failed.`,"validation_error")}function oi(){return(0,d.jsx)("style",{children:Ec})}function Oc(e){return typeof e=="number"?`${e}px`:e}function Hs(e,t){let n=e.availablePaymentMethods;return n&&t.some(r=>n[r])?"ready":"unavailable"}function Ks({state:e,placeholderTestId:t,borderRadius:n=8,children:r}){return e==="unavailable"||e==="load_error"?null:(0,d.jsxs)("div",{style:{position:"relative",minHeight:44},children:[(0,d.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,d.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 Ls(e){return e!=="unavailable"&&e!=="load_error"}function va(e){return(0,d.jsx)(Uc,{...e})}function Os({sessionId:e,nonce:t,email:n,billingApiUrl:r,onTokenizedBody:o,onErrorChange:a,isProcessing:l=!1,onButtonClick:c,onDecline:y,onTechnicalFailure:m,runBeforeButtonClick:p,billingName:g,onBuyerIdentityReady:f,onLoadStateChange:P,placeholderBorderRadius:A}){let D=vr(),{emitInstrument:he}=(0,s.useContext)($n),H=(0,qt.useStripe)(),S=(0,qt.useElements)(),[le,q]=(0,s.useState)("loading");(0,s.useEffect)(()=>{P?.(le)},[le,P]);let[pe,oe]=(0,s.useState)(!1),ce=!(0,u.isValidEmail)(n?.trim())||!g?.trim(),{request:Ve,collect:de,finish:Tt}=Xr(),Ge=(0,s.useRef)(!1),Ae=(0,s.useRef)(null),Be=(0,s.useRef)(null),[ae,ie]=(0,s.useState)(0),[O,Le]=(0,s.useState)(!1),Oe=(0,s.useRef)(!1),_e=(0,s.useRef)(new Map),{startAttempt:ze,finishAttempt:Pe,invalidateAttempt:w,isAttemptInvalidated:ue,isAttemptCurrent:be}=Ro((se,J,j)=>{m?.(se,J,{...j,popupBlocked:j?.popupBlocked??wr(J)}),Le(!0),ie(Ue=>Ue+1)});(0,s.useEffect)(()=>{O&&Be.current?.focus()},[O,ae]);let Y=(0,s.useCallback)(()=>{ie(se=>se+1)},[]),L=(0,s.useCallback)((se,J,j)=>{w(j),m?.("paypal",se,{code:J,popupBlocked:wr(se)}),Le(!0),Y()},[w,m,Y]),Se=(0,s.useCallback)(()=>{window.setTimeout(()=>{(Ae.current?.querySelector("iframe")??Ae.current)?.focus()},0)},[]);(0,s.useEffect)(()=>{Oe.current&&(Oe.current=!1,Se())},[Se,ae]);let rt=(0,s.useCallback)(()=>{Le(!1),a?.(null),Se()},[Se,a]);(0,s.useEffect)(()=>{if(!H||Ge.current)return;let se=new URLSearchParams(window.location.search),J=se.get("payment_intent"),j=se.get("payment_intent_client_secret"),Ue=se.get("redirect_status");if(!J||!j)return;Ge.current=!0;let Qe;try{let ot=localStorage.getItem(Do);if(ot){let te=JSON.parse(ot);te.clientSecret===j&&(Qe={...te.accountPatch?{accountPatch:te.accountPatch}:{},...te.sessionId?{sessionId:te.sessionId}:{},...te.nonce?{nonce:te.nonce}:{}})}}catch{}try{localStorage.removeItem(Do)}catch{}let fe=new URL(window.location.href);fe.searchParams.delete("payment_intent"),fe.searchParams.delete("payment_intent_client_secret"),fe.searchParams.delete("redirect_status"),window.history.replaceState({},"",fe.toString()),(async()=>{try{if(oe(!0),Ue==="failed"){let b="PayPal payment was declined. Please try again.";a?.(b),y?.(Qt("paypal",b));return}let{paymentIntent:ot,error:te}=await H.retrievePaymentIntent(j);if(te){a?.(te.message??"Failed to retrieve PayPal payment status.");return}if(ot&&(ot.status==="requires_capture"||ot.status==="succeeded")){let b=typeof ot.payment_method=="string"?ot.payment_method:ot.payment_method?.id;o({id:b??ot.id,type:"card",threeDSecureActionResultTokenId:ot.id,isPaypal:!0},Qe)}else{let b="PayPal payment was not completed. Please try again.";a?.(b),y?.(Qt("paypal",b))}}catch(ot){a?.(ot instanceof Error?ot.message:"Failed to complete PayPal payment.")}finally{oe(!1)}})()},[H,o,a,y]);let ht=(0,s.useCallback)(async se=>{if(l||pe){se.reject();return}let J=p?await p("paypal"):{proceed:!0};if(!J.proceed){_e.current.delete(ae),se.reject();return}let j=ze("paypal");_e.current.set(ae,{generation:j,accountPatch:J.accountPatch,sessionId:J.sessionId,nonce:J.nonce}),Le(!1),c?.("paypal"),se.resolve()},[l,c,p,ze,pe,ae]),Ye=(0,s.useCallback)(async se=>{if(!H||!S)return;let J=_e.current.get(ae);if(J&&!be(J.generation)){_e.current.delete(ae);return}if(!J&&ue()||J&&!Pe(J.generation))return;J||Pe();let j=J??null;if(_e.current.delete(ae),!j&&p){let b=await p("paypal");if(!b.proceed){se.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}j={accountPatch:b.accountPatch,sessionId:b.sessionId,nonce:b.nonce}}let Ue=j?.sessionId??e,Qe=j?.nonce??t,fe=await Rc({event:se,prepared:j,email:n,billingName:g,methodLabel:"PayPal",collect:de});if(!fe){se.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let ot=fe.email,te={...j?.accountPatch,...kn(fe,!0)};try{if(oe(!0),a?.(null),!Ue||!(0,u.isValidEmail)(ot))throw new Error("Missing sessionId or email for PayPal payment");await f?.(fe);let b=H.createPaymentMethod,{error:tt,paymentMethod:Ie}=await b({type:"paypal"});if(tt){L(tt,"stripe_paypal_create_payment_method_failed",J?.generation),se.paymentFailed({reason:"fail"});return}let z=await ha(r,he,Ue,Qe??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:Ie?.id??null,intentKind:"payment"});if(z.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let Fe=z.clientSecret,Te={return_url:window.location.href};if(Ie?.id&&(Te.payment_method=Ie.id),typeof window<"u")try{localStorage.setItem(Do,JSON.stringify({clientSecret:Fe,sessionId:Ue,nonce:Qe,accountPatch:te}))}catch{}let{error:mt,paymentIntent:yt}=await H.confirmPayment({clientSecret:Fe,confirmParams:Te,redirect:"if_required"});if(mt){if(typeof window<"u")try{localStorage.removeItem(Do)}catch{}if(ko(mt)){let B=mt.message??"Your payment was declined.";a?.(B),y?.(Qt("paypal",B,{code:br(mt),declineCode:Qr(mt)})),await ba({billingApiUrl:r,sessionId:Ue,nonce:Qe,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:br(mt)??"provider_declined"}})}else L(mt,"stripe_paypal_confirm_failed",J?.generation);return}if(typeof window<"u")try{localStorage.removeItem(Do)}catch{}let E=typeof yt?.payment_method=="string"?yt.payment_method:yt?.payment_method?.id;o({id:E??yt?.id,type:"card",threeDSecureActionResultTokenId:yt?.id,isPaypal:!0},{accountPatch:te,paymentMethodCategory:"paypal",sessionId:Ue,nonce:Qe});return}catch(b){L(b,"stripe_paypal_failed",J?.generation)}finally{oe(!1)}},[H,S,e,t,n,g,de,f,r,he,o,a,y,p,L,Pe,be,ue,ae]);return(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)(Ks,{state:le,placeholderTestId:"flopay-paypal-placeholder",borderRadius:A,children:(0,d.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:[O&&(0,d.jsx)("button",{ref:Be,type:"button","data-testid":"flopay-paypal-retry-button",onClick:rt,style:Vs,children:"Try PayPal again"}),Ve&&(0,d.jsx)(Zr,{identity:Ve.identity,methodLabel:Ve.methodLabel,onComplete:Tt,onCancel:()=>Tt(null)},Ve.id),(0,d.jsx)("div",{style:{display:Ve?"none":void 0},children:(0,d.jsx)(qt.ExpressCheckoutElement,{onReady:se=>q(Hs(se,["paypal"])),onLoadError:()=>{q("load_error"),si(Wt(D),"paypal","paypal")},onClick:ht,onConfirm:Ye,onCancel:()=>{let se=_e.current.get(ae);_e.current.delete(ae),Wt(D)?.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),w(se?.generation),Le(!1),Oe.current=!0,Y()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:ce,emailRequired:ce,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},ae)})]})}),pe&&(0,d.jsx)(jn,{status:"processing"})]})}function zs({sessionId:e,nonce:t,email:n,billingApiUrl:r,intentKind:o,expressMethods:a,onTokenizedBody:l,onErrorChange:c,onButtonClick:y,onDecline:m,onTechnicalFailure:p,runBeforeButtonClick:g,billingName:f,onBuyerIdentityReady:P,onLoadStateChange:A,placeholderBorderRadius:D}){let he=vr(),{emitInstrument:H}=(0,s.useContext)($n),S=(0,qt.useStripe)(),le=(0,qt.useElements)(),[q,pe]=(0,s.useState)("loading");(0,s.useEffect)(()=>{A?.(q)},[q,A]);let[oe,ce]=(0,s.useState)(!1),Ve=(0,s.useRef)(!(0,u.isValidEmail)(n?.trim())||!f?.trim()).current,{request:de,collect:Tt,finish:Ge}=Xr(),Ae=(0,s.useRef)(null),Be=(0,s.useRef)(null),[ae,ie]=(0,s.useState)(0),[O,Le]=(0,s.useState)(!1),[Oe,_e]=(0,s.useState)("google_pay"),ze=(0,s.useRef)(!1),Pe=(0,s.useRef)("google_pay"),w=(0,s.useRef)("google_pay"),ue=(0,s.useRef)(null),be=(0,s.useRef)(new Set);(0,s.useEffect)(()=>()=>{for(let b of be.current)window.clearTimeout(b);be.current.clear()},[]);let Y=(0,s.useRef)(new Map),{startAttempt:L,finishAttempt:Se,invalidateAttempt:rt,isAttemptInvalidated:ht,isAttemptCurrent:Ye,generationRef:se}=Ro((b,tt,Ie)=>{p?.(b,tt,{...Ie,popupBlocked:Ie?.popupBlocked??wr(tt)}),_e(b),Le(!0),ie(z=>z+1)});(0,s.useEffect)(()=>{O&&Be.current?.focus()},[O,ae]);let J=(0,s.useCallback)(()=>{ie(b=>b+1)},[]),j=(0,s.useCallback)((b,tt,Ie,z)=>{rt(z),p?.(b,tt,{code:Ie,popupBlocked:wr(tt)}),_e(b),Le(!0),J()},[rt,p,J]),Ue=(0,s.useCallback)(()=>{window.setTimeout(()=>{(Ae.current?.querySelector("iframe")??Ae.current)?.focus()},0)},[]);(0,s.useEffect)(()=>{ze.current&&(ze.current=!1,Ue())},[Ue,ae]);let Qe=(0,s.useCallback)(()=>{Le(!1),c?.(null),Ue()},[Ue,c]),fe=(0,s.useCallback)(async b=>{let tt=!1,Ie=He=>{tt||(tt=!0,b.paymentFailed({reason:"fail",...He?{message:He}:{}}))};if(!S||!le){Ie();return}let z=Y.current.get(ae);if(z&&!Ye(z.generation)){Y.current.delete(ae),Ie();return}if(!z&&ht()){Ie();return}if(z&&!Se(z.generation)){Ie();return}z||Se();let Fe=b.expressPaymentType??z?.method??Pe.current,Te=z??null,mt=Ds(Fe),yt;Fe==="apple_pay"?yt="apple_pay":Fe==="google_pay"&&(yt="google_pay");let E=z?.generation??se.current,B=Wt(he),bt=B?.now()??globalThis.performance?.now()??Date.now(),Je=new AbortController,Gt=!1,fn=!1,N=null,jt=e,Yt="processing",lt="other",Nt="provider_runtime",gn,In=new Promise((He,ft)=>{gn=ft}),hn=window.setTimeout(()=>{Gt=!0,Je.abort(),gn(ti)},Sc),Lt=async(He,ft,Pt)=>{Yt=He,lt=ft,Nt=ft==="intent_create"?"transport_error":"provider_runtime";let on=B?.now()??globalThis.performance?.now()??Date.now();try{return await Promise.race([Pt,In])}finally{let ct=B?.now()??globalThis.performance?.now()??Date.now();B?.performance({stage:He,durationMs:Math.max(0,ct-on),durationMode:"machine",requestCategory:ft,paymentMethodCategory:"wallet",provider:"stripe",...Gt?{statusClass:"timeout"}:{}})}};try{if(ce(!0),c?.(null),!Te&&g){let k=await Lt("processing","other",g(mt));if(!k.proceed){Ie();return}Te={accountPatch:k.accountPatch,sessionId:k.sessionId,nonce:k.nonce}}let He=Te?.sessionId??e;jt=He;let ft=Te?.nonce??t,Pt=ue.current??Te?.accountPatch,on=js({event:b,fallbackEmail:Pt?.email??n,fallbackName:[Pt?.firstName,Pt?.lastName].join(" ").trim()||f});if(!(0,u.isValidEmail)(on.email)){Ie("Buyer details are required."),Tt(ai(Fe),on).then(k=>{k&&(ue.current=k)});return}ue.current=null;let ct={...Te?.accountPatch,...kn(on,!0)};await Lt("processing","provider_sdk",Promise.resolve(P?.(on)));let{error:bn}=await Lt("tokenization","provider_sdk",le.submit());if(bn){Ie(),j(Fe,bn,"stripe_wallet_submit_failed",z?.generation);return}if(!He)throw new Error("Missing sessionId or email for payment.");let Xe=await Lt("processing","intent_create",ha(r,H,He,ft??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:Fe,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,B?.performance({stage:"callback",durationMs:Math.max(0,(B?.now()??globalThis.performance?.now()??Date.now())-bt),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe"});let vn=B?.now()??globalThis.performance?.now()??Date.now(),an={stage:"provider_confirmation",provider:"stripe",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",...yt?{walletType:yt}:{},attempt:E},Ht=!1;B?.log({name:"payment.provider_confirmation.started",...an}),N=window.setTimeout(()=>{N!==null&&be.current.delete(N),Ht=!0;let k=B?.now()??globalThis.performance?.now()??Date.now();B?.error({errorCode:"REQUEST_TIMEOUT",...an,operationOutcome:"watchdog_expired",checkoutSessionId:He,durationMs:Math.max(0,k-vn),statusClass:"timeout",failureCategory:"provider_runtime"}),B?.flush?.().catch(()=>{})},wc),be.current.add(N);let Ot=k=>{N!==null&&(window.clearTimeout(N),be.current.delete(N),N=null);let gt=B?.now()??globalThis.performance?.now()??Date.now(),Rt=Math.max(0,gt-vn),Et=k;return Ht&&(k==="resolved"?Et="resolved_late":k==="returned_error"?Et="returned_error_late":Et="rejected_late"),B?.log({name:"payment.provider_confirmation.returned",...an,operationOutcome:Et}),B?.performance({...an,durationMs:Rt,durationMode:"buyer",operationOutcome:Et}),{durationMs:Rt,operationOutcome:Et}},en=!1,Xt=k=>{if(!k||typeof k!="object")return null;let gt=k;if(gt.error)return null;let Rt=gt.setupIntent??gt.paymentIntent,Et=Rt?.id,cn=Rt?.status,ur=gt.setupIntent?cn==="succeeded":So(typeof cn=="string"?cn:void 0),Fn=Rt?.payment_method,U=null;return typeof Fn=="string"?U=Fn:typeof Fn?.id=="string"&&(U=Fn.id),!ur||typeof Et!="string"||!U?null:{intentId:Et,paymentMethodId:U}},Rn=k=>{if(en||z&&se.current!==z.generation)return;let gt=Xt(k);if(!gt)return;let{intentId:Rt,paymentMethodId:Et}=gt;en=!0;let cn=`${$s}:${He}`;if(typeof window<"u")try{localStorage.setItem(cn,JSON.stringify({createdAt:Date.now(),sessionId:He,nonce:ft,accountPatch:ct,paymentMethodId:Et,providerIntentId:Rt,paymentMethodType:Fe}))}catch{}try{l({id:Et,type:"card",threeDSecureActionResultTokenId:Rt},{accountPatch:ct,paymentMethodCategory:"wallet",sessionId:He,nonce:ft})}finally{if(typeof window<"u")try{localStorage.removeItem(cn)}catch{}}},xt,sn;try{let k=await((0,u.isSetupIntentClientSecret)(Jt)?S.confirmSetup({elements:le,clientSecret:Jt,redirect:"if_required"}):S.confirmPayment({elements:le,clientSecret:Jt,redirect:"if_required"}));if(!k||typeof k!="object"||(xt=k,!xt.error&&!Xt(xt)))throw ni;sn=Ot(xt.error?"returned_error":"resolved")}catch(k){let gt=k===ni,Rt=Ot(gt?"returned_error":"rejected");throw B?.error({...gt?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response"}:Va(k),...an,operationOutcome:Rt.operationOutcome,checkoutSessionId:He,durationMs:Rt.durationMs,statusClass:"unknown"}),k}let St=xt.error;if(St){if(ko(St)){let k=St.message??"Your payment was declined.";Ie(k),c?.(k),m?.(Qt(mt,k,{code:br(St),declineCode:Qr(St)})),ba({billingApiUrl:r,sessionId:He,nonce:ft,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:Fe,providerDeclineReason:br(St)??"provider_declined",...Xe.intentKind==="payment"&&Xe.providerObjectId.startsWith("pi_")?{providerIntentId:Xe.providerObjectId}:{}}})}else B?.error({...Va(St),...an,operationOutcome:sn.operationOutcome,checkoutSessionId:He,durationMs:sn.durationMs,statusClass:"unknown"}),Ie(),j(Fe,St,"stripe_wallet_confirm_failed",z?.generation);return}if(Rn(xt),!en)throw new Error("Invalid provider returned for APM intent")}catch(He){if(He===ti){let ft=B?.now()??globalThis.performance?.now()??Date.now();B?.error({errorCode:"REQUEST_TIMEOUT",stage:Yt,requestCategory:lt,paymentMethodCategory:"wallet",provider:"stripe",...yt?{walletType:yt}:{},operationOutcome:"watchdog_expired",checkoutSessionId:jt,durationMs:Math.max(0,ft-bt),statusClass:"timeout",failureCategory:Nt,attempt:E}),B?.flush?.().catch(()=>{})}Ie(),j(Fe,He,He===ti?"stripe_wallet_authorization_timeout":"stripe_wallet_failed",z?.generation)}finally{if(window.clearTimeout(hn),N!==null&&(window.clearTimeout(N),be.current.delete(N)),!fn){let He=B?.now()??globalThis.performance?.now()??Date.now();B?.performance({stage:"callback",durationMs:Math.max(0,He-bt),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe",...Gt?{statusClass:"timeout"}:{}})}ce(!1)}},[S,le,e,t,n,f,Tt,P,r,H,o,l,c,m,g,j,Se,Ye,ht,se,he,ae]),ot=(0,s.useMemo)(()=>{let b=["applePay","googlePay","paypal","link","amazonPay","klarna"],tt=new Set(["applePay","googlePay"]),Ie=new Set(a.map(u.stripeExpressMethodToOptionKey)),z={};for(let Fe of b)Ie.has(Fe)?z[Fe]=tt.has(Fe)?"always":"auto":z[Fe]="never";return z},[a]),te=(0,s.useMemo)(()=>a.map(u.stripeExpressMethodToOptionKey),[a]);return(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)(Ks,{state:q,placeholderTestId:"flopay-wallet-placeholder",borderRadius:D,children:(0,d.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:[O&&(0,d.jsxs)("button",{ref:Be,type:"button","data-testid":"flopay-wallet-retry-button",onClick:Qe,style:Vs,children:["Try ",ai(Oe)," again"]}),de&&(0,d.jsx)(Zr,{identity:de.identity,methodLabel:de.methodLabel,onComplete:Ge,onCancel:()=>Ge(null)},de.id),(0,d.jsx)("div",{style:{display:de?"none":void 0},children:(0,d.jsx)(qt.ExpressCheckoutElement,{onReady:b=>{pe(Hs(b,te))},onLoadError:b=>{pe("load_error"),si(Wt(he),"stripe","wallet")},onClick:async b=>{Pe.current=b.expressPaymentType,w.current=Ds(b.expressPaymentType);let tt=!0,Ie=window.setTimeout(()=>{tt=!1,b.reject()},Pc),z=g?await g(w.current):{proceed:!0};if(window.clearTimeout(Ie),!tt)return;if(!z.proceed){Y.current.delete(ae),b.reject();return}let Fe=L(b.expressPaymentType);Y.current.set(ae,{generation:Fe,method:b.expressPaymentType,accountPatch:z.accountPatch,sessionId:z.sessionId,nonce:z.nonce}),Le(!1),y?.(w.current),b.resolve()},onConfirm:fe,onCancel:()=>{let b=Y.current.get(ae);Y.current.delete(ae),Wt(he)?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet"}),rt(b?.generation),Le(!1),ze.current=!0,J()},options:{buttonType:{applePay:"plain",googlePay:"plain"},paymentMethods:ot,emailRequired:Ve,billingAddressRequired:Ve,layout:{maxColumns:1,overflow:"never"}}},ae)})]})}),oe&&(0,d.jsx)(jn,{status:"processing"})]})}function Ws(e,t){return{...e,paymentMethodTypes:[t],...t==="revolut_pay"||t==="sepa_debit"||t==="us_bank_account"?{setupFutureUsage:"off_session"}:null}}function zc({method:e,themeId:t,submitting:n=!1,disabled:r=!1,highlighted:o=!1,hasNextStep:a=!1,onClick:l,backgroundColor:c,borderColor:y,textColor:m,borderRadius:p,fontFamily:g}){let f=(0,u.resolveStripeMethodBrandVariant)(e,t),P=Cs[e],[A,D]=(0,s.useState)(!1),he=!!P&&!A,H=f?.backgroundColor??c??"#ffffff",S=f?.borderColor??y??"#d1d5db",le=f?.textColor??m??"#262833";return(0,d.jsx)("button",{type:"button","data-testid":`flopay-stripe-method-button-${e}`,"data-method":e,onClick:()=>{!n&&!r&&l()},disabled:n||r,"aria-busy":n||void 0,style:{position:"relative",width:"100%",boxSizing:"border-box",height:ga,padding:"0 1rem",backgroundColor:H,color:le,border:`1px solid ${S}`,borderRadius:p??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,d.jsx)("span",{style:{margin:"0 auto"},children:`Connecting to ${(0,u.getStripeMethodDisplayName)(e)}\u2026`}):(0,d.jsxs)(d.Fragment,{children:[(0,d.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:(0,u.hasVendoredStripeMethodLogo)(e)?8:0},children:[he?(0,d.jsx)("img",{src:P,alt:"","aria-hidden":"true",onError:()=>D(!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&&f?.logoSvg?(0,d.jsx)("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:f.logoSvg}}):null,(0,d.jsx)("span",{children:(0,u.getStripeMethodDisplayName)(e)})]}),a&&(0,d.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:le,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,d.jsx)("path",{d:"M9 18l6-6-6-6"})})]})})}function ii({method:e,sessionId:t,nonce:n,email:r,billingName:o,onBuyerIdentityReady:a,billingApiUrl:l,onTokenizedBody:c,onErrorChange:y,onDecline:m,onCancel:p,runBeforeButtonClick:g,onButtonClick:f,isProcessing:P,submitButtonColor:A,submitButtonBorderRadius:D,submitButtonStyle:he,errorText:H}){let S=vr(),{emitInstrument:le}=(0,s.useContext)($n),q=(0,qt.useStripe)(),pe=(0,qt.useElements)(),[oe,ce]=(0,s.useState)(!1),Ve=(0,s.useRef)(!1),[de,Tt]=(0,s.useState)(!1),[Ge,Ae]=(0,s.useState)("loading"),[Be,ae]=(0,s.useState)(""),ie=!(0,u.isValidEmail)(r?.trim()),O=!ie||(0,u.isValidEmail)(Be.trim()),Le=(0,s.useCallback)(async()=>{if(!q||!pe||P||Ve.current||!de)return;Ve.current=!0,ce(!0);let Oe=g?await g("card"):{proceed:!0};if(!Oe.proceed){Ve.current=!1,ce(!1);return}f?.("card");let _e=Oe.sessionId??t,ze=Oe.nonce??n,Pe=xr(o?.trim()),w=kn({email:Oe.accountPatch?.email?.trim()||r?.trim()||Be.trim(),firstName:Oe.accountPatch?.firstName?.trim()||Pe.firstName,lastName:Oe.accountPatch?.lastName?.trim()||Pe.lastName}),ue=w.email,be=kn({...Oe.accountPatch,...w});try{if(y?.(null),!(0,u.isValidEmail)(ue))throw new Error("A valid email address is required for payment.");await a?.(w);let Y=await pe.submit();if(Y.error){y?.(Y.error.message??"Payment failed.");return}let L=[w.firstName,w.lastName].filter(Boolean).join(" "),Se=await q.createPaymentMethod({elements:pe,params:{billing_details:{email:ue,...L?{name:L}:{}}}});if(Se.error||!Se.paymentMethod){y?.(Se.error?.message??"Failed to create payment method.");return}let rt=Se.paymentMethod;if(!_e||!ue)throw new Error("Missing sessionId or email for payment.");let ht=rt.type||e,Ye=await ha(l,le,_e,ze??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:ht,paymentMethodId:null,intentKind:"payment"});if(Ye.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let se=Ye.clientSecret;if(typeof window<"u")try{localStorage.setItem(lr,JSON.stringify({clientSecret:se,sessionId:_e,nonce:ze,accountPatch:be,paymentMethodId:rt.id,paymentMethodType:rt.type??e,gateway:"stripe"}))}catch{}let{error:J,paymentIntent:j}=await q.confirmPayment({clientSecret:se,confirmParams:{return_url:window.location.href,payment_method:rt.id},redirect:"if_required"});if(J){if(typeof window<"u")try{localStorage.removeItem(lr)}catch{}let fe=J.message??"Payment failed.";y?.(fe),m?.(Qt("card",fe,{code:J.code})),await ba({billingApiUrl:l,sessionId:_e,nonce:ze,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:J.code??"provider_declined"}});return}let Ue=j?.status;if(!So(Ue)){if(typeof window<"u")try{localStorage.removeItem(lr)}catch{}let fe=Ue==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";y?.(fe),m?.(Qt("card",fe,{code:Ue??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(lr)}catch{}let Qe=typeof j?.payment_method=="string"?j.payment_method:j?.payment_method?.id;c({id:Qe??rt.id,type:"card",threeDSecureActionResultTokenId:j?.id,gateway:"stripe",paymentMethodType:rt.type??e},{accountPatch:be,paymentMethodCategory:"apm",sessionId:_e,nonce:ze})}catch(Y){y?.(Y instanceof Error?Y.message:"Payment failed. Please try again.")}finally{Ve.current=!1,ce(!1)}},[q,pe,P,de,g,f,t,n,r,o,Be,a,l,le,e,c,y,m]);return(0,d.jsxs)("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[ie&&(0,d.jsx)("div",{"data-testid":"flopay-apm-identity-fields",style:{display:"flex",flexDirection:"column",gap:"0.75rem",marginBottom:"0.75rem"},children:ie&&(0,d.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",(0,d.jsx)("input",{type:"email",autoComplete:"email",required:!0,value:Be,onChange:Oe=>ae(Oe.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]})}),(0,d.jsx)(qt.PaymentElement,{onReady:()=>Ae("ready"),onLoadError:()=>{Ae("load_error"),si(Wt(S),"stripe","apm")},onChange:Oe=>{Tt(!!Oe.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,d.jsx)("button",{type:"button","data-testid":`flopay-stripe-method-pay-${e}`,onClick:()=>{Le()},disabled:!de||!O||oe||P||Ge!=="ready",style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:A,color:"white",border:"none",borderRadius:D,fontSize:"1rem",fontWeight:600,cursor:!de||!O||oe||P||Ge!=="ready"?"not-allowed":"pointer",opacity:!de||!O||oe||P||Ge!=="ready"?.5:1,transition:"opacity 120ms ease-out",...he??{}},children:oe?"Processing\u2026":`Pay with ${(0,u.getStripeMethodDisplayName)(e)}`}),H&&(0,d.jsx)(to,{margin:"0.75rem 0 0",children:H})]})}function Us({sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:a,paymentElementMethods:l,stripeInstance:c,paymentElementBaseOptions:y,onTokenizedBody:m,onErrorChange:p,onButtonClick:g,onDecline:f,runBeforeButtonClick:P,onLoadStateChange:A,isProcessing:D=!1,submitButtonColor:he="#4A49FF",submitButtonBorderRadius:H=8,submitButtonStyle:S,buttonAppearance:le,themeId:q,onExpandApm:pe,expandedApmMethod:oe}){let{emitInstrument:ce}=(0,s.useContext)($n),[Ve,de]=(0,s.useState)(null),[Tt,Ge]=(0,s.useState)(null),Ae=(0,s.useRef)(!1),{request:Be,collect:ae,finish:ie}=Xr();(0,s.useEffect)(()=>{l.length>0&&c?A?.("ready"):c||A?.("loading")},[l.length,c,A]);let O=(0,s.useCallback)(async w=>{if(!c||Ae.current||D)return;Ae.current=!0,Ge(w);let ue=P?await P("card"):{proceed:!0};if(!ue.proceed){Ae.current=!1,Ge(null);return}g?.("card");let be=ue.sessionId??e,Y=ue.nonce??t,L=xr([ue.accountPatch?.firstName,ue.accountPatch?.lastName].filter(Boolean).join(" ")||r),Se=kn({email:ue.accountPatch?.email?.trim()||n?.trim(),firstName:ue.accountPatch?.firstName?.trim()||L.firstName,lastName:ue.accountPatch?.lastName?.trim()||L.lastName});if(!(0,u.isValidEmail)(Se.email)){Ge(null);let Ye=await ae((0,u.getStripeMethodDisplayName)(w),Se);if(!Ye){Ae.current=!1;return}Se=Ye,Ge(w)}let rt=Se.email,ht=kn({...ue.accountPatch,...Se});try{if(p?.(null),!be||!(0,u.isValidEmail)(rt))throw new Error("Missing sessionId or email for payment.");await o?.(Se);let Ye=await ha(a,ce,be,Y??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:w,paymentMethodId:null,intentKind:"payment"});if(Ye.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let se=Ye.clientSecret;if(typeof window<"u")try{localStorage.setItem(lr,JSON.stringify({clientSecret:se,sessionId:be,nonce:Y,accountPatch:ht,paymentMethodType:w,gateway:"stripe"}))}catch{}let{error:J,paymentIntent:j}=await c.confirmPayment({clientSecret:se,confirmParams:{return_url:window.location.href,payment_method_data:{type:w,billing_details:{name:[Se.firstName,Se.lastName].filter(Boolean).join(" "),...rt?{email:rt}:{}}}},redirect:"if_required"});if(J){if(typeof window<"u")try{localStorage.removeItem(lr)}catch{}let fe=J.message??"Payment failed.";p?.(fe),f?.(Qt("card",fe,{code:J.code})),await ba({billingApiUrl:a,sessionId:be,nonce:Y,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:w,providerDeclineReason:J.code??"provider_declined"}});return}let Ue=j?.status;if(!So(Ue)){if(typeof window<"u")try{localStorage.removeItem(lr)}catch{}let fe=Ue==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";p?.(fe),f?.(Qt("card",fe,{code:Ue??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(lr)}catch{}let Qe=typeof j?.payment_method=="string"?j.payment_method:j?.payment_method?.id;m({id:Qe??j?.id,type:"card",threeDSecureActionResultTokenId:j?.id,gateway:"stripe",paymentMethodType:w},{accountPatch:ht,paymentMethodCategory:"apm",sessionId:be,nonce:Y})}catch(Ye){p?.(Ye instanceof Error?Ye.message:"Payment failed. Please try again.")}finally{Ae.current=!1,Ge(null)}},[c,D,P,g,e,t,n,ae,a,ce,r,o,m,p,f]),[Le,Oe]=(0,s.useState)(null),_e=pe?oe??null:Le,ze=(0,s.useCallback)(w=>{Ae.current||D||_e&&_e!==w||((0,u.needsStripeMethodExplicitConfirm)(w)?pe?pe(w):Oe(w):O(w))},[_e,D,O,pe]),Pe=(0,s.useMemo)(()=>Le?Ws(y,Le):null,[Le,y]);return(0,d.jsx)("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:Be?(0,d.jsx)(Zr,{identity:Be.identity,methodLabel:Be.methodLabel,onComplete:ie,onCancel:()=>ie(null)},Be.id):l.map(w=>{let ue=oe===w,be=Tt===w,Y=Tt!==null&&Tt!==w||oe!=null&&oe!==w;return(0,d.jsxs)(s.default.Fragment,{children:[(0,d.jsx)(zc,{method:w,themeId:q,submitting:be,disabled:Y,highlighted:ue,hasNextStep:(0,u.needsStripeMethodExplicitConfirm)(w),onClick:()=>ze(w),backgroundColor:le?.backgroundColor,borderColor:le?.borderColor,textColor:le?.textColor,borderRadius:le?.borderRadius,fontFamily:le?.fontFamily}),!pe&&Le===w&&Pe&&c&&(0,d.jsx)(qt.Elements,{stripe:c,options:Pe,children:(0,d.jsx)(ii,{method:w,sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:a,onTokenizedBody:m,onErrorChange:p,onDecline:f,onCancel:()=>Oe(null),runBeforeButtonClick:P,onButtonClick:g,isProcessing:D,submitButtonColor:he,submitButtonBorderRadius:H,submitButtonStyle:S})},w)]},w)})})}function Uc({sessionId:e,nonce:t,billingApiUrl:n,email:r,userId:o,onComplete:a,onError:l,onDecline:c,onTokenizedBody:y,firstName:m,lastName:p,chv:g,className:f,isProcessing:P,error:A,onErrorChange:D,showPayPal:he=!0,showStripe:H=!0,enabledPaymentMethods:S,enabledPaymentMethodCountries:le,showApplePay:q=!0,showGooglePay:pe=!0,layout:oe="default",theme:ce,buttonsTheme:Ve,buttonsStyles:de,appearance:Tt,cardButtonContent:Ge,cardBackButtonContent:Ae,cardTitleContent:Be,showSecurityFooter:ae,onButtonClick:ie,onBeforeButtonClick:O,onBuyerIdentityReady:Le,enableAVS:Oe,cardFieldOrder:_e,cardPreFormSlot:ze,avsLayout:Pe="row",country:w,zip:ue,addressLine1:be,addressLine2:Y,city:L,state:Se,onCountryChange:rt,onZipChange:ht,avsCheck:Ye,checkoutType:se,checkoutLayout:J,totalAmount:j=0,currency:Ue="usd",initialCardOpen:Qe=!1,directPaypal:fe,isSubscription:ot=!1,session:te,dataAttachmentPending:b=!1,dataAttachmentRequiresIdentity:tt=!1,debug:Ie=!1}){let z=vr(),Fe=Qo(),Te=(0,s.useContext)(tr),{emitInstrument:mt}=(0,s.useContext)($n),yt=te??Te.session,E=yt?.gateways?.paypal?.providerObjectType??fe?.providerObjectType,B=b||Te.claimPending===!0,bt=tt||Te.claimRequiresIdentity===!0,Je=B&&!bt,Gt=os(),[fn,N]=(0,s.useState)(!1),[jt,Yt]=(0,s.useState)(null),[lt,Nt]=(0,s.useState)(w??"US"),[gn,In]=(0,s.useState)(ue??""),[hn,Lt]=(0,s.useState)(be??""),[He,ft]=(0,s.useState)(Y??""),[Pt,on]=(0,s.useState)(L??""),[ct,bn]=(0,s.useState)(Se??""),[Xe,Jt]=(0,s.useState)(""),[vn,an]=(0,s.useState)({}),Ht=(0,s.useRef)(ue??""),Ot=(0,s.useRef)(w??"US"),en=(0,s.useRef)(be??""),Xt=(0,s.useRef)(Y??""),Rn=(0,s.useRef)(L??""),xt=(0,s.useRef)(Se??""),sn=(0,s.useRef)(""),St=(0,s.useRef)({});(0,s.useEffect)(()=>{let i=(C,G,Ne,Q,Ce)=>{if(St.current[C])return;let ke=G?.trim();!ke||ke===Ne.current||(Ne.current=ke,Q(ke),Ce?.(ke))};i("country",w,Ot,Nt,rt),i("zip",ue,Ht,In,ht),i("addressLine1",be,en,Lt),i("addressLine2",Y,Xt,ft),i("city",L,Rn,on),i("state",Se,xt,bn)},[w,ue,be,Y,L,Se,rt,ht]);let k=(0,s.useMemo)(()=>(0,u.resolveAVSConfig)(Oe),[Oe]),gt=k!==null,Rt=(0,s.useMemo)(()=>(0,u.isAuthorizationOnlySession)(te),[te]),Et=!!te?.vault?.html,cn=!!te?.gateways?.pcivault,Fn=!!(te?.gateways?.stripe?.enabledPaymentMethods??S)?.includes("card"),U=Et||Fn||cn,we=!!(H&&U&&z&&e),[tn,dn]=(0,s.useState)(()=>oe!=="buttons"||Qe?e??null:null),[Re,Kn]=(0,s.useState)(0),Dn=oe!=="buttons"||Qe||!!e&&tn===e,zt=(0,s.useMemo)(()=>!z||!we||!e||!Dn?null:z.cardCapture({sessionId:e,captureMethod:te?.captureMethod}),[z,we,e,Dn,te?.captureMethod]),un=(0,s.useMemo)(()=>{let i=lt,C=k?(0,u.isAVSFieldVisible)(k.postal_code,i):!1;return Nc(i,gn,C)},[k,lt,gn]),{avsInvalid:Ir,invalidAvsFields:Rr}=(0,s.useMemo)(()=>{let i={line1:!1,city:!1,state:!1,zip:!1};if(!we||!k)return{avsInvalid:!1,invalidAvsFields:i};let C=lt,G=(Ce,ke)=>(0,u.isAVSFieldVisible)(Ce,C)&&!ke.trim(),Ne={line1:G(k.address_line_1,hn),city:G(k.city,Pt),state:G(k.state,ct),zip:un.empty||un.malformed};return{avsInvalid:Ne.line1||Ne.city||Ne.state||Ne.zip,invalidAvsFields:Ne}},[we,k,lt,hn,Pt,ct,un]),[En,pr]=(0,s.useState)(!1),[Wn,Nn]=(0,s.useState)(!1),[wt,or]=(0,s.useState)(!1),[_n,Gn]=(0,s.useState)({line1:!1,city:!1,state:!1}),Cn=(0,s.useRef)(!1),Yn=(0,s.useRef)({email:!1,line1:!1,city:!1,state:!1,zip:!1}),Jn=(0,s.useRef)(!1),dt=(0,s.useCallback)(i=>{Yn.current[i]=!0,Jn.current=!0},[]),Tn=(0,s.useCallback)(i=>!Cn.current&&Yn.current[i],[]),Ln=(0,s.useCallback)(i=>{Tn(i)&&Gn(C=>C[i]?C:{...C,[i]:!0})},[Tn]),[xn,Xn]=(0,s.useState)(()=>ri(te?.vault)),[$e,pn]=(0,s.useState)(Qe&&U?"card":"buttons"),[Mt,mr]=(0,s.useState)(null),yr=$e==="expanding"||$e==="card",fr=te?.gateways?.stripe?"stripe":void 0,Mn=(0,s.useCallback)(()=>{mt?.({class:"card_surface",provider:fr})},[fr,mt]),Zn=(0,s.useRef)(null),Kt=(0,s.useCallback)(i=>{Zn.current&&clearTimeout(Zn.current),Zn.current=setTimeout(()=>{Zn.current=null,i()},No)},[]);(0,s.useEffect)(()=>()=>{Zn.current&&clearTimeout(Zn.current)},[]);let $=(0,s.useCallback)(()=>{Mn(),dn(e??null),Kn(i=>i+1),pn("expanding"),Kt(()=>pn("card"))},[Kt,Mn,e]),V=(0,s.useCallback)(()=>{pn("collapsing"),Kt(()=>pn("buttons"))},[Kt]),ne=(0,s.useCallback)(i=>{mr(i),pn("apm-expanding"),Kt(()=>pn("apm-form"))},[Kt]),re=(0,s.useCallback)(()=>{pn("apm-collapsing"),Kt(()=>{pn("buttons"),mr(null)})},[Kt]);(0,s.useEffect)(()=>{oe==="buttons"&&Qe&&U&&(dn(e??null),pn("card"))},[oe,Qe,U,e]);let[Ke,ee]=(0,s.useState)(null),X=(0,s.useRef)(!1),_=(0,s.useRef)(null),F=(0,s.useRef)("idle"),[Z,vt]=(0,s.useState)(null),et=(0,s.useRef)(Z);(0,s.useEffect)(()=>{et.current=Z},[Z]);let me=n||Gt,at=(0,s.useRef)(null),x=(0,s.useMemo)(()=>{if(Le||Te.claimBuyerIdentity||te?.buyerIdentified!==!1||!e||!t)return;let i=`${me}|${e}|${t}`;at.current?.key!==i&&(at.current={key:i,claim:Yr(new Pr.PaymentAPI(me,{telemetry:!1}),e,t,{...o?{userId:o}:{},...m?{firstName:m}:{},...p?{lastName:p}:{}})});let C=at.current.claim;return async G=>{await C(G)}},[Le,Te.claimBuyerIdentity,te?.buyerIdentified,e,t,me,o,m,p]),h=Le??Te.claimBuyerIdentity??x,M=A??jt,K=(0,s.useMemo)(()=>(0,u.resolveTheme)(ce),[ce]),v=(0,s.useMemo)(()=>{let i=K?.buttonsLayout??(0,u.resolveButtonsLayoutTheme)(Ve);return de?{...i,...de,cardButton:{...i.cardButton,...de.cardButton},cardFormContainer:{...i.cardFormContainer,...de.cardFormContainer},backButton:{...i.backButton,...de.backButton},backButtonIcon:{...i.backButtonIcon,...de.backButtonIcon},submitButton:{...i.submitButton,...de.submitButton},title:{...i.title,...de.title}}:i},[K,Ve,de]),W=Tt??K?.appearance,We=(0,s.useMemo)(()=>fa({appearance:W,buttonsStyles:v,layout:oe}),[W,v,oe]),ln=Te.inlineSessionPatchProcessing??!1,it=(P??fn)||ln,st=me.replace(/\/+$/,""),ye=(0,s.useMemo)(()=>ja({userId:o,email:r,firstName:m,lastName:p,country:w,zip:ue},vn),[o,r,m,p,w,ue,vn]),ve=[ye.firstName,ye.lastName].filter(i=>!!i?.trim()).join(" "),Ze=!(0,u.isValidEmail)(ye.email?.trim()),De=(0,s.useRef)(null);we&&De.current===null&&(De.current=Ze);let Ee=we&&(De.current??Ze),Ct=(0,s.useMemo)(()=>Lc(Xe,Ee),[Xe,Ee]),nn=Ct.empty||Ct.malformed,xe=(0,s.useMemo)(()=>z?z.getRawProvider():null,[z]),Pn=(0,s.useMemo)(()=>Fe?Fe.getRawProvider():null,[Fe]),On=j||100,Or=Ue.toLowerCase(),Ra=(0,s.useMemo)(()=>W?(0,Pr.toStripeAppearance)(W):null,[W]),zr=Ra,gi=(0,s.useMemo)(()=>{let i=Ra??{},C=i.rules??{};return{...i,rules:{...C,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...C[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...C[".AccordionItemContents"]??{}}}}},[Ra]),hi=(0,s.useMemo)(()=>({...es(j,te?.captureMethod),currency:Or,...zr?{appearance:zr}:null}),[j,Or,te?.captureMethod,zr]),bi=(0,s.useMemo)(()=>({mode:"payment",amount:On,currency:Or,captureMethod:"manual",setupFutureUsage:"off_session",...zr?{appearance:zr}:null}),[On,Or,zr]),ge=(0,s.useCallback)(i=>{Yt(i),D?.(i)},[D]),Ea=(0,s.useRef)(""),[vi,al]=(0,s.useState)(!1),_a=(0,s.useCallback)(()=>{al(!0)},[]);(0,s.useEffect)(()=>{if(!we||!Ee||!h||!vi||nn||Ea.current)return;let i=kn({email:(0,u.isValidEmail)(ye.email?.trim())?ye.email?.trim():sn.current.trim(),firstName:ye.firstName?.trim(),lastName:ye.lastName?.trim()});Ea.current=JSON.stringify(i),an(C=>({...C,...i})),Promise.resolve(h(i)).catch(C=>{Ea.current="",ge(C instanceof Error?C.message:"Failed to attach buyer details.")})},[we,Ee,h,vi,nn,ye.email,ye.firstName,ye.lastName,ge]),(0,s.useEffect)(()=>{!we||!zt||zt.setCardFieldOrder?.(_e??null,k==null&&!Ee)},[we,zt,_e,k,Ee]),(0,s.useEffect)(()=>{($e==="expanding"||$e==="collapsing"||$e==="apm-expanding"||$e==="apm-collapsing")&&ge(null)},[$e,ge]);let Qn=(0,s.useCallback)((i,C,G)=>{c?.(Qt(i,C,G))},[c]),Ur=(0,s.useCallback)((i,C,G)=>{let Ne=G?.popupBlocked??wr(C),Q=Fc(i,Ne),Ce=Ar(G?.code)??br(C)??"external_payment_method_failed",ke=new u.FloPayError(Q,"api_error",{code:"external_payment_method_failed",param:i});ee(null),oe==="buttons"&&(pn("buttons"),mr(null)),ge(Q),l?.(ke),console.error("[FloPay] External payment method failed:",{method:i,code:Ce,popupBlocked:Ne})},[oe,l,ge]);(0,s.useEffect)(()=>{if(!we||!e){Xn(null);return}let i=ri(te?.vault);if(i){Xn(i);return}if(!Dn){Xn(null);return}Xn(null);let C=!0;return new Pr.PaymentAPI(st).getVaultCapture(e,t).then(G=>{if(!C)return;let Ne=ri(G);Ne?Xn(Ne):ge("Failed to load the secure card form.")}).catch(G=>{C&&ge(G instanceof Error?G.message:"Failed to load the secure card form.")}),()=>{C=!1}},[we,Dn,Re,e,te?.vault,st,t,ge]);let ar=(0,s.useRef)({onComplete:a,onError:l,updateError:ge,emitDecline:Qn,resolvedAccount:ye,avsConfig:k,avsCheckProp:Ye,sessionId:e,nonce:t,baseUrl:st,captureMethod:te?.captureMethod,paymentId:te?.paymentId,authorizationExpiresAt:te?.authorizationExpiresAt});ar.current={onComplete:a,onError:l,updateError:ge,emitDecline:Qn,resolvedAccount:ye,avsConfig:k,avsCheckProp:Ye,sessionId:e,nonce:t,baseUrl:st,captureMethod:te?.captureMethod,paymentId:te?.paymentId,authorizationExpiresAt:te?.authorizationExpiresAt};let Ta=(0,s.useRef)(!1),Ci=(0,s.useCallback)(()=>{let i=ar.current,C=i.resolvedAccount.email?.trim(),G=(0,u.isValidEmail)(C)?C:sn.current.trim();if(!(0,u.isValidEmail)(G))return null;let Ne=i.resolvedAccount.firstName?.trim(),Q=i.resolvedAccount.lastName?.trim(),Ce=Ot.current||i.resolvedAccount.country||"US",ke=i.avsConfig?(0,u.isAVSFieldVisible)(i.avsConfig.state,Ce):!1,kt=i.avsConfig?(0,u.isAVSFieldVisible)(i.avsConfig.address_line_1,Ce):!1,Bt=i.avsConfig?(0,u.isAVSFieldVisible)(i.avsConfig.postal_code,Ce):!1,Ft=i.avsConfig?(0,u.isAVSFieldVisible)(i.avsConfig.city,Ce):!1,Zt=i.avsConfig?(0,u.isAVSFieldVisible)(i.avsConfig.address_line_2,Ce):!1,It=kt&&!ke&&Bt?(0,u.getStateFromPostalCode)(Ce,(Ht.current??"").trim()):null,gr=ke?xt.current:It;return{accountData:{userId:i.resolvedAccount.userId??"",email:G,...Ne?{firstName:Ne}:{},...Q?{lastName:Q}:{},...Bt&&Ht.current?{zip:Ht.current}:{},...Ft&&Rn.current?{city:Rn.current}:{},...gr?{state:gr}:{},...kt&&en.current?{addressLine1:en.current}:{},...Zt&&Xt.current?{addressLine2:Xt.current}:{},country:Ce},...i.avsCheckProp===void 0?{}:{avsCheck:i.avsCheckProp},...i.avsConfig?{avsConfig:{country:(0,u.isAVSFieldVisible)(i.avsConfig.country,Ce),postal_code:Bt,address_line_1:kt,address_line_2:Zt,city:Ft,state:ke}}:{}}},[]),Pi=(0,s.useRef)(B);Pi.current=B,(0,s.useEffect)(()=>{B||M!==As||ar.current.updateError(null)},[B,M]),(0,s.useEffect)(()=>{!we||!zt||zt.setSubmitGate?.(Ir||B||nn)},[we,zt,Ir,B,nn]),(0,s.useEffect)(()=>{if(!we||!zt)return;Ta.current=!1;let i=!1,C=zt.on("submitting",()=>{pr(!0),_.current&&clearTimeout(_.current),F.current="validation-window",_.current=setTimeout(()=>{_.current=null,F.current==="validation-window"&&(F.current="processing")},kc),ee("processing");let ke=ar.current;if(!ke.sessionId||!ke.nonce)return;let kt=Ci();if(!kt){ke.updateError("Enter a valid email address."),F.current="idle",ee(null);return}new Pr.PaymentAPI(ke.baseUrl).patchAccountSnapshot(ke.sessionId,ke.nonce,kt,{telemetryMode:"best_effort"}).catch(Bt=>{if(!Ic(Bt))return;let Ft=Bt instanceof Error?Bt.message:"Please check your billing address and try again.";ke.updateError(Ft),F.current="idle",ee(null),ke.onError?.(Bt instanceof u.FloPayError?Bt:new u.FloPayError(Ft,"api_error"))})}),G=zt.on("complete",async ke=>{if(oo(ke.sessionId??ar.current.sessionId),F.current="terminal",ee("success"),await new Promise(Ft=>setTimeout(Ft,1200)),Ta.current)return;Ta.current=!0;let kt=ar.current,Bt=(0,u.isAuthorizationOnlySession)(kt)||ke.outcome==="authorized";ar.current.onComplete?.(Bt?{status:"authorized",paymentIntentId:ke.intentId,paymentId:ke.paymentId??kt.paymentId,sessionId:ke.sessionId??kt.sessionId,authorizationExpiresAt:ke.authorizationExpiresAt??kt.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",paymentIntentId:ke.intentId,checkoutMethod:"card"})}),Ne=zt.on("decline",async ke=>{let kt=ar.current,Bt=ke.message??"Your payment was declined. Please try another card or contact your bank.";F.current="terminal",kt.updateError(Bt),ee("error");let Ft=ke.failureOutcome??(0,u.normalizeCheckoutFailureOutcome)(ke.declineReason)??"authorization_declined";kt.emitDecline("card",Bt,{code:Ft,declineCode:Ft}),await new Promise(Zt=>setTimeout(Zt,1500)),!i&&(F.current="idle",ee(null))}),Q=zt.on("error",async ke=>{let kt=ar.current,Bt=ke.message??"There was a problem processing your payment. Please try again.";F.current="terminal",kt.updateError(Bt),ee("error"),kt.onError?.(new u.FloPayError(Bt,"api_error",{code:ke.failureOutcome??"capture_failed"})),await new Promise(Ft=>setTimeout(Ft,1500)),!i&&(F.current="idle",ee(null))}),Ce=zt.on("blocked",()=>{if(!Pi.current){pr(!0);return}_a(),ar.current.updateError(As)});return()=>{i=!0,_.current&&(clearTimeout(_.current),_.current=null),F.current="idle",C(),G(),Ne(),Q(),Ce()}},[we,zt,_a,Ci]);let ir=!!fe?.clientId,co=Array.isArray(S),Uo=co&&S.length>0,il=co&&S.includes("paypal"),{expressMethods:$o,paymentElementMethods:uo}=(0,s.useMemo)(()=>(0,u.partitionStripeMethods)(S,{excludePaypal:ir}),[S,ir]),Si=ir||!!Fe,sl=(0,s.useMemo)(()=>Si?$o.filter(i=>i!=="paypal"):$o,[$o,Si]),ll=(0,s.useMemo)(()=>{let i=[];return q&&i.push("apple_pay"),pe&&i.push("google_pay"),i},[q,pe]),$r=co?sl:ll,cl=H&&$r.length>0,xa=gt?lt:w,qo=(0,s.useMemo)(()=>{let i=xa?.trim().toUpperCase();return i?le?uo.filter(C=>{let G=le[C];return!G||G.length===0||G.includes(i)}):(0,u.filterStripeMethodsByCountry)(uo,xa):uo},[uo,xa,le]),Ma=(0,s.useMemo)(()=>({mode:"payment",amount:On,currency:Or,paymentMethodCreation:"manual",appearance:gi}),[On,Or,gi]),[wi,ki]=(0,s.useState)("loading"),[Ii,Ri]=(0,s.useState)("loading"),[Ei,_i]=(0,s.useState)("loading"),[dl,Aa]=(0,s.useState)(!1),[Ti,Ba]=(0,s.useState)("loading"),[jo,ul]=(0,s.useState)();(0,s.useEffect)(()=>{ul(vs())},[]);let xi=he&&(ir||(co?il:jo===!1)),Mi=H&&cl,po=!Je&&xi&&ir,Ai=Ti==="retrying"||Ti==="exhausted",mo=!Je&&xi&&!!Pn&&(!ir||Ai),qr=!Je&&Mi&&!!xe,yo=!Je&&H&&Uo&&qo.length>0&&!!xe,pl=po&&!Ai?dl:mo&&Ls(wi),ml=qr&&Ls(Ii),yl=yo&&Ei!=="load_error",Bi=i=>i==="loading"||i==="ready",Fi=po||mo&&Bi(wi)||qr&&Bi(Ii)||yo&&Ei!=="load_error",Vo=(0,s.useRef)(!1);(0,s.useEffect)(()=>{if(!Vo.current){if(!H&&!he){Vo.current=!0;let i=new u.FloPayError("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");l?.(i),ge(i.message)}else if(!H&&he&&!ir&&!Pn){Vo.current=!0;let i=new u.FloPayError("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");l?.(i),ge(i.message)}else if(jo!==void 0&&!Je&&!U&&!Fi){Vo.current=!0;let i=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"});l?.(i),ge(i.message)}}},[H,he,ir,Pn,jo,Je,U,Fi,l,ge]);let Di=(0,s.useRef)(!1);(0,s.useEffect)(()=>{if(Di.current||!Uo)return;let i=[];q!==!0&&i.push("showApplePay"),pe!==!0&&i.push("showGooglePay"),i.length!==0&&(Di.current=!0,console.warn(`[FloPay] ${i.join(" / ")} ${i.length===1?"is":"are"} deprecated: the Apple Pay / Google Pay surface is now driven by \`gateways.stripe.enabledPaymentMethods\` on the session response. Remove the legacy prop(s) to silence this warning.`))},[Uo,q,pe]);let Ni=(0,s.useCallback)((i,C)=>Te.applyInlineSessionPatch?Te.applyInlineSessionPatch(i).then(G=>({error:null,sessionId:G.sessionId||e,nonce:G.session?.clientSecret||t})).catch(G=>{let Ne=Ns(C,G);return ge(Ne.message),l?.(Ne),{error:Ne,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[Te.applyInlineSessionPatch,t,l,e,ge]),er=(0,s.useCallback)(async i=>{if(!O)return{proceed:!0};try{let C=await O({method:i,sessionId:e||void 0,createSession:Te.inlineSessionDraft});if(C===!1)return{proceed:!1};if(C&&typeof C=="object"){C.account&&an(Ne=>({...Ne??{},...C.account}));let G=await Ni(C,i);return G.error?{proceed:!1,accountPatch:C.account}:{proceed:!0,accountPatch:C.account,sessionId:G.sessionId,nonce:G.nonce}}return{proceed:!0}}catch(C){let G=Ns(i,C);return ge(G.message),l?.(G),{proceed:!1}}},[Ni,Te.inlineSessionDraft,O,l,e,ge]),Li=(0,s.useCallback)(async(i,C)=>{if(X.current)return;X.current=!0,N(!0),ee("processing"),ge(null);let G=C?.sessionId??e,Ne=C?.nonce??t,Q=ja(ye,C?.accountPatch),Ce=C?.completionPaymentMethodId??wo(i),ke=i.originalPaymentMethodId?{...i,originalPaymentMethodId:void 0}:i,kt=xc(i),Bt=()=>{mt?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"process_payment",provider:kt})};try{let Zt=await new Pr.PaymentAPI(st).processPayment(Q.userId??"",{sessionId:G,nonce:Ne,paymentMethodCategory:C?.paymentMethodCategory??Ac(i),tokenizedData:ke,accountData:{...C?.accountPatch,userId:Q.userId??"",email:Q.email??"",firstName:Q.firstName||void 0,lastName:Q.lastName||void 0,...k?(()=>{let ut=Ot.current,Un=(0,u.isAVSFieldVisible)(k.state,ut),mn=(0,u.isAVSFieldVisible)(k.address_line_1,ut),Dt=(0,u.isAVSFieldVisible)(k.postal_code,ut),Tr=mn&&!Un&&Dt?(0,u.getStateFromPostalCode)(ut,(Ht.current??"").trim()):null,Co=Un?xt.current:Tr;return{country:ut,...Dt&&Ht.current?{zip:Ht.current}:{},...(0,u.isAVSFieldVisible)(k.city,ut)&&Rn.current?{city:Rn.current}:{},...Co?{state:Co}:{},...mn&&en.current?{addressLine1:en.current}:{},...(0,u.isAVSFieldVisible)(k.address_line_2,ut)&&Xt.current?{addressLine2:Xt.current}:{}}})():{}},chv:g,avsCheck:Ye??!1,checkoutType:se,checkoutLayout:J,avsConfig:k?{country:(0,u.isAVSFieldVisible)(k.country,Ot.current),postal_code:(0,u.isAVSFieldVisible)(k.postal_code,Ot.current),address_line_1:(0,u.isAVSFieldVisible)(k.address_line_1,Ot.current),address_line_2:(0,u.isAVSFieldVisible)(k.address_line_2,Ot.current),city:(0,u.isAVSFieldVisible)(k.city,Ot.current),state:(0,u.isAVSFieldVisible)(k.state,Ot.current)}:void 0});if(Zt.ok){let ut=Zt.status===204?null:await Zt.json().catch(()=>null),Un=(0,u.isAuthorizationOnlySession)(te)||ut?.status==="authorized";oo(G),ee("success"),vt(null),await new Promise(Tr=>setTimeout(Tr,1200));let mn;typeof ut?.paymentId=="string"?mn=ut.paymentId:te?.paymentId&&(mn=te.paymentId);let Dt;typeof ut?.authorizationExpiresAt=="string"?Dt=ut.authorizationExpiresAt:te?.authorizationExpiresAt&&(Dt=te.authorizationExpiresAt),a?.(Un?{status:"authorized",...mn===void 0?{}:{paymentId:mn},sessionId:typeof ut?.sessionId=="string"?ut.sessionId:G,...Dt===void 0?{}:{authorizationExpiresAt:Dt},paymentIntentId:i.threeDSecureActionResultTokenId,paymentMethodId:Ce,checkoutMethod:i.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:i.threeDSecureActionResultTokenId,paymentMethodId:Ce,checkoutMethod:i.isPaypal?"paypal":"card"});return}let It=await Zt.json().catch(()=>null);if(It?.type==="paypal_redirect_required"){let ut=It.threeDSecureToken,Un=It.paymentMethodId||i.id||"";if(!z||!ut){ee("error"),ge("PayPal authorization required but no token provided.");return}try{let mn=Fe?.getRawProvider();if(!mn){ge("PayPal is not available.");return}let Dt={return_url:window.location.href};Un&&(Dt.payment_method=Un);let{error:Tr}=await mn.confirmPayment({clientSecret:ut,confirmParams:Dt,redirect:"if_required"});if(Tr){ee("error");let Co=Tr.message??"PayPal payment failed.";ge(Co),Qn("paypal",Co,{code:Tr.code})}}catch(mn){ee("error"),ge(mn instanceof Error?mn.message:"PayPal authorization failed.")}return}if(It?.type==="paypal_direct_required"){let ut=It.orderId;if(!ut){ee("error"),ge("PayPal retry required but no order id provided.");return}let Un=et.current?.attempts??0;if(Un>=2){ee("error"),ge("PayPal payment could not be completed after multiple attempts."),Qn("paypal","paypal_direct_required retry limit exceeded");return}Aa(!1),Ba("loading"),vt({orderId:ut,attempts:Un+1}),ee(null);return}(0,u.classifyPaymentRejection)(Zt.status,It)||Bt(),ee("error");let gr=It?.message??"Payment failed. Please try again.";ge(gr),Qn(i.isPaypal?"paypal":"card",gr,{code:It?.code??It?.gatewayErrorCode,declineCode:It?.declineCode??It?.gatewayDeclineReason}),await new Promise(ut=>setTimeout(ut,1500))}catch(Ft){qs(Ft)||Bt(),ee("error"),ge(Ft instanceof Error?Ft.message:"An unexpected error occurred"),await new Promise(Zt=>setTimeout(Zt,1500))}finally{N(!1),ee(null),X.current=!1}},[st,e,t,ye,k,Ye,se,J,g,z,Fe,te,a,ge,Qn,mt]),Sn=(0,s.useCallback)((i,C)=>{y?y(i):Li(i,C)},[y,Li]),fo=`${$s}:${e}`;(0,s.useEffect)(()=>{if(typeof window>"u")return;let i=localStorage.getItem(fo);if(!i)return;let C;try{C=JSON.parse(i)}catch{localStorage.removeItem(fo);return}if(!C||typeof C.createdAt!="number"||Date.now()-C.createdAt<0||Date.now()-C.createdAt>Cc||typeof C.paymentMethodId!="string"||typeof C.providerIntentId!="string"||typeof C.paymentMethodType!="string"||C.sessionId!==e||!t||C.nonce!==t||!$r.includes(C.paymentMethodType)){localStorage.removeItem(fo);return}localStorage.removeItem(fo),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,fo,$r]);let Oi=(0,s.useRef)(!1);(0,s.useEffect)(()=>{if(typeof window>"u"||Oi.current)return;let i=new URLSearchParams(window.location.search),C=i.get("payment_intent"),G=i.get("payment_intent_client_secret"),Ne=i.get("redirect_status");if(!C||!G)return;let Q=Zt=>{let It=localStorage.getItem(Zt);if(!It)return null;try{return JSON.parse(It)}catch{return localStorage.removeItem(Zt),null}},Ce=Q(lr)??Q(Ms),ke;if(Ce?.clientSecret){if(Ce.clientSecret!==G)return;ke={...Ce.accountPatch?{accountPatch:Ce.accountPatch}:{},...Ce.sessionId?{sessionId:Ce.sessionId}:{},...Ce.nonce?{nonce:Ce.nonce}:{}}}else if(Ce?.sessionId&&Ce.sessionId!==e)return;Oi.current=!0,localStorage.removeItem(lr),localStorage.removeItem(Ms);let kt=new URL(window.location.href);kt.searchParams.delete("payment_intent"),kt.searchParams.delete("payment_intent_client_secret"),kt.searchParams.delete("redirect_status"),window.history.replaceState({},"",kt.toString());let Bt=Ce?.paymentMethodType??Ce?.tokenType??"card",Ft="card";(async()=>{let Zt=z?.getRawProvider();if(!Zt){let Dt="Payment is not available \u2014 please refresh and try again.";ge(Dt),Qn(Ft,Dt);return}if(Ne==="failed"){let Dt="Payment was declined. Please try again.";ge(Dt),Qn(Ft,Dt);return}let{paymentIntent:It,error:gr}=await Zt.retrievePaymentIntent(G);if(gr){let Dt=gr.message??"Failed to retrieve payment status.";ge(Dt),Qn(Ft,Dt,{code:gr.code});return}let ut=It?.status,Un=So(ut);if(!It||!Un){let Dt=ut==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";ge(Dt),Qn(Ft,Dt,{code:ut??"missing_payment_intent"});return}let mn=typeof It.payment_method=="string"?It.payment_method:It.payment_method?.id;Sn({id:mn??Ce?.paymentMethodId??Ce?.tokenId??It.id,type:"card",threeDSecureActionResultTokenId:It.id,gateway:Ce?.gateway??"stripe",paymentMethodType:Bt},ke)})()},[e,Sn,z,ge,Qn]);let Fa=(0,s.useCallback)(i=>{i.preventDefault()},[]);if(!(z!==null))return(0,d.jsx)("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let go=oe==="buttons",wn=W?.variables,fl=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),Da=wn?.colorBackground,gl=Da&&!fl.has(Da)?Da:void 0,ho=v.cardInputBorder??(go?"#e5e7eb":"#A4A4FF"),zi=wn?.colorDanger??"#dc2626",At=i=>Rr[i]&&(_n[i]||En),Ho=nn&&(wt||En),zn=i=>i?zi:ho,Ko=(un.malformed||un.empty)&&(Wn||En),hl=zn(Ko),Na=v.cardFormContainer?.backgroundColor??gl??(go?"white":"#EDEDFF"),jr=v.cardInputBackground??wn?.colorBackground??"white",La=Kr(Ae),Ui=Kr(Be),Vr=v.nameInput,$i=v.cardInputFontSize??Oc(Vr?.fontSize)??wn?.fontSizeBase??"16px",qi=typeof Vr?.fontFamily=="string"?Vr.fontFamily:wn?.fontFamily??"Poppins, sans-serif",ji=ei(Vr?.fontWeight)??400,bl=v.cardInputColor??(typeof Vr?.color=="string"?Vr.color:void 0)??wn?.colorText??"#262833",vl=v.cardInputPlaceholderColor??"#9ca3af",Ut=wn?.borderRadius??"8px",Er=wn?.borderRadius??v.cardButton?.borderRadius??Ut,_r=wn?.colorPrimary??"#4A49FF",Cl=wn?.colorPrimaryHover??lo(_r,.12),Oa=wn?.colorText??"#262833",za={fontSize:$i,fontFamily:qi,fontWeight:ji,color:bl,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},bo={marginTop:"0.375rem",...za,fontSize:"0.75rem",lineHeight:1.4,color:zi},Pl={"--flopay-input-placeholder-color":vl,"--flopay-input-font-size":$i,"--flopay-input-font-family":qi,"--flopay-input-font-weight":String(ji)},vo=v.cardFormContainer??{},Ua=vo.padding??(go?"0":"1rem"),$a=vo.borderRadius??Ut,Sl=zt&&xn?(0,d.jsx)(so,{capture:zt,html:xn.html,messageToken:xn.messageToken,expectedOrigin:xn.expectedOrigin,theme:We,onReady:()=>{if(!Ee&&!k||typeof document>"u")return;let i=()=>{let G=(document.querySelector('[data-testid="flopay-vault-identity-fields"]')??document.querySelector('[data-testid="flopay-avs-fields"]'))?.querySelector("input:not([disabled]), select:not([disabled])");if(G){Cn.current=!0;try{G.focus()}finally{Cn.current=!1}}};Jn.current||i()},onError:i=>ge(i),onValidation:i=>{let C=F.current;(C==="idle"||C==="validation-window")&&(ge(i),i&&F.current==="validation-window"&&(_.current&&(clearTimeout(_.current),_.current=null),F.current="idle",ee(null)))}}):(0,d.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"}),Vi=(0,d.jsxs)("div",{onFocusCapture:i=>{["INPUT","SELECT","TEXTAREA","IFRAME"].includes(i.target.tagName)&&Mn()},style:{backgroundColor:Na,borderRadius:$a,...vo,padding:Ua,...Pl,display:"flex",flexDirection:"column"},children:[(0,d.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 @@ ${Yt.join(`
35
35
  font-family: var(--flopay-input-font-family);
36
36
  font-weight: var(--flopay-input-font-weight);
37
37
  }
38
- `}),yo&&mr&&(0,l.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:we?-2:0},children:[(0,l.jsxs)("button",{type:"button",onClick:j,style:{display:"inline-flex",alignItems:"center",gap:Ba?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)(Hr,{content:Ae})]}),Li?(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)(bo,{content:Be})})]}),!yo&&!Li&&(0,l.jsx)("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:Fa,order:we?-3:0,...b.title},children:(0,l.jsx)(bo,{content:Be})}),we&&Ie&&(0,l.jsx)("div",{style:{order:-2,width:"100%"},children:Ie}),we&&_e&&(0,l.jsxs)("div",{"data-testid":"flopay-vault-identity-fields",style:{order:-1,marginTop:"0.5rem"},children:[(0,l.jsx)("div",{style:{backgroundColor:qr,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||ka()},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",...Da}})}),$o&&(0,l.jsx)("div",{id:"flopay-buyer-email-error",role:"alert","data-testid":"flopay-email-error",style:go,children:bt.empty?"Email address is required":"Enter a valid email address"})]}),P&&(0,l.jsx)("div",{style:{order:we?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let a=lt,C=(Z=!1)=>({backgroundColor:qr,border:`1px solid ${zn(Z)}`,borderRadius:Ut,marginTop:"0.5rem",padding:"10px"}),W=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...Da}),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:go,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:qr,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:qr,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:go,children:"City is required"}),At("state")&&(0,l.jsxs)("div",{id:"flopay-billing-state-error",role:"alert","data-testid":"flopay-state-error",style:go,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:qr,borderTop:`1px solid ${fo}`,borderRight:`1px solid ${fo}`,borderBottom:`1px solid ${fo}`,borderLeft:`1px solid ${fo}`,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:qr,border:`1px solid ${nl}`,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:go,children:un.empty?`${(0,u.getPostalCodeLabel)(a)} is required`:nc(a)})]})})()}),we&&sl,M&&(0,l.jsx)(Qr,{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"},qi=a=>Re?!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=${co}`,` shouldRenderStripePayPal=${uo}`,` hasPaypalStripeInstance=${!!Pn}`].join(`
39
- `)}):null,$i=a=>Re?!V||!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=${V}`,` currency=${Ue}`,` amountInCents=${On}`,` enabledPaymentMethods: ${JSON.stringify(S??[])}`,` enabledPaymentMethodsProvided=${so}`,` hasEnabledMethods=${No}`,` expressMethods: ${JSON.stringify(Oo)}`,` walletExpressMethods: ${JSON.stringify(zr)}`,` paymentElementMethods: ${JSON.stringify(lo)}`,` paymentElementMethodsForCurrency: ${JSON.stringify(zo)}`,` hasStripeInstance=${!!xe}`,` shouldRenderWallets=${Ur}`,` shouldRenderPaymentElement=${po}`].join(`
40
- `)}):null,ji=qe==="apm-expanding"||qe==="apm-form"||qe==="apm-collapsing",jr;qe==="apm-expanding"?jr=Cs:qe==="apm-collapsing"&&(jr=Ps);let Ko=Mt?Fs(Ea,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:pa,padding:"0 1rem"}:{padding:"0.9rem 1rem"},Oe;qe==="expanding"||qe==="apm-expanding"?Oe=Jl:(qe==="collapsing"||qe==="apm-collapsing")&&(Oe=Gl);let Z;return qe==="expanding"?Z=Cs:qe==="collapsing"&&(Z=Ps),(0,l.jsxs)("form",{onSubmit:xa,className:p,noValidate:!0,style:{position:"relative"},children:[(0,l.jsx)(ei,{}),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?Zl:{},...Oe?{animation:Oe,pointerEvents:"none"}:{}},children:[qi("flopay-direct-paypal-gate-debug"),$i("flopay-stripe-gate-debug"),co&&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)(Ro,{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:Or,onButtonClick:ae,runBeforeButtonClick:er,isProcessing:it,onLoadStateChange:_a,onInitializationStateChange:Ta,session:mt,existingOrderId:X?.orderId,debug:Re},X?.orderId??"fresh")]}),uo&&(0,l.jsx)($t.Elements,{stripe:Pn,options:yi,children:(0,l.jsx)(Is,{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:Or,runBeforeButtonClick:er,onLoadStateChange:Ci,placeholderBorderRadius:Er})}),Ur?(0,l.jsx)($t.Elements,{stripe:xe,options:mi,children:(0,l.jsx)(Rs,{sessionId:e,nonce:t,email:me.email,billingName:be||void 0,onBuyerIdentityReady:m,billingApiUrl:pe,intentKind:$>0?"payment":"setup",expressMethods:zr,onTokenizedBody:Sn,onErrorChange:fe,onButtonClick:ae,onDecline:c,onTechnicalFailure:Or,runBeforeButtonClick:er,onLoadStateChange:Si,placeholderBorderRadius:Er})}):null,!Ur&&Ei?(0,l.jsx)("div",{style:{height:pa,borderRadius:Er,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,po&&(0,l.jsx)(Es,{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:xe,paymentElementBaseOptions:Ea,onTokenizedBody:Sn,onErrorChange:fe,onButtonClick:ae,onDecline:c,runBeforeButtonClick:er,onLoadStateChange:ki,isProcessing:it,submitButtonColor:_r,submitButtonBorderRadius:Ut,submitButtonStyle:b.submitButton,onExpandApm:re,expandedApmMethod:Mt,themeId:he,buttonAppearance:{backgroundColor:b.cardButton?.backgroundColor,borderColor:b.cardInputBorder,textColor:b.cardButton?.color,borderRadius:Er}}),we&&(0,l.jsx)("button",{type:"button",onClick:async()=>{it||!(await er("card")).proceed||(ae?.("card"),U())},disabled:it,style:{width:"100%",...W,...b.cardButton,...oi({themeBundle:K,resolvedPrimaryColor:_r,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=al)},onMouseLeave:Ce=>{(K||wn?.colorPrimary)&&(Ce.currentTarget.style.backgroundColor=_r)},onMouseDown:Ce=>{Ce.currentTarget.style.transform="scale(0.985)"},onMouseUp:Ce=>{Ce.currentTarget.style.transform="scale(1)"},children:(0,l.jsx)(Kr,{content:$e})}),M&&qe==="buttons"&&(0,l.jsx)(Qr,{margin:"0.25rem 0",styleOverride:b.errorBanner,children:M})]}),we&&C&&(0,l.jsx)("div",{style:{gridArea:"1 / 1",...Z?{animation:Z}:{},...qe==="collapsing"?{pointerEvents:"none"}:{}},children:Ui}),V&&ji&&Mt&&Ko&&xe&&(0,l.jsx)("div",{style:{gridArea:"1 / 1",...jr?{animation:jr}:{},...qe==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,l.jsxs)("div",{style:{backgroundColor:Aa,borderRadius:Na,...ho,padding:La},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:Ba?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)(Hr,{content:Ae})]}),(0,l.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:b.titleFontSize??"1.05rem",color:Fa,paddingRight:80,...b.title},children:`Pay with ${(0,u.getStripeMethodDisplayName)(Mt)}`})]}),(0,l.jsx)($t.Elements,{stripe:xe,options:Ko,children:(0,l.jsx)(ni,{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:_r,submitButtonBorderRadius:Ut,submitButtonStyle:b.submitButton,errorText:M})},Mt)]})})]})]})}return ji&&Mt&&Ko&&xe&&V?(0,l.jsxs)("form",{onSubmit:xa,className:p,noValidate:!0,style:{position:"relative"},children:[(0,l.jsx)(ei,{}),We&&(0,l.jsx)(jn,{status:We,errorMessage:M,authorized:Et}),(0,l.jsx)("div",{style:{...jr?{animation:jr}:{},...qe==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,l.jsxs)("div",{style:{backgroundColor:Aa,borderRadius:Na,...ho,padding:La},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:Ba?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)(Hr,{content:Ae})]}),(0,l.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:b.titleFontSize??"1.05rem",color:Fa,paddingRight:80,...b.title},children:`Pay with ${(0,u.getStripeMethodDisplayName)(Mt)}`})]}),(0,l.jsx)($t.Elements,{stripe:xe,options:Ko,children:(0,l.jsx)(ni,{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:_r,submitButtonBorderRadius:Ut,submitButtonStyle:b.submitButton,errorText:M})},Mt)]})})]}):(0,l.jsxs)("form",{onSubmit:xa,className:p,noValidate:!0,style:{position:"relative"},children:[(0,l.jsx)(ei,{}),We&&(0,l.jsx)(jn,{status:We,errorMessage:M,authorized:Et}),(0,l.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[qi("flopay-direct-paypal-gate-debug-default"),$i("flopay-stripe-gate-debug-default"),co&&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)(Ro,{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:Or,onButtonClick:ae,runBeforeButtonClick:er,isProcessing:it,onLoadStateChange:_a,onInitializationStateChange:Ta,session:mt,existingOrderId:X?.orderId,debug:Re},X?.orderId??"fresh")]}),uo&&(0,l.jsx)($t.Elements,{stripe:Pn,options:yi,children:(0,l.jsx)(Is,{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:Or,runBeforeButtonClick:er,onLoadStateChange:Ci,placeholderBorderRadius:Er})}),Ur&&(0,l.jsx)($t.Elements,{stripe:xe,options:mi,children:(0,l.jsx)(Rs,{sessionId:e,nonce:t,email:me.email,billingName:be||void 0,onBuyerIdentityReady:m,billingApiUrl:pe,intentKind:$>0?"payment":"setup",expressMethods:zr,onTokenizedBody:Sn,onErrorChange:fe,onButtonClick:ae,onDecline:c,onTechnicalFailure:Or,runBeforeButtonClick:er,onLoadStateChange:Si,placeholderBorderRadius:Er})}),po&&(0,l.jsx)(Es,{sessionId:e,nonce:t,email:me.email,billingName:[me.firstName,me.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:pe,paymentElementMethods:zo,stripeInstance:xe,paymentElementBaseOptions:Ea,onTokenizedBody:Sn,onErrorChange:fe,onButtonClick:ae,onDecline:c,runBeforeButtonClick:er,onLoadStateChange:ki,isProcessing:it,submitButtonColor:_r,submitButtonBorderRadius:Ut,submitButtonStyle:b.submitButton,themeId:he,onExpandApm:re,expandedApmMethod:Mt,buttonAppearance:{backgroundColor:b.cardButton?.backgroundColor,borderColor:b.cardInputBorder,textColor:b.cardButton?.color,borderRadius:Er}})]}),we&&(Zs||Xs||Qs)&&(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"}})]}),we&&Ui]})}var k=require("react/jsx-runtime"),Dr=44,di="flopay_checkout_saved_payment_resume",va=new Map,ga=new Map;function Ds(e,t){t.settled&&t.consumers===0&&va.get(e)===t&&va.delete(e)}function lc(e,t,n){let r=ga.get(e);if(r&&(!r.sdkGeneratedIdempotencyKey||!t||r.sdkGeneratedIdempotencyKey===t))return r.attempt;let o=n(),i={attempt:o,sdkGeneratedIdempotencyKey:t};ga.set(e,i);let d=()=>{ga.get(e)===i&&ga.delete(e)};return o.then(d,d),o}function Fo(e){return new Promise(t=>setTimeout(t,e))}function ha(e,t,n){let r=Zo({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:Me.SDK_VERSION,enabled:t!==!1});return r.beginCheckout(n),r}function Do(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function ai(e,t,n,r,o){let i=ha(e,t,n);i.error({errorCode:r,stage:o,paymentMethodCategory:"unknown",...o==="session_read"?{requestCategory:"session_read"}:{}}),Do(i)}function cc(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 ci(e){let t=e?.data.paypal?.publishableKey;if(t)return{clientId:t,environment:e?.data.paypal?.environment,providerObjectType:e?.data.paypal?.providerObjectType}}function ii(e){return!e||e.data.stripe?.publishableKey?!1:!!ci(e)?.clientId}function ui(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function dc(){if(!ui())return null;try{let e=window.sessionStorage.getItem(di);return e?JSON.parse(e):null}catch{return null}}function Ls(e){if(ui())try{window.sessionStorage.setItem(di,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function si(){if(ui())try{window.sessionStorage.removeItem(di)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}function uc(){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 Ns(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 li(e,t){return e?"custom_layout":t==="buttons"?"buttons_layout":"default_layout"}function pc(e,t){return e?"unknown":t==="buttons"?"buttons":"embedded"}function Os(e){return e?.gateways?.stripe?"stripe":e?.gateways?.paypal?"paypal":void 0}function mc(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 ba({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:Pe,cardBackButtonContent:Rt,cardTitleContent:$e,showSecurityFooter:Ae,onButtonClick:Be,onBeforeButtonClick:le,enableAVS:ae,cardFieldOrder:D,cardPreFormSlot:Fe,avsLayout:De,className:te,initialErrorMessage:Ie=null,children:ve,checkoutMode:x,confirmLabel:Q,renderConfirmButton:Se,onSessionCompleted:ue}){let ce=(0,Me.resolveBillingApiUrl)(r),ze=(0,w.useMemo)(()=>(0,Me.resolveTheme)(G),[G]),rt=i??ze?.appearance,gt=n?"embedded_checkout":"standard_checkout",Ge=li(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),Re=(0,w.useMemo)(()=>n?to(n):"",[n]),O=n?`create:${Re}`:`session:${e??""}`,Le=Os(h),Te=(0,w.useRef)(new Set),pt=(0,w.useRef)(O),mt=(0,w.useRef)(O);ko(()=>{mt.current=O,pt.current!==O&&(pt.current=O,Te.current.clear())},[O]);let R=(0,w.useCallback)(U=>{if(mt.current===O){if($a.has(U.name)){if(Te.current.has(U.name))return;Te.current.add(U.name)}nt(()=>g?.(U))}},[O,g]),A=Zr(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)(Ie),[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),we=(0,w.useRef)(!1),tn=(0,w.useRef)(!1),dn=(0,w.useRef)(null),Ee=(0,w.useMemo)(()=>({checkoutMode:x??In,layout:pc(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(Ee),ye&&ye!==$&&Wt(ye)?.setCheckoutContext(Ee)},[$,ye,Ee]);let un=(0,w.useRef)(ue);un.current=ue;let Ir=(0,w.useCallback)(U=>{cn(U),!(U!=="exhausted"||tn.current)&&(tn.current=!0,Dn.current?.(new Me.FloPayError("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),Rr=(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:Me.SDK_VERSION,checkout_type:gt,checkout_layout:Ge,billing_api_url:ce})},[Ge,gt,ce]);let En=(0,w.useMemo)(()=>n?to(n,!0):"",[n]),ur=(0,w.useMemo)(()=>Ot===En?an:void 0,[an,Ot,En]),Wn=(0,w.useMemo)(()=>n?Oa(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(Ie)},[Ie]);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=Os(U),We=Qe.current??ne.current,ee=Wt(We),J=We?null:ha(ce,o,Ee),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=ps(j?.initialAutoProcessingError),K;if(M)pe(),M.type==="paypal_redirect_required"&&dn.current?.publishableKey&&Ls({sessionId:re,publishableKey:dn.current.publishableKey,paypalPublishableKey:dn.current.paypalPublishableKey}),K=await la(M,{flopay:Qe.current,paypalFlopay:ne.current,attempt3DS:j?.attempt3DS,billingApiUrl:ce,sessionId:re,session:U,telemetry:!1}),M.type==="paypal_redirect_required"&&si();else if(j?.initialAutoProcessingPending){let Ye=(await new Fr.PaymentAPI(ce,{telemetry:!1}).waitForCheckoutSessionCompletion(j.initialAutoProcessingPending.sessionId,{initialDelayMs:j.initialAutoProcessingPending.retryAfterMs})).data.session;if(!Yr(Ye))throw Go(Ye);K=Mr(Ye,re)}else{if(j?.initialAutoProcessingError)throw kr(j.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:j.initialAutoProcessingError.checkoutMethod});if(j?.fromCreateSession)return j?.fallbackToFull&&(hn("full"),Ns("full")),!1;{let b=await oo({billingApiUrl:ce,sessionId:re,session:U,telemetry:!1});b.type==="success"?K=b.result:(pe(),b.type==="paypal_redirect_required"&&dn.current?.publishableKey&&Ls({sessionId:re,publishableKey:dn.current.publishableKey,paypalPublishableKey:dn.current.paypalPublishableKey}),K=await la(b,{flopay:Qe.current,paypalFlopay:ne.current,attempt3DS:j?.attempt3DS,billingApiUrl:ce,sessionId:re,session:U,telemetry:!1}),b.type==="paypal_redirect_required"&&si())}}re&&no(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 Fo(1200),m=()=>Hn.current?.(K)}catch(M){let K=Mo(M),b=K.checkoutMethod??xo;Ct(K.message),Xe(K.message),bn(!1),j?.fallbackToFull&&(E.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),hn("full"),Ns("full")),T();let H=K.statusCode===void 0?void 0:(0,Me.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,Me.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([Fo(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&&Do(J),ct(null),Xe(null)}return nt(m),!0},[or,A,ce,o,Ee]);(0,w.useEffect)(()=>{if(typeof window>"u"||we.current)return;let U=new URLSearchParams(window.location.search),j=U.get("payment_intent_client_secret");if(!j)return;let re=dc();re&&(we.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 Me.FloPayError("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:ee,paypalFlopay:J}=await da({publishableKey:re.publishableKey,paypalPublishableKey:re.paypalPublishableKey,billingApiUrl:ce,locale:d,telemetry:o});oe=Wt(J??ee),oe?.setCheckoutContext(Ee),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 Me.FloPayError("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:B,error:X}=await E.retrievePaymentIntent(j);if(X)throw Object.assign(new Me.FloPayError(X.message??"Failed to retrieve PayPal payment status.","api_error",{code:X.code}),{checkoutMethod:"paypal"});let vt=Gi(B?.status);if(!B||vt==="failed")throw Object.assign(new Me.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 Fr.PaymentAPI(ce,{telemetry:!1}).getUnifiedCheckoutSession(re.sessionId)).data.session;if(m&&m.status!=="complete"){let M=await oo({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 Me.FloPayError("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});pe=M.result.status}}re.sessionId&&no(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 Fo(1200),nt(()=>Hn.current?.({status:pe,paymentIntentId:B.id,paymentMethodId:et,checkoutMethod:"paypal"}))}catch(ee){let J=Mo(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=ha(ce,o,Ee);X.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),Do(X)}else ai(ce,o,Ee,"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 Fo(1500)}finally{si(),uc(),ct(null),Xe(null),He(!1)}})())},[or,d,ce,o,Ee]);let Yn=(0,w.useRef)(null),Cn=(0,w.useMemo)(()=>St?to(St):"",[St]),Gn=(0,w.useRef)(St);Gn.current=St,(0,w.useEffect)(()=>{fn(e??"")},[e]),(0,w.useEffect)(()=>{z.current=!1,Ct(Ie),Xe(null),bn(!1),ct(null)},[Cn,Ie,e]);async function Jn(U,j,re){let oe=ha(ce,o,Ee),We=new Fr.PaymentAPI(ce,{telemetry:!1}),ee=!1;try{let J=U.idempotencyKey===void 0?void 0:(0,Me.resolveIdempotencyKey)(U.idempotencyKey),E=Ka(j,re),B=Ha(j,re);E?.canonicalIdentity===re&&B&&B.canonicalIdentity===void 0&&(aa(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&&(ls(at.data.session,U)?(oa(j,re,pe,E.nonce??at.data.session?.clientSecret),B&&B.canonicalIdentity===void 0&&(aa(j,re,B.idempotencyKey),X??(X=B.idempotencyKey))):(ra(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=Wr(We,pe,Ye,U.account)),pe&&at&&b==="complete"){if(Wa(pe))return{sid:pe,result:at};ra(j,re),pe=null,at=null,et=!0}}catch{oe.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),E?.canonicalIdentity===void 0?(ra(j,re),X=J):na(j,re),pe=null}if(!pe){!J&&(et||!X)&&(X=(0,Me.resolveIdempotencyKey)(),vt=X),X&&aa(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:li(ve,de)};Object.defineProperty(Ye,Fr.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,Me.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 Me.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,Me.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&&oa(j,re,be,me.data.session?.clientSecret??st.nonce),ln(),me},me=>{throw na(j,re),it(me),me}).finally(()=>Do(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&&oa(j,re,pe,at.data.session?.clientSecret)}let K=at?.data.session;return!m&&pe&&K?.buyerIdentified===!1&&K.clientSecret&&(m=Wr(We,pe,K.clientSecret,U.account)),{sid:pe??"",result:at,sdkGeneratedIdempotencyKey:vt,...T?{claimed:T}:{},...m?{claim:m}:{},...M?{claimRequiresIdentity:!0}:{}}}finally{ee||Do(oe)}}let dt=(0,w.useRef)(Jn);ko(()=>{dt.current=Jn},[Jn]);let Tn=(0,w.useCallback)(async(U,j)=>{let re=Gn.current;if(!re)throw new Me.FloPayError("createSession is required to bootstrap checkout.","validation_error");let oe=Oa(re,U),We=to(oe),ee=ss(oe),J=va.get(We);if(!J){let X={canonicalIdentity:We,promise:dt.current(oe,ee,We),consumers:0,settled:!1};J=X,va.set(We,X);let vt=()=>{X.settled=!0,Ds(We,X)};X.promise.then(vt,vt)}J.consumers+=1;let E=!1,B=()=>{E||(E=!0,J.consumers-=1,Ds(We,J))};j?.(B);try{let X=await J.promise;Yn.current=We,U&&(en(En),Kt(H=>Hi(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 Me.FloPayError?Ye:new Me.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}=ca(et),{flopay:K,paypalFlopay:b}=await da({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(!mc(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(Wi(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=ca(E.result);let X=ii(E.result),vt=Wa(E.sid||B?.id);if(!U&&J&&B&&!X&&!vt){z.current=!0,await lc(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 Fo(1200),U||(nt(()=>{Hn.current?.({status:"succeeded"})}),ct(null),Xe(null));return}J&&(ct(null),Xe(null));let X=E instanceof Me.FloPayError?E:new Me.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 Fr.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 Me.FloPayError("No session data returned","api_error");let X=B.checkoutMode;if(X==="setup")throw new Me.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?.(Mr(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?Wr(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=ii(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 Me.FloPayError?!ee&&!cc(J)&&ai(ce,o,Ee,"NETWORK_REQUEST_FAILED","session_read"):ai(ce,o,Ee,"INTERNAL_SDK_ERROR","checkout_mount");let E=J instanceof Me.FloPayError?J:new Me.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}=ca(ee);dn.current={publishableKey:J,paypalPublishableKey:E};let{flopay:B,paypalFlopay:X}=await da({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=ci(ie),pr=ii(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(Dr),ge&&(S||se)&&j(Dr),ge&&j(Dr),(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)(fc,{onButtonClick:Be,showPayPal:N,showStripe:ge,showApplePay:S,showGooglePay:se,theme:G,buttonsTheme:he,buttonsStyles:Ke,cardButtonContent:Pe,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)(Qr,{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:Rr,children:"Retry PayPal"})]}),xt?c??(0,k.jsx)("div",{role:"status","data-testid":"flopay-paypal-catalog-loading","aria-label":"Preparing PayPal",style:{height:Dr,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)(is,{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:Ir,allowAutomaticRetry:dr===0,session:h,telemetry:o,telemetryContext:Ee,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)(_o,{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}),Se?Se({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)(_o,{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)(yc,{sessionId:L,nonce:h?.clientSecret||void 0,billingApiUrl:ce,session:h,children:ve})]}):(0,k.jsx)(fa,{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,Me.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:Pe,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:li(ve,de),className:te,directPaypal:ci(ie),isSubscription:h?.mode==="subscription",session:h,dataAttachmentPending:xt,dataAttachmentRequiresIdentity:Pt,debug:q})},O)}),Ht]})}function yc({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 fc({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,Me.resolveTheme)(i),[i]),F=(0,w.useMemo)(()=>{let S=I?.buttonsLayout??(0,Me.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:Dr,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(g){let S=F.cardInputBorder??"#e5e7eb",se=F.cardInputBackground??"white",q=Vr(y),de=Vr(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)(Hr,{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)(bo,{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:`
38
+ `}),go&&yr&&(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:we?-2:0},children:[(0,d.jsxs)("button",{type:"button",onClick:V,style:{display:"inline-flex",alignItems:"center",gap:La?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,d.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,d.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,d.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,d.jsx)(Gr,{content:Ae})]}),Ui?(0,d.jsx)("div",{style:{flex:1}}):(0,d.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:v.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...v.title},children:(0,d.jsx)(Po,{content:Be})})]}),!go&&!Ui&&(0,d.jsx)("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:Oa,order:we?-3:0,...v.title},children:(0,d.jsx)(Po,{content:Be})}),we&&ze&&(0,d.jsx)("div",{style:{order:-2,width:"100%"},children:ze}),we&&Ee&&(0,d.jsxs)("div",{"data-testid":"flopay-vault-identity-fields",style:{order:-1,marginTop:"0.5rem"},children:[(0,d.jsx)("div",{style:{backgroundColor:jr,border:`1px solid ${zn(Ho)}`,borderRadius:Ut,padding:"10px"},children:(0,d.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:i=>{dt("email"),sn.current=i.target.value,Jt(i.target.value)},onPointerDown:()=>dt("email"),onKeyDown:()=>dt("email"),onBlur:()=>{Tn("email")&&or(!0),nn||_a()},disabled:it,required:!0,"aria-invalid":Ho||void 0,"aria-describedby":Ho?"flopay-buyer-email-error":void 0,"data-testid":"flopay-email",style:{width:"100%",border:"none",outline:"none",background:"transparent",...za}})}),Ho&&(0,d.jsx)("div",{id:"flopay-buyer-email-error",role:"alert","data-testid":"flopay-email-error",style:bo,children:Ct.empty?"Email address is required":"Enter a valid email address"})]}),k&&(0,d.jsx)("div",{style:{order:we?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let i=lt,C=(Q=!1)=>({backgroundColor:jr,border:`1px solid ${zn(Q)}`,borderRadius:Ut,marginTop:"0.5rem",padding:"10px"}),G=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...za}),Ne=(0,u.getStateOptions)(i);return(0,d.jsxs)(d.Fragment,{children:[(0,u.isAVSFieldVisible)(k.address_line_1,i)&&(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("div",{style:C(At("line1")),children:(0,d.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:Q=>{dt("line1"),St.current.addressLine1=!0,en.current=Q.target.value,Lt(Q.target.value)},onPointerDown:()=>dt("line1"),onKeyDown:()=>dt("line1"),onBlur:()=>Ln("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:G()})}),At("line1")&&(0,d.jsx)("div",{id:"flopay-billing-address-line1-error",role:"alert","data-testid":"flopay-address-line1-error",style:bo,children:"Street address is required"})]}),(0,u.isAVSFieldVisible)(k.address_line_2,i)&&(0,d.jsx)("div",{style:C(),children:(0,d.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:Q=>{St.current.addressLine2=!0,Xt.current=Q.target.value,ft(Q.target.value)},disabled:it,"data-testid":"flopay-address-line2",style:G()})}),((0,u.isAVSFieldVisible)(k.city,i)||(0,u.isAVSFieldVisible)(k.state,i))&&(0,d.jsxs)("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[(0,u.isAVSFieldVisible)(k.city,i)&&(0,d.jsx)("div",{style:{flex:1,backgroundColor:jr,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)(k.state,i)?{borderRight:"none",borderTopRightRadius:0,borderBottomRightRadius:0}:{borderRadius:Ut}},children:(0,d.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-city",name:"billing-city",placeholder:"City",autoComplete:"billing address-level2",value:Pt,onChange:Q=>{dt("city"),St.current.city=!0,Rn.current=Q.target.value,on(Q.target.value)},onPointerDown:()=>dt("city"),onKeyDown:()=>dt("city"),onBlur:()=>Ln("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:G()})}),(0,u.isAVSFieldVisible)(k.state,i)&&(0,d.jsx)("div",{style:{flex:1,backgroundColor:jr,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)(k.city,i)?{borderTopLeftRadius:0,borderBottomLeftRadius:0,borderLeft:`1px solid ${zn(At("state")||At("city"))}`}:{borderRadius:Ut}},children:Ne?(0,d.jsxs)("select",{id:"flopay-billing-state",name:"billing-state",value:ct,onChange:Q=>{dt("state"),St.current.state=!0,xt.current=Q.target.value,bn(Q.target.value)},onPointerDown:()=>dt("state"),onKeyDown:()=>dt("state"),onBlur:()=>Ln("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:{...G(),cursor:"pointer"},children:[(0,d.jsx)("option",{value:"",children:(0,u.getStateLabel)(i)}),Ne.map(Q=>(0,d.jsx)("option",{value:Q.code,children:Q.name},Q.code))]}):(0,d.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-state",name:"billing-state",placeholder:(0,u.getStateLabel)(i),autoComplete:"billing address-level1",value:ct,onChange:Q=>{dt("state"),St.current.state=!0,xt.current=Q.target.value,bn(Q.target.value)},onPointerDown:()=>dt("state"),onKeyDown:()=>dt("state"),onBlur:()=>Ln("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:G()})})]}),At("city")&&(0,d.jsx)("div",{id:"flopay-billing-city-error",role:"alert","data-testid":"flopay-city-error",style:bo,children:"City is required"}),At("state")&&(0,d.jsxs)("div",{id:"flopay-billing-state-error",role:"alert","data-testid":"flopay-state-error",style:bo,children:[(0,u.getStateLabel)(i)," is required"]}),((0,u.isAVSFieldVisible)(k.country,i)||(0,u.isAVSFieldVisible)(k.postal_code,i))&&(0,d.jsxs)("div",{style:{display:"flex",flexDirection:Pe==="column"?"column":"row",gap:Pe==="column"?"0.5rem":"0",marginTop:"0.5rem"},children:[(0,u.isAVSFieldVisible)(k.country,i)&&(0,d.jsx)("div",{style:{flex:Pe==="row"?1:void 0,backgroundColor:jr,borderTop:`1px solid ${ho}`,borderRight:`1px solid ${ho}`,borderBottom:`1px solid ${ho}`,borderLeft:`1px solid ${ho}`,padding:"10px",...Pe==="row"&&(0,u.isAVSFieldVisible)(k.postal_code,i)?{borderRadius:"0",borderTopLeftRadius:Ut,borderBottomLeftRadius:Ut,borderRight:"none"}:{borderRadius:Ut}},children:(0,d.jsx)("select",{id:"flopay-billing-country",name:"billing-country",value:lt,onChange:Q=>{St.current.country=!0,Ot.current=Q.target.value,Nt(Q.target.value),rt?.(Q.target.value),xt.current="",bn("")},disabled:it,autoComplete:"billing country","data-testid":"flopay-country",style:{...G(),cursor:"pointer"},children:u.COUNTRY_OPTIONS.map(Q=>(0,d.jsxs)("option",{value:Q.code,children:[Q.flag," ",Q.name]},Q.code))})}),(0,u.isAVSFieldVisible)(k.postal_code,i)&&(0,d.jsx)("div",{style:{flex:Pe==="row"?1:void 0,backgroundColor:jr,border:`1px solid ${hl}`,padding:"10px",...Pe==="row"&&(0,u.isAVSFieldVisible)(k.country,i)?{borderRadius:"0",borderTopRightRadius:Ut,borderBottomRightRadius:Ut}:{borderRadius:Ut}},children:(0,d.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:Q=>{dt("zip"),St.current.zip=!0,Ht.current=Q.target.value,In(Q.target.value),ht?.(Q.target.value)},onPointerDown:()=>dt("zip"),onKeyDown:()=>dt("zip"),onBlur:()=>{Tn("zip")&&Nn(!0)},disabled:it,required:un.required,"aria-invalid":Ko||void 0,"aria-describedby":Ko?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:G()})})]}),Ko&&(0,d.jsx)("div",{id:"flopay-billing-postal-code-error",role:"alert","data-testid":"flopay-zip-error",style:bo,children:un.empty?`${(0,u.getPostalCodeLabel)(i)} is required`:Dc(i)})]})})()}),we&&Sl,M&&(0,d.jsx)(to,{margin:"0.75rem 0",styleOverride:v.errorBanner,children:M})]}),Wo={margin:0,padding:"6px 8px",background:"#eef2ff",border:"1px solid #c7d2fe",borderRadius:6,color:"#111827",font:"11px/1.35 ui-monospace, SFMono-Regular, Menlo, monospace",whiteSpace:"pre-wrap",wordBreak:"break-word"},Hi=i=>Ie?!he||!ir?(0,d.jsx)("pre",{"data-testid":i,style:Wo,children:"FloPay/DirectPayPal-debug - not enabled"}):(0,d.jsx)("pre",{"data-testid":i,style:Wo,children:["FloPay/DirectPayPal-debug (parent gate)",` showPayPal=${he}`,` directPaypalConfigured=${ir}`,` inAppBrowserDetected=${String(jo)}`,` shouldRenderDirectPayPal=${po}`,` shouldRenderStripePayPal=${mo}`,` hasPaypalStripeInstance=${!!Pn}`].join(`
39
+ `)}):null,Ki=i=>Ie?!H||!xe?(0,d.jsx)("pre",{"data-testid":i,style:Wo,children:"FloPay/Stripe-debug - not enabled"}):(0,d.jsx)("pre",{"data-testid":i,style:Wo,children:["FloPay/Stripe-debug (parent gate)",` showStripe=${H}`,` currency=${Ue}`,` amountInCents=${On}`,` enabledPaymentMethods: ${JSON.stringify(S??[])}`,` enabledPaymentMethodsProvided=${co}`,` hasEnabledMethods=${Uo}`,` expressMethods: ${JSON.stringify($o)}`,` walletExpressMethods: ${JSON.stringify($r)}`,` paymentElementMethods: ${JSON.stringify(uo)}`,` paymentElementMethodsForCurrency: ${JSON.stringify(qo)}`,` hasStripeInstance=${!!xe}`,` shouldRenderWallets=${qr}`,` shouldRenderPaymentElement=${yo}`].join(`
40
+ `)}):null,Wi=$e==="apm-expanding"||$e==="apm-form"||$e==="apm-collapsing",Hr;$e==="apm-expanding"?Hr=Bs:$e==="apm-collapsing"&&(Hr=Fs);let Go=Mt?Ws(Ma,Mt):null;if(oe==="buttons"){let i=$e==="buttons"||$e==="expanding"||$e==="apm-expanding",C=$e==="expanding"||$e==="card"||$e==="collapsing",G=Ge===void 0?{boxSizing:"border-box",height:ga,padding:"0 1rem"}:{padding:"0.9rem 1rem"},Ne;$e==="expanding"||$e==="apm-expanding"?Ne=Tc:($e==="collapsing"||$e==="apm-collapsing")&&(Ne=_c);let Q;return $e==="expanding"?Q=Bs:$e==="collapsing"&&(Q=Fs),(0,d.jsxs)("form",{onSubmit:Fa,className:f,noValidate:!0,style:{position:"relative"},children:[(0,d.jsx)(oi,{}),Ke&&(0,d.jsx)(jn,{status:Ke,errorMessage:M,authorized:Rt}),(0,d.jsxs)("div",{style:{display:"grid"},children:[(0,d.jsxs)("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!i&&!Ne?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!i&&!Ne?Mc:{},...Ne?{animation:Ne,pointerEvents:"none"}:{}},children:[Hi("flopay-direct-paypal-gate-debug"),Ki("flopay-stripe-gate-debug"),po&&fe&&(0,d.jsxs)(d.Fragment,{children:[Z&&(0,d.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,d.jsx)(Eo,{sessionId:e,nonce:t,billingApiUrl:me,email:ye.email,billingName:ve||void 0,onBuyerIdentityReady:h,clientId:fe.clientId,environment:fe.environment,currency:Ue.toUpperCase(),isSubscription:ot,providerObjectType:E,onTokenizedBody:Sn,onComplete:a,onErrorChange:ge,onDecline:c,onTechnicalFailure:Ur,onButtonClick:ie,runBeforeButtonClick:er,isProcessing:it,onLoadStateChange:Aa,onInitializationStateChange:Ba,session:yt,existingOrderId:Z?.orderId,debug:Ie},Z?.orderId??"fresh")]}),mo&&(0,d.jsx)(qt.Elements,{stripe:Pn,options:bi,children:(0,d.jsx)(Os,{sessionId:e,nonce:t,email:ye.email,billingName:ve||void 0,onBuyerIdentityReady:h,billingApiUrl:me,onTokenizedBody:Sn,onErrorChange:ge,isProcessing:it,onButtonClick:ie,onDecline:c,onTechnicalFailure:Ur,runBeforeButtonClick:er,onLoadStateChange:ki,placeholderBorderRadius:Er})}),qr?(0,d.jsx)(qt.Elements,{stripe:xe,options:hi,children:(0,d.jsx)(zs,{sessionId:e,nonce:t,email:ye.email,billingName:ve||void 0,onBuyerIdentityReady:h,billingApiUrl:me,intentKind:j>0?"payment":"setup",expressMethods:$r,onTokenizedBody:Sn,onErrorChange:ge,onButtonClick:ie,onDecline:c,onTechnicalFailure:Ur,runBeforeButtonClick:er,onLoadStateChange:Ri,placeholderBorderRadius:Er})}):null,!qr&&Mi?(0,d.jsx)("div",{style:{height:ga,borderRadius:Er,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,yo&&(0,d.jsx)(Us,{sessionId:e,nonce:t,email:ye.email,billingName:[ye.firstName,ye.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:h,billingApiUrl:me,paymentElementMethods:qo,stripeInstance:xe,paymentElementBaseOptions:Ma,onTokenizedBody:Sn,onErrorChange:ge,onButtonClick:ie,onDecline:c,runBeforeButtonClick:er,onLoadStateChange:_i,isProcessing:it,submitButtonColor:_r,submitButtonBorderRadius:Ut,submitButtonStyle:v.submitButton,onExpandApm:ne,expandedApmMethod:Mt,themeId:ce,buttonAppearance:{backgroundColor:v.cardButton?.backgroundColor,borderColor:v.cardInputBorder,textColor:v.cardButton?.color,borderRadius:Er}}),we&&(0,d.jsx)("button",{type:"button",onClick:async()=>{it||!(await er("card")).proceed||(ie?.("card"),$())},disabled:it,style:{width:"100%",...G,...v.cardButton,...li({themeBundle:K,resolvedPrimaryColor:_r,resolvedBorderRadius:Ut,submitButtonStyle:v.submitButton,explicitPrimaryColor:wn?.colorPrimary}),fontSize:v.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=Cl)},onMouseLeave:Ce=>{(K||wn?.colorPrimary)&&(Ce.currentTarget.style.backgroundColor=_r)},onMouseDown:Ce=>{Ce.currentTarget.style.transform="scale(0.985)"},onMouseUp:Ce=>{Ce.currentTarget.style.transform="scale(1)"},children:(0,d.jsx)(Wr,{content:Ge})}),M&&$e==="buttons"&&(0,d.jsx)(to,{margin:"0.25rem 0",styleOverride:v.errorBanner,children:M})]}),we&&C&&(0,d.jsx)("div",{style:{gridArea:"1 / 1",...Q?{animation:Q}:{},...$e==="collapsing"?{pointerEvents:"none"}:{}},children:Vi}),H&&Wi&&Mt&&Go&&xe&&(0,d.jsx)("div",{style:{gridArea:"1 / 1",...Hr?{animation:Hr}:{},...$e==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,d.jsxs)("div",{style:{backgroundColor:Na,borderRadius:$a,...vo,padding:Ua},children:[(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,d.jsxs)("button",{type:"button","data-testid":"flopay-apm-back-button",onClick:re,style:{display:"inline-flex",alignItems:"center",gap:La?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,d.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,d.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,d.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,d.jsx)(Gr,{content:Ae})]}),(0,d.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:v.titleFontSize??"1.05rem",color:Oa,paddingRight:80,...v.title},children:`Pay with ${(0,u.getStripeMethodDisplayName)(Mt)}`})]}),(0,d.jsx)(qt.Elements,{stripe:xe,options:Go,children:(0,d.jsx)(ii,{method:Mt,sessionId:e,nonce:t,email:ye.email,billingName:[ye.firstName,ye.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:h,billingApiUrl:me,onTokenizedBody:Sn,onErrorChange:ge,onDecline:c,onCancel:re,runBeforeButtonClick:er,onButtonClick:ie,isProcessing:it,submitButtonColor:_r,submitButtonBorderRadius:Ut,submitButtonStyle:v.submitButton,errorText:M})},Mt)]})})]})]})}return Wi&&Mt&&Go&&xe&&H?(0,d.jsxs)("form",{onSubmit:Fa,className:f,noValidate:!0,style:{position:"relative"},children:[(0,d.jsx)(oi,{}),Ke&&(0,d.jsx)(jn,{status:Ke,errorMessage:M,authorized:Rt}),(0,d.jsx)("div",{style:{...Hr?{animation:Hr}:{},...$e==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,d.jsxs)("div",{style:{backgroundColor:Na,borderRadius:$a,...vo,padding:Ua},children:[(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,d.jsxs)("button",{type:"button","data-testid":"flopay-apm-back-button-default",onClick:re,style:{display:"inline-flex",alignItems:"center",gap:La?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,d.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,d.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,d.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,d.jsx)(Gr,{content:Ae})]}),(0,d.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:v.titleFontSize??"1.05rem",color:Oa,paddingRight:80,...v.title},children:`Pay with ${(0,u.getStripeMethodDisplayName)(Mt)}`})]}),(0,d.jsx)(qt.Elements,{stripe:xe,options:Go,children:(0,d.jsx)(ii,{method:Mt,sessionId:e,nonce:t,email:ye.email,billingName:[ye.firstName,ye.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:h,billingApiUrl:me,onTokenizedBody:Sn,onErrorChange:ge,onDecline:c,onCancel:re,runBeforeButtonClick:er,onButtonClick:ie,isProcessing:it,submitButtonColor:_r,submitButtonBorderRadius:Ut,submitButtonStyle:v.submitButton,errorText:M})},Mt)]})})]}):(0,d.jsxs)("form",{onSubmit:Fa,className:f,noValidate:!0,style:{position:"relative"},children:[(0,d.jsx)(oi,{}),Ke&&(0,d.jsx)(jn,{status:Ke,errorMessage:M,authorized:Rt}),(0,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Hi("flopay-direct-paypal-gate-debug-default"),Ki("flopay-stripe-gate-debug-default"),po&&fe&&(0,d.jsxs)(d.Fragment,{children:[Z&&(0,d.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,d.jsx)(Eo,{sessionId:e,nonce:t,billingApiUrl:me,email:ye.email,billingName:ve||void 0,onBuyerIdentityReady:h,clientId:fe.clientId,environment:fe.environment,currency:Ue.toUpperCase(),isSubscription:ot,providerObjectType:E,onTokenizedBody:Sn,onComplete:a,onErrorChange:ge,onDecline:c,onTechnicalFailure:Ur,onButtonClick:ie,runBeforeButtonClick:er,isProcessing:it,onLoadStateChange:Aa,onInitializationStateChange:Ba,session:yt,existingOrderId:Z?.orderId,debug:Ie},Z?.orderId??"fresh")]}),mo&&(0,d.jsx)(qt.Elements,{stripe:Pn,options:bi,children:(0,d.jsx)(Os,{sessionId:e,nonce:t,email:ye.email,billingName:ve||void 0,onBuyerIdentityReady:h,billingApiUrl:me,onTokenizedBody:Sn,onErrorChange:ge,isProcessing:it,onButtonClick:ie,onDecline:c,onTechnicalFailure:Ur,runBeforeButtonClick:er,onLoadStateChange:ki,placeholderBorderRadius:Er})}),qr&&(0,d.jsx)(qt.Elements,{stripe:xe,options:hi,children:(0,d.jsx)(zs,{sessionId:e,nonce:t,email:ye.email,billingName:ve||void 0,onBuyerIdentityReady:h,billingApiUrl:me,intentKind:j>0?"payment":"setup",expressMethods:$r,onTokenizedBody:Sn,onErrorChange:ge,onButtonClick:ie,onDecline:c,onTechnicalFailure:Ur,runBeforeButtonClick:er,onLoadStateChange:Ri,placeholderBorderRadius:Er})}),yo&&(0,d.jsx)(Us,{sessionId:e,nonce:t,email:ye.email,billingName:[ye.firstName,ye.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:me,paymentElementMethods:qo,stripeInstance:xe,paymentElementBaseOptions:Ma,onTokenizedBody:Sn,onErrorChange:ge,onButtonClick:ie,onDecline:c,runBeforeButtonClick:er,onLoadStateChange:_i,isProcessing:it,submitButtonColor:_r,submitButtonBorderRadius:Ut,submitButtonStyle:v.submitButton,themeId:ce,onExpandApm:ne,expandedApmMethod:Mt,buttonAppearance:{backgroundColor:v.cardButton?.backgroundColor,borderColor:v.cardInputBorder,textColor:v.cardButton?.color,borderRadius:Er}})]}),we&&(ml||pl||yl)&&(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem",margin:"0.5rem 0 0.75rem",color:"#999",fontSize:"0.85rem"},children:[(0,d.jsx)("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}}),(0,d.jsx)("span",{children:"or pay with card"}),(0,d.jsx)("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}})]}),we&&Vi]})}var R=require("react/jsx-runtime"),Lr=44,yi="flopay_checkout_saved_payment_resume",Sa=new Map,Ca=new Map;function Gs(e,t){t.settled&&t.consumers===0&&Sa.get(e)===t&&Sa.delete(e)}function $c(e,t,n){let r=Ca.get(e);if(r&&(!r.sdkGeneratedIdempotencyKey||!t||r.sdkGeneratedIdempotencyKey===t))return r.attempt;let o=n(),a={attempt:o,sdkGeneratedIdempotencyKey:t};Ca.set(e,a);let l=()=>{Ca.get(e)===a&&Ca.delete(e)};return o.then(l,l),o}function Lo(e){return new Promise(t=>setTimeout(t,e))}function Pa(e,t,n){let r=ta({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:Me.SDK_VERSION,enabled:t!==!1});return r.beginCheckout(n),r}function Oo(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function ci(e,t,n,r,o){let a=Pa(e,t,n);a.error({errorCode:r,stage:o,paymentMethodCategory:"unknown",...o==="session_read"?{requestCategory:"session_read"}:{}}),Oo(a)}function qc(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 mi(e){let t=e?.data.paypal?.publishableKey;if(t)return{clientId:t,environment:e?.data.paypal?.environment,providerObjectType:e?.data.paypal?.providerObjectType}}function di(e){return!e||e.data.stripe?.publishableKey?!1:!!mi(e)?.clientId}function fi(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function jc(){if(!fi())return null;try{let e=window.sessionStorage.getItem(yi);return e?JSON.parse(e):null}catch{return null}}function Ys(e){if(fi())try{window.sessionStorage.setItem(yi,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function ui(){if(fi())try{window.sessionStorage.removeItem(yi)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}function Vc(){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 Js(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 pi(e,t){return e?"custom_layout":t==="buttons"?"buttons_layout":"default_layout"}function Hc(e,t){return e?"unknown":t==="buttons"?"buttons":"embedded"}function Xs(e){return e?.gateways?.stripe?"stripe":e?.gateways?.paypal?"paypal":void 0}function Kc(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 wa({sessionId:e,nonce:t,createSession:n,billingApiUrl:r,telemetry:o,appearance:a,locale:l,loading:c,error:y,onComplete:m,onError:p,onInstrument:g,onDecline:f,onCountryChange:P,onZipChange:A,showPayPal:D=!0,showStripe:he=!0,enabledPaymentMethods:H,showApplePay:S=!0,showGooglePay:le=!0,debug:q=!1,layout:pe,theme:oe,buttonsTheme:ce,buttonsStyles:Ve,cardButtonContent:de,cardBackButtonContent:Tt,cardTitleContent:Ge,showSecurityFooter:Ae,onButtonClick:Be,onBeforeButtonClick:ae,enableAVS:ie,cardFieldOrder:O,cardPreFormSlot:Le,avsLayout:Oe,className:_e,initialErrorMessage:ze=null,children:Pe,checkoutMode:w,confirmLabel:ue,renderConfirmButton:be,onSessionCompleted:Y}){let L=(0,Me.resolveBillingApiUrl)(r),Se=(0,I.useMemo)(()=>(0,Me.resolveTheme)(oe),[oe]),rt=a??Se?.appearance,ht=n?"embedded_checkout":"standard_checkout",Ye=pi(Pe,pe),[se,J]=(0,I.useState)(null),[j,Ue]=(0,I.useState)(null),Qe=(0,I.useRef)(null),[fe,ot]=(0,I.useState)(null),te=(0,I.useRef)(null),[b,tt]=(0,I.useState)(null),Ie=(0,I.useMemo)(()=>n?ro(n):"",[n]),z=n?`create:${Ie}`:`session:${e??""}`,Fe=Xs(b),Te=(0,I.useRef)(new Set),mt=(0,I.useRef)(z),yt=(0,I.useRef)(z);Br(()=>{yt.current=z,mt.current!==z&&(mt.current=z,Te.current.clear())},[z]);let E=(0,I.useCallback)($=>{if(yt.current===z){if(Ka.has($.name)){if(Te.current.has($.name))return;Te.current.add($.name)}nt(()=>g?.($))}},[z,g]),B=eo(E,z),bt=(0,I.useRef)(!1),Je=(0,I.useCallback)($=>{if(bt.current)return;let V=$.gateway||!Fe?$:{...$,gateway:Fe};E(V)},[E,Fe]);(0,I.useEffect)(()=>{B({class:"lifecycle",name:"checkout.mount"})},[B]);let[Gt,fn]=(0,I.useState)(e??""),N=e??Gt,jt=n?"":N,[Yt,lt]=(0,I.useState)(!0),[Nt,gn]=(0,I.useState)(null),[In,hn]=(0,I.useState)("full"),[Lt,He]=(0,I.useState)(!1),[ft,Pt]=(0,I.useState)(ze),[on,ct]=(0,I.useState)(null),[bn,Xe]=(0,I.useState)(null),[Jt,vn]=(0,I.useState)(!1),[an,Ht]=(0,I.useState)(void 0),[Ot,en]=(0,I.useState)(""),[Xt,Rn]=(0,I.useState)(!1),[xt,sn]=(0,I.useState)(!1),[St,k]=(0,I.useState)(!1),gt=(0,I.useRef)(0),Rt=(0,I.useRef)(void 0),[Et,cn]=(0,I.useState)("loading"),[ur,Fn]=(0,I.useState)(0),U=(0,I.useRef)(!1),we=(0,I.useRef)(!1),tn=(0,I.useRef)(!1),dn=(0,I.useRef)(null),Re=(0,I.useMemo)(()=>({checkoutMode:w??In,layout:Hc(Pe,pe)}),[w,Pe,In,pe]),Kn=(0,I.useRef)(m);Kn.current=m;let Dn=(0,I.useRef)(p);Dn.current=p;let zt=(0,I.useRef)(f);zt.current=f,(0,I.useEffect)(()=>{Wt(j)?.setCheckoutContext(Re),fe&&fe!==j&&Wt(fe)?.setCheckoutContext(Re)},[j,fe,Re]);let un=(0,I.useRef)(Y);un.current=Y;let Ir=(0,I.useCallback)($=>{cn($),!($!=="exhausted"||tn.current)&&(tn.current=!0,Dn.current?.(new Me.FloPayError("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),Rr=(0,I.useCallback)(()=>{cn("retrying"),Fn($=>$+1)},[]);(0,I.useEffect)(()=>{cn("loading"),Fn(0),tn.current=!1},[N]),(0,I.useEffect)(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:Me.SDK_VERSION,checkout_type:ht,checkout_layout:Ye,billing_api_url:L})},[Ye,ht,L]);let En=(0,I.useMemo)(()=>n?ro(n,!0):"",[n]),pr=(0,I.useMemo)(()=>Ot===En?an:void 0,[an,Ot,En]),Wn=(0,I.useMemo)(()=>n?qa(n,pr):void 0,[n,pr]),Nn=w??Wn?.checkoutMode??"full",wt=(0,I.useMemo)(()=>Wn?{...Wn,checkoutMode:Nn}:void 0,[Wn,Nn]);(0,I.useEffect)(()=>{Ht(void 0),en(En),Rt.current=void 0,k(!1)},[En]),(0,I.useEffect)(()=>{Pt(ze)},[ze]);let or=(0,I.useCallback)(($,V,ne)=>{nt(()=>{zt.current?.(Qt($,V,ne))})},[]),_n=(0,I.useCallback)(async($,V)=>{Pt(null),Xe(null),vn(!1),ct("processing");let ne=V?.sessionId??$.id,re=Xs($),Ke=Qe.current??te.current,ee=Wt(Ke),X=Ke?null:Pa(L,o,Re),_={log:M=>{ee?ee.log(M):X?.log(M)},error:M=>{ee?ee.error(M):X?.error(M)},terminal:M=>{ee?ee.terminal(M):X?.terminal(M)},performance:M=>{ee?ee.performance(M):X?.performance(M)},now:()=>ee?.now()??X?.now()??0,elapsed:M=>ee?.elapsed(M)??Math.max(0,(X?.now()??M)-M)},F=_.now(),Z=!!(V?.initialAutoProcessingError||V?.initialAutoProcessingPending),vt=!1,et,me=()=>{vt||(vt=!0,Z=!0,et=_.now(),_.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),_.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},at=!1,x=()=>{at||(at=!0,_.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),_.performance({stage:"processing",durationMs:_.elapsed(F),durationMode:"machine",paymentMethodCategory:"saved"}),et!==void 0&&_.performance({stage:"recovery",durationMs:_.elapsed(et),durationMode:"machine",paymentMethodCategory:"saved"}))};_.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),bt.current=!0;try{_.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"})}finally{bt.current=!1}B({class:"lifecycle",name:"payment.processing.started",provider:re}),Z&&me();let h;try{let M=gs(V?.initialAutoProcessingError),K;if(M)me(),M.type==="paypal_redirect_required"&&dn.current?.publishableKey&&Ys({sessionId:ne,publishableKey:dn.current.publishableKey,paypalPublishableKey:dn.current.paypalPublishableKey}),K=await ua(M,{flopay:Qe.current,paypalFlopay:te.current,attempt3DS:V?.attempt3DS,billingApiUrl:L,sessionId:ne,session:$,telemetry:!1}),M.type==="paypal_redirect_required"&&ui();else if(V?.initialAutoProcessingPending){let We=(await new Nr.PaymentAPI(L,{telemetry:!1}).waitForCheckoutSessionCompletion(V.initialAutoProcessingPending.sessionId,{initialDelayMs:V.initialAutoProcessingPending.retryAfterMs})).data.session;if(!Jr(We))throw Zo(We);K=Mr(We,ne)}else{if(V?.initialAutoProcessingError)throw kr(V.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:V.initialAutoProcessingError.checkoutMethod});if(V?.fromCreateSession)return V?.fallbackToFull&&(hn("full"),Js("full")),!1;{let v=await io({billingApiUrl:L,sessionId:ne,session:$,telemetry:!1});v.type==="success"?K=v.result:(me(),v.type==="paypal_redirect_required"&&dn.current?.publishableKey&&Ys({sessionId:ne,publishableKey:dn.current.publishableKey,paypalPublishableKey:dn.current.paypalPublishableKey}),K=await ua(v,{flopay:Qe.current,paypalFlopay:te.current,attempt3DS:V?.attempt3DS,billingApiUrl:L,sessionId:ne,session:$,telemetry:!1}),v.type==="paypal_redirect_required"&&ui())}}ne&&oo(ne),x(),Z&&(_.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),_.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),_.terminal({outcome:K.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),vn(K.status==="authorized"),ct("success"),await Lo(1200),h=()=>Kn.current?.(K)}catch(M){let K=Ao(M),v=K.checkoutMethod??Mo;Pt(K.message),Xe(K.message),vn(!1),V?.fallbackToFull&&(_.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),hn("full"),Js("full")),x();let W=K.statusCode===void 0?void 0:(0,Me.telemetryStatusClass)(K.statusCode,"unknown"),We=W==="4xx"?{requestCategory:"process_payment",statusClass:W}:{},ln=W===void 0||W==="4xx";if(ln&&(K.telemetryOutcome==="payment_declined"||!!(K.declineCode||K.code?.toLowerCase().includes("declin"))))_.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...We});else if(ln&&(K.telemetryOutcome==="validation_rejected"||K.type==="validation_error"))_.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...We});else{let ye=(0,Me.classifyTelemetryFailure)(M,Z?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown"),ve=K.telemetryRequestCategory??"process_payment";bt.current=!0;try{_.error({...ye,...K.telemetryFailureCategory?{failureCategory:K.telemetryFailureCategory}:{},stage:Z?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:ve})}finally{bt.current=!1}B({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:ve,provider:re})}return nt(()=>Dn.current?.(K)),or(v,K,{code:K.code,declineCode:K.declineCode}),ct("error"),await Promise.allSettled([Lo(1500),V?.ensureProvidersReady?V.ensureProvidersReady():Promise.resolve()]),Z&&(_.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),_.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{x(),X&&Oo(X),ct(null),Xe(null)}return nt(h),!0},[or,B,L,o,Re]);(0,I.useEffect)(()=>{if(typeof window>"u"||we.current)return;let $=new URLSearchParams(window.location.search),V=$.get("payment_intent_client_secret");if(!V)return;let ne=jc();ne&&(we.current=!0,(async()=>{let re,Ke=0;Pt(null),Xe(null),ct("processing"),He(!0);try{if($.get("redirect_status")==="failed")throw Object.assign(new Me.FloPayError("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:ee,paypalFlopay:X}=await ma({publishableKey:ne.publishableKey,paypalPublishableKey:ne.paypalPublishableKey,billingApiUrl:L,locale:l,telemetry:o});re=Wt(X??ee),re?.setCheckoutContext(Re),Ke=re?.now()??0,re?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),re?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let _=(X??ee)?.getRawProvider();if(!_)throw Object.assign(new Me.FloPayError("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:F,error:Z}=await _.retrievePaymentIntent(V);if(Z)throw Object.assign(new Me.FloPayError(Z.message??"Failed to retrieve PayPal payment status.","api_error",{code:Z.code}),{checkoutMethod:"paypal"});let vt=Qi(F?.status);if(!F||vt==="failed")throw Object.assign(new Me.FloPayError("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let et=typeof F.payment_method=="string"?F.payment_method:F.payment_method?.id,me=vt;if(ne.sessionId){let h=(await new Nr.PaymentAPI(L,{telemetry:!1}).getUnifiedCheckoutSession(ne.sessionId)).data.session;if(h&&h.status!=="complete"){let M=await io({billingApiUrl:L,sessionId:ne.sessionId,session:h,telemetry:!1,tokenizedData:{id:et??F.id,type:"card",threeDSecureActionResultTokenId:F.id,isPaypal:!0}});if(M.type!=="success")throw Object.assign(new Me.FloPayError("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});me=M.result.status}}ne.sessionId&&oo(ne.sessionId),re?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),re?.performance({stage:"redirect_resume",durationMs:re.elapsed(Ke),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),re?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),ct("success"),await Lo(1200),nt(()=>Kn.current?.({status:me,paymentIntentId:F.id,paymentMethodId:et,checkoutMethod:"paypal"}))}catch(ee){let X=Ao(ee),_=X.checkoutMethod??"paypal",F=!!(X.declineCode||X.code?.toLowerCase().includes("declin"));if(re)re.performance({stage:"redirect_resume",durationMs:re.elapsed(Ke),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),F?re.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):re.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(F){let Z=Pa(L,o,Re);Z.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),Oo(Z)}else ci(L,o,Re,"REDIRECT_RESUME_FAILED","redirect_resume");Pt(X.message),Xe(X.message),nt(()=>Dn.current?.(X)),or(_,X,{code:X.code,declineCode:X.declineCode}),ct("error"),await Lo(1500)}finally{ui(),Vc(),ct(null),Xe(null),He(!1)}})())},[or,l,L,o,Re]);let Gn=(0,I.useRef)(null),Cn=(0,I.useMemo)(()=>wt?ro(wt):"",[wt]),Yn=(0,I.useRef)(wt);Yn.current=wt,(0,I.useEffect)(()=>{fn(e??"")},[e]),(0,I.useEffect)(()=>{U.current=!1,Pt(ze),Xe(null),vn(!1),ct(null)},[Cn,ze,e]);async function Jn($,V,ne){let re=Pa(L,o,Re),Ke=new Nr.PaymentAPI(L,{telemetry:!1}),ee=!1;try{let X=$.idempotencyKey===void 0?void 0:(0,Me.resolveIdempotencyKey)($.idempotencyKey),_=Ya(V,ne),F=Ja(V,ne);_?.canonicalIdentity===ne&&F&&F.canonicalIdentity===void 0&&(la(V,ne,F.idempotencyKey),F={...F,canonicalIdentity:ne});let Z=X??(F?.canonicalIdentity===ne?F.idempotencyKey:void 0),vt,et=!1;re.log({name:_?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let me=_?.sid??null,at=null,x,h,M=!1;if(me)try{at=await Ke.getUnifiedCheckoutSession(me,_?.nonce),_&&_.canonicalIdentity===void 0&&(ps(at.data.session,$)?(sa(V,ne,me,_.nonce??at.data.session?.clientSecret),F&&F.canonicalIdentity===void 0&&(la(V,ne,F.idempotencyKey),Z??(Z=F.idempotencyKey))):(ia(V,ne),F=null,Z=X,me=null,at=null));let v=at?.data.session?.status,W=at?.data.session,We=W?.clientSecret||_?.nonce;if(me&&W?.buyerIdentified===!1&&We&&(h=Yr(Ke,me,We,$.account)),me&&at&&v==="complete"){if(Xa(me))return{sid:me,result:at};ia(V,ne),me=null,at=null,et=!0}}catch{re.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),_?.canonicalIdentity===void 0?(ia(V,ne),Z=X):aa(V,ne),me=null}if(!me){!X&&(et||!Z)&&(Z=(0,Me.resolveIdempotencyKey)(),vt=Z),Z&&la(V,ne,Z);let v=re.now(),W=0;re.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let We={...$,idempotencyKey:Z,avsCheck:!!ie,avsConfig:typeof ie=="object"?ie:void 0,checkoutType:"embedded_checkout",checkoutLayout:pi(Pe,pe)};Object.defineProperty(We,Nr.SESSION_CREATE_TELEMETRY,{configurable:!1,enumerable:!1,value:{onAttempt:st=>{W=Math.max(W,st)}}});let ln=()=>{re.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:"2xx"}),re.performance({stage:"session_create",durationMs:re.now()-v,durationMode:"machine",requestCategory:"session_create",attempt:W,statusClass:"2xx"})},it=st=>{let ye=(0,Me.classifyTelemetryFailure)(st,"CHECKOUT_SESSION_CREATE_FAILED","unknown");re.performance({stage:"session_create",durationMs:re.now()-v,durationMode:"machine",requestCategory:"session_create",attempt:W,statusClass:ye.statusClass}),st instanceof Me.FloPayError&&st.type==="validation_error"?re.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown"}):ye.statusClass==="4xx"?re.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create",statusClass:"4xx"}):(re.error({...ye,stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create"}),B({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_create"}))};try{if((0,Me.isDetachedSessionEligible)(We)){let st=await Ke.createDetachedSession(We);st.claimed.catch(()=>{}),at=st.shell,me=st.sessionId,h=st.claim,x=st.claimed.then(ye=>{let ve=ye.data.session?.id??st.sessionId;return ve&&sa(V,ne,ve,ye.data.session?.clientSecret??st.nonce),ln(),ye},ye=>{throw aa(V,ne),it(ye),ye}).finally(()=>Oo(re)),x.catch(()=>{}),ee=!0,re.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),re.performance({stage:"session_shell",durationMs:re.now()-v,durationMode:"machine",requestCategory:"session_create",attempt:W,statusClass:"2xx",paymentMethodCategory:"card"})}else at=await Ke.createAndFetchSession(We),ln()}catch(st){throw it(st),st}me=at.data.session?.id??me??"",me&&!x&&sa(V,ne,me,at.data.session?.clientSecret)}let K=at?.data.session;return!h&&me&&K?.buyerIdentified===!1&&K.clientSecret&&(h=Yr(Ke,me,K.clientSecret,$.account)),{sid:me??"",result:at,sdkGeneratedIdempotencyKey:vt,...x?{claimed:x}:{},...h?{claim:h}:{},...M?{claimRequiresIdentity:!0}:{}}}finally{ee||Oo(re)}}let dt=(0,I.useRef)(Jn);Br(()=>{dt.current=Jn},[Jn]);let Tn=(0,I.useCallback)(async($,V)=>{let ne=Yn.current;if(!ne)throw new Me.FloPayError("createSession is required to bootstrap checkout.","validation_error");let re=qa(ne,$),Ke=ro(re),ee=us(re),X=Sa.get(Ke);if(!X){let Z={canonicalIdentity:Ke,promise:dt.current(re,ee,Ke),consumers:0,settled:!1};X=Z,Sa.set(Ke,Z);let vt=()=>{Z.settled=!0,Gs(Ke,Z)};Z.promise.then(vt,vt)}X.consumers+=1;let _=!1,F=()=>{_||(_=!0,X.consumers-=1,Gs(Ke,X))};V?.(F);try{let Z=await X.promise;Gn.current=Ke,$&&(en(En),Ht(W=>Ji(W,$)));let{sid:vt,result:et,claimed:me,claim:at,claimRequiresIdentity:x}=Z;if(Rt.current=at,k(x===!0),J(et),et.data.session&&tt(et.data.session),vt&&fn(vt),me){gt.current+=1;let W=gt.current;sn(!0),me.then(We=>{gt.current===W&&(J(We),We.data.session&&tt(We.data.session),sn(!1),k(!1))},We=>{gt.current===W&&(sn(!1),k(!1),gn(We instanceof Me.FloPayError?We:new Me.FloPayError(We instanceof Error?We.message:"Failed to create session","api_error")))})}else gt.current+=1,sn(!1),k(!1);let{publishableKey:h,paypalPublishableKey:M}=pa(et),{flopay:K,paypalFlopay:v}=await ma({publishableKey:h,paypalPublishableKey:M,billingApiUrl:L,locale:l,telemetry:o});return Qe.current=K,Ue(K),te.current=v,ot(v),lt(!1),Z}catch(Z){throw Gn.current===Ke&&(Gn.current=null),Z}finally{V||F()}},[En,l,L,o]),Ln=(0,I.useRef)(_n);Ln.current=_n;let xn=(0,I.useRef)(Tn);xn.current=Tn;let Xn=(0,I.useCallback)(async $=>{if(!Kc($)||Xt)return{sessionId:Gt,session:b};Rn(!0);try{let V=await Tn($);return{sessionId:V.sid,session:V.result.data.session??null}}finally{Rn(!1)}},[Tn,Xt,Gt,b]),$e=(0,I.useCallback)(async $=>{let V=Rt.current;if(!V)return;let ne=gt.current,re=await V($);gt.current===ne&&(J(re),re.data.session&&tt(re.data.session))},[]);(0,I.useEffect)(()=>{let $=!1,V;gn(null);let ne=Yn.current;if(Cn&&ne)return hn(Nn),lt(!1),Gn.current===Cn?()=>{$=!0}:(tt(Xi(ne,w)),(async()=>{let ee=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),X=Nn==="auto"&&!U.current&&!ee;X&&(Pt(null),Xe(null),ct("processing"));try{let _=await xn.current(void 0,et=>{V=et}),F=_.result.data.session??null;dn.current=pa(_.result);let Z=di(_.result),vt=Xa(_.sid||F?.id);if(!$&&X&&F&&!Z&&!vt){U.current=!0,await $c(Cn,_.sdkGeneratedIdempotencyKey,()=>Ln.current(F,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:_.result.autoProcessingError,initialAutoProcessingPending:_.result.autoProcessingPending,autoProcessingAttempted:_.result.autoProcessingAttempted,sessionId:_.sid||F.id}));return}!$&&X&&((Z||vt)&&(U.current=!0),ct(null),Xe(null))}catch(_){if($)return;let F=Xo(_);if(X&&F==="session_auto_completed"){U.current=!0,ct("success"),await Lo(1200),$||(nt(()=>{Kn.current?.({status:"succeeded"})}),ct(null),Xe(null));return}X&&(ct(null),Xe(null));let Z=_ instanceof Me.FloPayError?_:new Me.FloPayError(_ instanceof Error?_.message:"Failed to create session","api_error");gn(Z)}finally{V?.(),V=void 0}})(),()=>{$=!0,V?.()});lt(!0);async function re(){let ee=!1;try{let X=new Nr.PaymentAPI(L,{telemetry:!1}),_=await X.getUnifiedCheckoutSession(N,t);if($)return;J(_);let F=_.data.session??null;if(tt(F),!F)throw new Me.FloPayError("No session data returned","api_error");let Z=F.checkoutMode;if(Z==="setup")throw new Me.FloPayError("This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.","validation_error",{code:"InvalidCardSetupSurface",param:"sessionId"});if(F.status==="authorized"){lt(!1),nt(()=>{Kn.current?.(Mr(F,N)),un.current?.(F.successUrl??"")});return}if(F.status==="complete"){lt(!1),nt(()=>{un.current?.(F.successUrl??"")});return}if(F.status==="expired")throw Jo(F);ee=!0;let vt=w??Z??"full";hn(vt),gt.current+=1;let et=F.clientSecret||t;Rt.current=F.buyerIdentified===!1&&et?Yr(X,N,et,{...F.customer?.id?{userId:F.customer.id}:{}}):void 0,sn(!1),k(!1);let me=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),at=di(_);if(vt==="auto"&&!U.current&&!me&&!at){U.current=!0;let x=Ke(_);try{if(await Ln.current(F,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>x,sessionId:N||F.id}),$)return;await x,$||lt(!1);return}catch{if($)return;await x,$||lt(!1);return}}await Ke(_),$||lt(!1)}catch(X){if($)return;ee&&B({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"}),X instanceof Me.FloPayError?!ee&&!qc(X)&&ci(L,o,Re,"NETWORK_REQUEST_FAILED","session_read"):ci(L,o,Re,"INTERNAL_SDK_ERROR","checkout_mount");let _=X instanceof Me.FloPayError?X:new Me.FloPayError(X instanceof Error?X.message:"Failed to initialize checkout","api_error");gn(_),lt(!1)}}async function Ke(ee){let{publishableKey:X,paypalPublishableKey:_}=pa(ee);dn.current={publishableKey:X,paypalPublishableKey:_};let{flopay:F,paypalFlopay:Z}=await ma({publishableKey:X,paypalPublishableKey:_,billingApiUrl:L,locale:l,telemetry:o});Qe.current=F,Ue(F),te.current=Z,ot(Z)}return re(),()=>{$=!0}},[w,Cn,Nn,jt,t]);let pn=(0,I.useCallback)(async()=>{if(!(Lt||!b)){He(!0),Pt(null);try{await _n(b,{attempt3DS:!0,fallbackToFull:!0,sessionId:N||b.id})}finally{He(!1)}}},[N,Lt,_n,b]),Mt=mi(se),mr=di(se),yr=(0,I.useMemo)(()=>{if(!(!se||!b||!se.data.stripe?.publishableKey))return{billingApiUrl:L}},[se,b,L]),fr=!!(n&&!Pe&&pe==="buttons"&&ae&&Nn==="full"),Mn=(0,I.useMemo)(()=>({session:b,loading:Yt,error:Nt,checkoutMode:In,inlineSessionDraft:wt,applyInlineSessionPatch:fr?Xn:void 0,inlineSessionPatchProcessing:Xt,claimPending:xt,claimRequiresIdentity:St,claimBuyerIdentity:$e}),[b,Yt,Nt,In,wt,fr,Xn,Xt,xt,St,$e]),Zn=!!n&&pe==="buttons"&&!mr&&(!j||!yr),Kt=on?(0,R.jsx)(jn,{status:on,errorMessage:bn,authorized:Jt}):null;if(Yt){if(c)return(0,R.jsxs)(R.Fragment,{children:[c,Kt]});if(pe==="buttons"){let $=Se?.buttonsLayout?.cardButton?.borderRadius??Se?.appearance.variables?.borderRadius??8,V=ne=>(0,R.jsx)("div",{style:{height:ne,borderRadius:$,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return(0,R.jsxs)(R.Fragment,{children:[(0,R.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[D&&V(Lr),he&&(S||le)&&V(Lr),he&&V(Lr),(0,R.jsx)("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),Kt]})}return(0,R.jsxs)(R.Fragment,{children:[(0,R.jsxs)("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[(0,R.jsx)("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),(0,R.jsx)("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),Kt]})}return Nt?y?(0,R.jsx)(tr.Provider,{value:Mn,children:y(Nt)}):(0,R.jsx)(tr.Provider,{value:Mn,children:(0,R.jsx)("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:Nt.message})}):Zn?(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(tr.Provider,{value:Mn,children:(0,R.jsx)(Gc,{onButtonClick:Be,showPayPal:D,showStripe:he,showApplePay:S,showGooglePay:le,theme:oe,buttonsTheme:ce,buttonsStyles:Ve,cardButtonContent:de,cardBackButtonContent:Tt,cardTitleContent:Ge})}),Kt]}):mr&&b&&Mt?(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(tr.Provider,{value:Mn,children:(0,R.jsxs)("div",{className:_e,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[ft&&(0,R.jsx)(to,{icon:!1,children:ft}),Et==="retrying"&&(0,R.jsx)("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),Et==="exhausted"&&(0,R.jsxs)("div",{role:"alert",children:[(0,R.jsx)("div",{children:"PayPal is temporarily unavailable. Please try again."}),(0,R.jsx)("button",{type:"button",onClick:Rr,children:"Retry PayPal"})]}),xt?c??(0,R.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,R.jsx)("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})}):Et!=="exhausted"&&(0,R.jsx)("div",{"aria-hidden":Et==="retrying"?!0:void 0,style:Et==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:(0,R.jsx)(ds,{sessionId:N,nonce:b.clientSecret||void 0,billingApiUrl:L,email:b.customer?.email||wt?.account?.email,billingName:[b.customer?.firstName,b.customer?.lastName].filter(Boolean).join(" ")||[wt?.account?.firstName,wt?.account?.lastName].filter(Boolean).join(" ")||void 0,onBuyerIdentityReady:$e,clientId:Mt.clientId,environment:Mt.environment,currency:(b.currency??"usd").toUpperCase(),isSubscription:b.mode==="subscription",providerObjectType:Mt.providerObjectType,onComplete:m,onErrorChange:Pt,onDecline:f,onButtonClick:Be,onInitializationStateChange:Ir,allowAutomaticRetry:ur===0,session:b,telemetry:o,telemetryContext:Re,onInstrument:Je,debug:q},`${z}:paypal-init-${ur}`)})]})}),Kt]}):!j||!yr?(0,R.jsx)(R.Fragment,{children:Kt}):In==="confirm"?(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(tr.Provider,{value:Mn,children:(0,R.jsx)(To,{flopay:j,paypalFlopay:fe,options:yr,onInstrument:Je,children:(0,R.jsxs)("div",{className:_e,children:[ft&&(0,R.jsx)("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:ft}),be?be({onConfirm:pn,isProcessing:Lt}):(0,R.jsx)("button",{type:"button",onClick:pn,disabled:Lt,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:Lt?"not-allowed":"pointer",opacity:Lt?.6:1},children:Lt?"Processing...":ue??"Confirm Purchase"})]})},z)}),Kt]}):(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(tr.Provider,{value:Mn,children:(0,R.jsx)(To,{flopay:j,paypalFlopay:fe,options:yr,onInstrument:Je,children:Pe?(0,R.jsxs)(R.Fragment,{children:[ft&&(0,R.jsx)("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:ft}),(0,R.jsx)(Wc,{sessionId:N,nonce:b?.clientSecret||void 0,billingApiUrl:L,session:b,children:Pe})]}):(0,R.jsx)(va,{sessionId:N,nonce:b?.clientSecret||void 0,email:b?.customer?.email||wt?.account?.email,userId:b?.customer?.id||wt?.account?.userId,firstName:b?.customer?.firstName||wt?.account?.firstName,lastName:b?.customer?.lastName||wt?.account?.lastName,totalAmount:b?Math.round((0,Me.buildCheckoutDisplayData)(b).total*100):0,currency:b?.currency?.toLowerCase()??"usd",onComplete:m,onError:p,onDecline:f,error:ft,onErrorChange:Pt,showPayPal:D,showStripe:he,enabledPaymentMethods:H??se?.data.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:se?.data.stripe?.enabledPaymentMethodCountries,showApplePay:S,showGooglePay:le,layout:pe,theme:oe,buttonsTheme:ce,buttonsStyles:Ve,appearance:rt,cardButtonContent:de,cardBackButtonContent:Tt,cardTitleContent:Ge,onButtonClick:Be,onBeforeButtonClick:ae,onBuyerIdentityReady:$e,enableAVS:ie,...O?{cardFieldOrder:O}:{},...Le?{cardPreFormSlot:Le}:{},avsLayout:Oe,country:b?.customer?.country,city:b?.customer?.city,state:b?.customer?.state,onCountryChange:P,onZipChange:A,avsCheck:!!ie,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:pi(Pe,pe),className:_e,directPaypal:mi(se),isSubscription:b?.mode==="subscription",session:b,dataAttachmentPending:xt,dataAttachmentRequiresIdentity:St,debug:q})},z)}),Kt]})}function Wc({sessionId:e,nonce:t,billingApiUrl:n,session:r,children:o}){return(0,R.jsx)(R.Fragment,{children:I.default.Children.map(o,a=>{if(!I.default.isValidElement(a))return a;let l=a.props,c={};return l.sessionId||(c.sessionId=e),!l.nonce&&t&&(c.nonce=t),l.billingApiUrl||(c.billingApiUrl=n),r?.customer&&(l.email||(c.email=r.customer.email),l.userId||(c.userId=r.customer.id),l.firstName||(c.firstName=r.customer.firstName),l.lastName||(c.lastName=r.customer.lastName)),Object.keys(c).length===0?a:I.default.cloneElement(a,c)})})}function Gc({onButtonClick:e,showPayPal:t,showStripe:n=!0,showApplePay:r,showGooglePay:o,theme:a,buttonsTheme:l,buttonsStyles:c,cardButtonContent:y,cardBackButtonContent:m,cardTitleContent:p}){let[g,f]=(0,I.useState)(!1),P=(0,I.useMemo)(()=>(0,Me.resolveTheme)(a),[a]),A=(0,I.useMemo)(()=>{let S=P?.buttonsLayout??(0,Me.resolveButtonsLayoutTheme)(l);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},[P,l,c]),D=P?.buttonsLayout?.cardButton?.borderRadius??P?.appearance.variables?.borderRadius??8,he=S=>(0,R.jsx)("div",{style:{height:S,borderRadius:D,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),H=y===void 0?{boxSizing:"border-box",height:Lr,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(g){let S=A.cardInputBorder??"#e5e7eb",le=A.cardInputBackground??"white",q=Kr(m),pe=Kr(p);return(0,R.jsxs)("div",{style:{backgroundColor:A.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",...A.cardFormContainer},children:[(0,R.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,R.jsxs)("button",{type:"button",onClick:()=>f(!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",...A.backButton},children:[(0,R.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...A.backButtonIcon},children:(0,R.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,R.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,R.jsx)(Gr,{content:m})]}),pe?(0,R.jsx)("div",{style:{flex:1}}):(0,R.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...A.title},children:(0,R.jsx)(Po,{content:p})})]}),(0,R.jsx)("div",{style:{backgroundColor:le,border:`1px solid ${S}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:(0,R.jsx)("div",{style:{width:"60%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,R.jsxs)("div",{style:{display:"flex"},children:[(0,R.jsx)("div",{style:{flex:1,backgroundColor:le,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${S}`,borderLeft:`1px solid ${S}`,borderBottomLeftRadius:8,padding:12,height:45},children:(0,R.jsx)("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,R.jsx)("div",{style:{flex:1,backgroundColor:le,borderTop:"none",borderRight:`1px solid ${S}`,borderBottom:`1px solid ${S}`,borderLeft:`1px solid ${S}`,borderBottomRightRadius:8,padding:12,height:45},children:(0,R.jsx)("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),(0,R.jsx)("div",{style:{backgroundColor:le,border:`1px solid ${S}`,borderRadius:8,marginTop:8,padding:12,height:45},children:(0,R.jsx)("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,R.jsx)("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",...A.submitButton,opacity:.5}}),(0,R.jsx)("style",{children:`
41
41
  @keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }
42
42
  @keyframes flopay-interim-expand {
43
43
  0% { opacity: 0; max-height: 0; transform: translateY(-12px); }
44
44
  40% { opacity: 1; }
45
45
  100% { opacity: 1; max-height: 600px; transform: translateY(0); }
46
46
  }
47
- `})]})}return(0,k.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&ge(Dr),n&&(r||o)&&ge(Dr),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)(Kr,{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"),gc=44;function zs(e){return new Promise(t=>setTimeout(t,e))}function hc(e,t){return e instanceof Kn.FloPayError?e:new Kn.FloPayError(e instanceof Error?e.message:t,"api_error")}function vc(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function bc(e){if(e.createSession)return{...e.createSession,checkoutMode:"auto"};if(!e.clientId||!e.account||!e.successUrl||!e.cancelUrl)return null;let t=e.products!=null;return{clientId:e.clientId,products:e.products,items:t?void 0:e.items,subscriptions:t?void 0:e.subscriptions,account:e.account,successUrl:e.successUrl,cancelUrl:e.cancelUrl,couponCodes:e.couponCodes,tagsData:e.tagsData,utmMetadata:e.utmMetadata,checkoutMode:"auto"}}function Us({sessionId:e,nonce:t,createSession:n,paymentMethodId:r,checkoutMethod:o,clientId:i,products:d,items:c,subscriptions:v,account: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:Pe=!1,type:Rt="button",style:$e,...Ae}){let Be=(0,Ve.useMemo)(()=>(0,Kn.resolveBillingApiUrl)(N),[N]),le=(0,Ve.useMemo)(()=>bc({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,Ie]=(0,Ve.useState)(null),[ve,x]=(0,Ve.useState)(!1),[Q,Se]=(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"&&Se(null)};return window.addEventListener("keydown",R),()=>{window.removeEventListener("keydown",R)}},[]);let ie=(0,Ve.useCallback)((R,A=xo)=>{Ge.current?.(Qt(A,R,{code:R.code,declineCode:R.declineCode}))},[]),Y=(0,Ve.useCallback)(async R=>{ue.current&&(Ie(null),x(R.result.status==="authorized"),De("success"),await zs(1200),ue.current&&nt(()=>rt.current?.(R)))},[]),$=(0,Ve.useCallback)(async(R,A)=>{ue.current&&(gt.current?.(R),A?.emitDecline&&ie(R,A.method),Ie(R.message),x(!1),De("error"),await zs(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(Yr(Je)){await Y({result:Mr(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 Ca.PaymentAPI(Be).waitForCheckoutSessionCompletion(R.autoProcessingPending.sessionId,{initialDelayMs:R.autoProcessingPending.retryAfterMs})).data.session;if(!Yr(Gt))throw Go(Gt);await Y({result:Mr(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 ms({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 kr({type:jt.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:jt.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:R.autoProcessingError.checkoutMethod});let Lt=(await new Ca.PaymentAPI(Be).waitForCheckoutSessionCompletion(A,{initialDelayMs:0,nonce:Yt})).data.session;if(!Yr(Lt))throw kr({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:R.autoProcessingError.checkoutMethod});await Y({result:Mr(Lt,A),session:Lt,sessionId:Lt.id||A,autoCompleted:!1});return}throw kr(R.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:R.autoProcessingError.checkoutMethod})}if(ht?.fromCreateSession&&R.autoProcessingAttempted===!0)throw kr({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let fn=await oo({billingApiUrl:Be,sessionId:A??Je.id,session:Je,nonce:Yt});if(fn.type!=="success")throw kr({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=Mo(fn),jt=Je.id||A;await $(L,{emitDecline:!0,method:L.checkoutMethod??xo}),vc(L,jt)&&jt&&ue.current&&Se({sessionId:jt,errorMessage:L.message,nonce:Yt||void 0})}},[t,Be,$,Y]),Qe=(0,Ve.useCallback)(async R=>{if(Ae.onClick?.(R),!(R.defaultPrevented||Pe||ae)){if(Se(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),Ie(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),Ie(null));return}D(!0),Ie(null),x(!1),De("processing");try{let A=new Ca.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 $(hc(A,"Automatic payment failed. Please try again."))}finally{ue.current&&(De(null),Ie(null),D(!1))}}},[Ae.onClick,le,Pe,ae,t,Ue,Be,e,$,Y]),ye=(0,Ve.useCallback)(R=>{let A=ze.current;Se(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]),Re=(0,Ve.useMemo)(()=>{let R=h?.appearance;return S?R?{...R,...S,variables:{...R.variables,...S.variables}}:S:R},[S,h]),O=Re?.variables,Le=O?.colorPrimary??"#4A49FF",Te=O?.colorPrimaryHover??io(Le,.12),pt=O?.borderRadius??"8px";return(0,rr.jsxs)(rr.Fragment,{children:[(0,rr.jsx)("button",{...Ae,type:Rt,onClick:Qe,disabled:Pe||ae,"aria-busy":ae,style:{width:"100%",...Ke===void 0?{boxSizing:"border-box",height:gc,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...tt.cardButton,...oi({themeBundle:h,resolvedPrimaryColor:Le,resolvedBorderRadius:pt,submitButtonStyle:tt.submitButton,explicitPrimaryColor:O?.colorPrimary}),fontSize:tt.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:Pe||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:Pe||ae?.6:1,...$e},onMouseEnter:R=>{Ae.onMouseEnter?.(R),!R.defaultPrevented&&!Pe&&!ae&&(h||O?.colorPrimary)&&(R.currentTarget.style.backgroundColor=Te)},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)(Kr,{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&&Se(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)(ba,{sessionId:Q.sessionId,nonce:Q.nonce,checkoutMode:"full",billingApiUrl:Be,locale:ge,theme:V,...Re?{appearance:Re}:{},buttonsTheme:se,buttonsStyles:q,initialErrorMessage:Q.errorMessage,cardTitleContent:null,onComplete:ye,onError:ot,onDecline:ne})})})]})}var Pa=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 qs(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 $s({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),Pe=(0,It.useMemo)(()=>{if(typeof o=="object")return o;let te=(0,Bn.resolveTheme)(o);if(te)return ua({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,Ie=new Pa.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 Ie.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 Ie.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 Pa.PciVaultCardCapture({sessionId:e,operation:"card_setup",telemetry:r}))}catch(ve){if(!te)return;let x=qs(ve);D.current=!0,S(x),nt(()=>$e.current?.(x))}})(),()=>{te=!1,Ie.destroy()}},[n,t,e,r]),(0,It.useEffect)(()=>{if(!I)return;let te=!1;Ke.current=!1,he.current=!1;let Ie=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(Se=>setTimeout(Se,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(Se=>setTimeout(Se,1500)),te||q(null)))()});return()=>{te=!0,Ie(),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)(ao,{capture:I,html:N.html,messageToken:N.messageToken,expectedOrigin:N.expectedOrigin,theme:Pe,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 Ie=qs(new Error(te),{code:"card_setup_widget_failed",retryable:!0});nt(()=>$e.current?.(Ie))}})]})}0&&(module.exports={DirectPayPalButton,FloPayAutomaticPaymentButton,FloPayCardSetup,FloPayCardSetupError,FloPayCheckout,FloPayProvider,SplitCardForm,VaultCardFields,dropThirdPartyOnlyError,useCheckout,useFloPay,usePayPalFloPay});
47
+ `})]})}return(0,R.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&he(Lr),n&&(r||o)&&he(Lr),n&&(0,R.jsx)("button",{type:"button",onClick:()=>{e?.("card"),f(!0)},style:{width:"100%",...H,backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:"8px",fontSize:A.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,...A.cardButton},onMouseDown:S=>{S.currentTarget.style.transform="scale(0.985)"},onMouseUp:S=>{S.currentTarget.style.transform="scale(1)"},children:(0,R.jsx)(Wr,{content:y})}),(0,R.jsx)("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}var rr=require("react/jsx-runtime"),Yc=44;function Zs(e){return new Promise(t=>setTimeout(t,e))}function Jc(e,t){return e instanceof Hn.FloPayError?e:new Hn.FloPayError(e instanceof Error?e.message:t,"api_error")}function Xc(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function Zc(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 Qs({sessionId:e,nonce:t,createSession:n,paymentMethodId:r,checkoutMethod:o,clientId:a,products:l,items:c,subscriptions:y,account:m,successUrl:p,cancelUrl:g,couponCodes:f,tagsData:P,utmMetadata:A,billingApiUrl:D,locale:he,theme:H,appearance:S,buttonsTheme:le,buttonsStyles:q,onSuccess:pe,onError:oe,onDecline:ce,children:Ve,disabled:de=!1,type:Tt="button",style:Ge,...Ae}){let Be=(0,je.useMemo)(()=>(0,Hn.resolveBillingApiUrl)(D),[D]),ae=(0,je.useMemo)(()=>Zc({createSession:n,clientId:a,products:l,items:c,subscriptions:y,account:m,successUrl:p,cancelUrl:g,couponCodes:f,tagsData:P,utmMetadata:A}),[m,g,a,f,n,l,c,y,p,P,A]),[ie,O]=(0,je.useState)(!1),[Le,Oe]=(0,je.useState)(null),[_e,ze]=(0,je.useState)(null),[Pe,w]=(0,je.useState)(!1),[ue,be]=(0,je.useState)(null),Y=(0,je.useRef)(!0),L=(0,je.useRef)(null),Se=(0,je.useRef)(ue),rt=(0,je.useRef)(pe),ht=(0,je.useRef)(oe),Ye=(0,je.useRef)(ce);(0,je.useEffect)(()=>{Se.current=ue},[ue]),(0,je.useEffect)(()=>{rt.current=pe},[pe]),(0,je.useEffect)(()=>{ht.current=oe},[oe]),(0,je.useEffect)(()=>{Ye.current=ce},[ce]),(0,je.useEffect)(()=>(Y.current=!0,()=>{Y.current=!1,L.current?.abort()}),[]),(0,je.useEffect)(()=>{if(typeof window>"u")return;let E=B=>{B.key==="Escape"&&be(null)};return window.addEventListener("keydown",E),()=>{window.removeEventListener("keydown",E)}},[]);let se=(0,je.useCallback)((E,B=Mo)=>{Ye.current?.(Qt(B,E,{code:E.code,declineCode:E.declineCode}))},[]),J=(0,je.useCallback)(async E=>{Y.current&&(ze(null),w(E.result.status==="authorized"),Oe("success"),await Zs(1200),Y.current&&nt(()=>rt.current?.(E)))},[]),j=(0,je.useCallback)(async(E,B)=>{Y.current&&(ht.current?.(E),B?.emitDecline&&se(E,B.method),ze(E.message),w(!1),Oe("error"),await Zs(1500))},[se]),Ue=(0,je.useCallback)(async(E,B,bt)=>{let Je=E.data.session??null;if(!Je)throw new Hn.FloPayError("No session data returned","api_error");let Gt=Je.clientSecret||t;if(Jr(Je)){await J({result:Mr(Je,B),session:Je,sessionId:Je.id||B,autoCompleted:!1});return}if(Je.status==="expired")throw Jo(Je);try{if(E.autoProcessingPending){let Yt=(await new ka.PaymentAPI(Be).waitForCheckoutSessionCompletion(E.autoProcessingPending.sessionId,{initialDelayMs:E.autoProcessingPending.retryAfterMs})).data.session;if(!Jr(Yt))throw Zo(Yt);await J({result:Mr(Yt,B),session:Yt,sessionId:Yt.id||B,autoCompleted:!1});return}if(E.autoProcessingError){if(E.autoProcessingError.type==="3ds_required"&&E.autoProcessingError.nextActionRedirectUrl&&B&&Gt){let N=new AbortController;L.current=N;let jt;try{jt=await hs({billingApiUrl:Be,sessionId:B,nonce:Gt,nextActionRedirectUrl:E.autoProcessingError.nextActionRedirectUrl,signal:N.signal})}finally{L.current===N&&(L.current=null)}if(jt.status==="declined")throw kr({type:jt.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:jt.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:E.autoProcessingError.checkoutMethod});let Nt=(await new ka.PaymentAPI(Be).waitForCheckoutSessionCompletion(B,{initialDelayMs:0,nonce:Gt})).data.session;if(!Jr(Nt))throw kr({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:E.autoProcessingError.checkoutMethod});await J({result:Mr(Nt,B),session:Nt,sessionId:Nt.id||B,autoCompleted:!1});return}throw kr(E.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:E.autoProcessingError.checkoutMethod})}if(bt?.fromCreateSession&&E.autoProcessingAttempted===!0)throw kr({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let fn=await io({billingApiUrl:Be,sessionId:B??Je.id,session:Je,nonce:Gt});if(fn.type!=="success")throw kr({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await J({result:fn.result,session:Je,sessionId:Je.id||B,autoCompleted:!1})}catch(fn){let N=Ao(fn),jt=Je.id||B;await j(N,{emitDecline:!0,method:N.checkoutMethod??Mo}),Xc(N,jt)&&jt&&Y.current&&be({sessionId:jt,errorMessage:N.message,nonce:Gt||void 0})}},[t,Be,j,J]),Qe=(0,je.useCallback)(async E=>{if(Ae.onClick?.(E),!(E.defaultPrevented||de||ie)){if(be(null),e&&ae){let B=new Hn.FloPayError("Provide either sessionId or create-session props, not both.","validation_error");await j(B),Y.current&&(Oe(null),ze(null));return}if(!e&&!ae){let B=new Hn.FloPayError("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await j(B),Y.current&&(Oe(null),ze(null));return}O(!0),ze(null),w(!1),Oe("processing");try{let B=new ka.PaymentAPI(Be);if(e){let bt=await B.getUnifiedCheckoutSession(e,t);await Ue(bt,e);return}try{let bt=await B.createAndFetchSession({...ae});await Ue(bt,bt.data.session?.id??null,{fromCreateSession:!0})}catch(bt){if(Xo(bt)==="session_auto_completed"){await J({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw bt}}catch(B){await j(Jc(B,"Automatic payment failed. Please try again."))}finally{Y.current&&(Oe(null),ze(null),O(!1))}}},[Ae.onClick,ae,de,ie,t,Ue,Be,e,j,J]),fe=(0,je.useCallback)(E=>{let B=Se.current;be(null),rt.current?.({result:E,session:null,sessionId:B?.sessionId??null,autoCompleted:!1})},[]),ot=(0,je.useCallback)(E=>{ht.current?.(E)},[]),te=(0,je.useCallback)(E=>{Ye.current?.(E)},[]),b=(0,je.useMemo)(()=>(0,Hn.resolveTheme)(H),[H]),tt=(0,je.useMemo)(()=>{let E=b?.buttonsLayout??(0,Hn.resolveButtonsLayoutTheme)(le);return q?{...E,...q,cardButton:{...E.cardButton,...q.cardButton}}:E},[b,le,q]),Ie=(0,je.useMemo)(()=>{let E=b?.appearance;return S?E?{...E,...S,variables:{...E.variables,...S.variables}}:S:E},[S,b]),z=Ie?.variables,Fe=z?.colorPrimary??"#4A49FF",Te=z?.colorPrimaryHover??lo(Fe,.12),mt=z?.borderRadius??"8px";return(0,rr.jsxs)(rr.Fragment,{children:[(0,rr.jsx)("button",{...Ae,type:Tt,onClick:Qe,disabled:de||ie,"aria-busy":ie,style:{width:"100%",...Ve===void 0?{boxSizing:"border-box",height:Yc,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...tt.cardButton,...li({themeBundle:b,resolvedPrimaryColor:Fe,resolvedBorderRadius:mt,submitButtonStyle:tt.submitButton,explicitPrimaryColor:z?.colorPrimary}),fontSize:tt.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:de||ie?"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:de||ie?.6:1,...Ge},onMouseEnter:E=>{Ae.onMouseEnter?.(E),!E.defaultPrevented&&!de&&!ie&&(b||z?.colorPrimary)&&(E.currentTarget.style.backgroundColor=Te)},onMouseLeave:E=>{Ae.onMouseLeave?.(E),!E.defaultPrevented&&(b||z?.colorPrimary)&&(E.currentTarget.style.backgroundColor=Fe)},onMouseDown:E=>{Ae.onMouseDown?.(E),E.defaultPrevented||(E.currentTarget.style.transform="scale(0.985)")},onMouseUp:E=>{Ae.onMouseUp?.(E),E.defaultPrevented||(E.currentTarget.style.transform="scale(1)")},children:(0,rr.jsx)(Wr,{content:Ve})}),Le&&(0,rr.jsx)(jn,{status:Le,errorMessage:_e,authorized:Pe}),ue&&(0,rr.jsx)("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:E=>{E.target===E.currentTarget&&be(null)},style:{position:"fixed",inset:0,background:"rgba(0, 0, 0, 0.45)",display:"flex",alignItems:"center",justifyContent:"center",padding:"1.5rem",zIndex:1100},children:(0,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)(wa,{sessionId:ue.sessionId,nonce:ue.nonce,checkoutMode:"full",billingApiUrl:Be,locale:he,theme:H,...Ie?{appearance:Ie}:{},buttonsTheme:le,buttonsStyles:q,initialErrorMessage:ue.errorMessage,cardTitleContent:null,onComplete:fe,onError:ot,onDecline:te})})})]})}var Ia=require("@flopay/js/card-setup"),Bn=require("@flopay/shared"),pt=require("react");var el={light:{success:"#166534",error:"#991B1B"},dark:{success:"#4ADE80",error:"#FCA5A5"}};function tl(e){let t=e.appearance.variables??{},n=e.buttonsLayout.cardFormContainer??{},r=e.appearance.theme==="night",o=r?el.dark:el.light,a=t.colorText??(r?"#F1F5F9":"#262833"),l=e.appearance.rules?.[".Label"];return{panel:{...n.background===void 0?{}:{background:n.background},...n.backgroundColor===void 0?{}:{backgroundColor:n.backgroundColor},...n.border===void 0?{}:{border:n.border},...n.borderRadius===void 0?{}:{borderRadius:n.borderRadius},...n.boxShadow===void 0?{}:{boxShadow:n.boxShadow},color:a,...t.fontFamily?{fontFamily:t.fontFamily}:{}},spinnerTrackColor:e.buttonsLayout.cardInputBorder??(r?"#374151":"#e5e7eb"),spinnerAccentColor:t.colorPrimary??"#4A49FF",labelColors:{processing:a,success:o.success,error:o.error},noteColor:l?.color??a}}var dr=require("react/jsx-runtime"),zo=class extends Bn.FloPayError{constructor(t,n,r){super(t,n,r),this.name="FloPayCardSetupError",this.retryable=r.retryable}};function nl(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 zo(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 rl({sessionId:e,nonce:t,billingApiUrl:n,telemetry:r,theme:o="modern-light",containerStyle:a,loading:l=null,onReady:c,onComplete:y,onDecline:m,onCancel:p,onValidation:g,onError:f}){let[P,A]=(0,pt.useState)(null),[D,he]=(0,pt.useState)(null),[H,S]=(0,pt.useState)(null),[le,q]=(0,pt.useState)(null),[pe,oe]=(0,pt.useState)(null),ce=(0,pt.useRef)(!1),Ve=(0,pt.useRef)(!1),de=(0,pt.useMemo)(()=>typeof o=="object"?void 0:(0,Bn.resolveTheme)(o),[o]),Tt=(0,pt.useMemo)(()=>typeof o=="object"?o:de?fa({appearance:de.appearance,buttonsStyles:de.buttonsLayout,layout:"default"}):null,[de,o]),Ge=(0,pt.useMemo)(()=>Ps(de?.buttonsLayout.cardFormContainer,a),[de,a]),Ae=(0,pt.useMemo)(()=>de?tl(de):void 0,[de]),Be=(0,pt.useRef)(c),ae=(0,pt.useRef)(f),ie=(0,pt.useRef)(y),O=(0,pt.useRef)(m),Le=(0,pt.useRef)(p),Oe=(0,pt.useRef)(g),_e=(0,pt.useRef)(!1),ze=(0,pt.useRef)(!1),Pe=(0,pt.useRef)(0);return Be.current=c,ae.current=f,ie.current=y,O.current=m,Le.current=p,Oe.current=g,(0,pt.useEffect)(()=>{let w=Pe.current+1;return Pe.current=w,()=>{queueMicrotask(()=>{Pe.current===w&&(_e.current||ze.current||(ze.current=!0,nt(()=>{Le.current?.({status:"cancelled",sessionId:e})})))})}},[e]),(0,pt.useEffect)(()=>{let w=!0,ue=new Ia.PaymentAPI((0,Bn.resolveBillingApiUrl)(n),{telemetry:r});return A(null),he(null),S(null),_e.current=!1,ze.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 be=await ue.getUnifiedCheckoutSession(e,t);if(!w)return;let Y=be.data.session;if(!Y||!(0,Bn.isCardSetupCheckoutSession)(Y))throw new Bn.FloPayError("FloPayCardSetup only accepts a zero-amount, productless setup session.","validation_error",{code:"InvalidCardSetupSession",param:"sessionId"});let L=Y.vault;if(L?.html?.trim()||(L=await ue.getVaultCapture(e,t)),!L.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(!w)return;he(L),A(new Ia.PciVaultCardCapture({sessionId:e,operation:"card_setup",telemetry:r}))}catch(be){if(!w)return;let Y=nl(be);_e.current=!0,S(Y),nt(()=>ae.current?.(Y))}})(),()=>{w=!1,ue.destroy()}},[n,t,e,r]),(0,pt.useEffect)(()=>{if(!P)return;let w=!1;Ve.current=!1,ce.current=!1;let ue=P.on("submitting",()=>{ce.current=!0,oe(null),q("processing")}),be=P.on("complete",L=>{_e.current=!0,ce.current=!1,q("success"),(async()=>(await new Promise(Se=>setTimeout(Se,1200)),!Ve.current&&(Ve.current=!0,nt(()=>{ie.current?.({status:"succeeded",sessionId:e,...L.paymentMethod?{paymentMethod:L.paymentMethod}:{}})}),w||q(null))))()}),Y=P.on("decline",L=>{_e.current=!0,ce.current=!1,oe(L.message??null),q("error"),nt(()=>{O.current?.({status:"declined",sessionId:e,...L.declineReason?{reason:L.declineReason}:{},...L.message?{message:L.message}:{}})}),(async()=>(await new Promise(Se=>setTimeout(Se,1500)),w||q(null)))()});return()=>{w=!0,ue(),be(),Y()}},[P,e]),H?(0,dr.jsx)("div",{role:"alert",children:H.message}):!P||!D?.html?(0,dr.jsx)(dr.Fragment,{children:l}):(0,dr.jsxs)(dr.Fragment,{children:[le&&(0,dr.jsx)(jn,{status:le,errorMessage:pe,processingLabel:"SAVING CARD...",successLabel:"CARD SAVED",errorLabel:"CARD NOT SAVED",successNote:null,...Ae?{theme:Ae}:{}}),(0,dr.jsx)(so,{capture:P,html:D.html,messageToken:D.messageToken,expectedOrigin:D.expectedOrigin,theme:Tt,containerStyle:Ge,onReady:()=>{nt(()=>Be.current?.())},onValidation:w=>{nt(()=>Oe.current?.(w))},onError:w=>{if(!w)return;ce.current&&(ce.current=!1,oe(w),q("error"),setTimeout(()=>q(null),1500));let ue=nl(new Error(w),{code:"card_setup_widget_failed",retryable:!0});nt(()=>ae.current?.(ue))}})]})}0&&(module.exports={DirectPayPalButton,FloPayAutomaticPaymentButton,FloPayCardSetup,FloPayCardSetupError,FloPayCheckout,FloPayProvider,SplitCardForm,VaultCardFields,dropThirdPartyOnlyError,useCheckout,useFloPay,usePayPalFloPay});