@flopay/react 1.9.9 → 1.9.10

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 xl=Object.create;var Yo=Object.defineProperty;var Ml=Object.getOwnPropertyDescriptor;var Al=Object.getOwnPropertyNames;var Bl=Object.getPrototypeOf,Fl=Object.prototype.hasOwnProperty;var Dl=(e,t)=>{for(var n in t)Yo(e,n,{get:t[n],enumerable:!0})},Ji=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Al(t))!Fl.call(e,o)&&o!==n&&Yo(e,o,{get:()=>t[o],enumerable:!(r=Ml(t,o))||r.enumerable});return e};var Xi=(e,t,n)=>(n=e!=null?xl(Bl(e)):{},Ji(t||!e||!e.__esModule?Yo(n,"default",{value:e,enumerable:!0}):n,e)),Nl=e=>Ji(Yo({},"__esModule",{value:!0}),e);var dd={};Dl(dd,{DirectPayPalButton:()=>Eo,FloPayAutomaticPaymentButton:()=>il,FloPayCardSetup:()=>dl,FloPayCardSetupError:()=>zo,FloPayCheckout:()=>Pa,FloPayProvider:()=>To,SplitCardForm:()=>ha,VaultCardFields:()=>so,dropThirdPartyOnlyError:()=>ul.dropThirdPartyOnlyError,useCheckout:()=>ls,useFloPay:()=>hr,usePayPalFloPay:()=>Qo});module.exports=Nl(dd);var ul=require("@flopay/shared");var Sa=require("@flopay/js"),Un=require("@flopay/shared"),Ke=require("react");var It=require("react/jsx-runtime");function Ll(){return(0,It.jsxs)(It.Fragment,{children:[(0,It.jsxs)("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,It.jsx)("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),(0,It.jsx)("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",(0,It.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"#9ca3af",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{position:"absolute",right:"1rem"},"aria-hidden":"true",children:(0,It.jsx)("path",{d:"M9 18l6-6-6-6"})})]})}function Ol(){return(0,It.jsx)(It.Fragment,{children:"Go back"})}function zl(){return(0,It.jsx)(It.Fragment,{children:"Secure card checkout"})}function Hr(e){return e!==void 0&&(e===""||e===null||e===!1)}function Wr({content:e}){return(0,It.jsx)(It.Fragment,{children:e===void 0?(0,It.jsx)(Ll,{}):e})}function Gr({content:e}){return(0,It.jsx)(It.Fragment,{children:e===void 0?(0,It.jsx)(Ol,{}):e})}function Po({content:e}){return(0,It.jsx)(It.Fragment,{children:e===void 0?(0,It.jsx)(zl,{}):e})}var Bt=require("@flopay/shared"),Ul="Checkout is temporarily unavailable. Please try again later.";function Ua(e){return{errorCode:"PROVIDER_LOAD_FAILED",failureCategory:e instanceof Bt.FloPayError&&e.type==="authentication_error"?"invalid_response":"provider_runtime",stage:"provider_load",provider:"stripe",requestCategory:"provider_sdk"}}function ql(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 Zi(){return new Bt.FloPayError(Ul,"api_error",{code:"CheckoutInitializationFailed"})}function Qi(e,t,n){let r=e?.data.session,o=r?.gateways?.stripe?.enabledPaymentMethods??e?.data.stripe?.enabledPaymentMethods;return!!(n&&(r?.vault?.html||r?.gateways?.pcivault||o?.includes("card"))||t&&e?.data.paypal?.publishableKey)}function es(e,t){if(t&&(!(e instanceof Bt.FloPayError)||e.type==="authentication_error"))return Ua(e);if(!(e instanceof Bt.FloPayError&&ql(e))){if(!t&&!(e instanceof Bt.FloPayError)&&(e instanceof TypeError||e instanceof SyntaxError))return{...(0,Bt.classifyTelemetryFailure)(e,"NETWORK_REQUEST_FAILED"),stage:"session_read",requestCategory:"session_read"};if(!t&&e instanceof Bt.FloPayError)return{errorCode:"NETWORK_REQUEST_FAILED",stage:"session_read",requestCategory:"session_read"};if(!(e instanceof Bt.FloPayError))return{errorCode:"INTERNAL_SDK_ERROR",stage:"checkout_mount"}}}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,Bt.isCardHolderNamePlaceholder)(l.firstName,l.lastName);if(!(0,Bt.isValidEmail)(l.email))return Promise.reject(new Bt.FloPayError("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}));let g={};for(let[y,m]of Object.entries(l)){if(c&&y.endsWith("Name")||typeof m!="string")continue;let v=m.trim();v&&(g[y]=v)}return o=e.claimCheckoutSession(t,n,{accountData:g}),o.catch(()=>{}),o}}function ts(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 ns(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 Mr(e){if((0,Bt.isCardHolderNamePlaceholder)(e))return{};let[t,...n]=e?.trim().split(/\s+/)??[];return t?{firstName:t,lastName:n.join(" ")||void 0}:{}}function $a(e,t){return t?{...e,...t}:e}function tn(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 $l=[{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 $l)if(n.test(t))return r;return e}function Ar(e,t){return e.status!=="authorized"?{status:"succeeded"}:{status:"authorized",paymentId:e.paymentId,sessionId:e.id||t||void 0,authorizationExpiresAt:e.authorizationExpiresAt}}function Jr(e){return e?.status==="authorized"||e?.status==="complete"}function rs(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function Jo(e){let t=rs(e);return new Bt.FloPayError(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function Xo(e){return e instanceof Bt.FloPayError||typeof e=="object"&&e!==null&&"code"in e?e.code:void 0}function Zo(e){let t=rs(e),n="checkout_processing_timeout";return t?n="authorization_expired":e?.status==="expired"&&(n="checkout_session_expired"),new Bt.FloPayError(t?"Authorization has expired.":"Automatic payment failed. Please try again.","api_error",{code:n})}function So(e,t){return e==="processing"||(0,Bt.isMoneySettledOutcome)(e,t)}function os(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}function as(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 Cr=require("@flopay/js"),Fe=require("@flopay/shared"),P=Xi(require("react"),1);var ja=require("react"),Ln=(0,ja.createContext)({flopay:null,paypalFlopay:null,billingApiUrl:""}),Zn=(0,ja.createContext)({session:null,loading:!1,error:null});var na=require("@flopay/js"),Ot=require("@flopay/shared"),ms=require("@paypal/paypal-js"),A=require("react");var is=require("@flopay/shared"),Qn=require("react"),fr=require("react/jsx-runtime");function wn(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,Qn.useState)(null),n=(0,Qn.useRef)(null),r=(0,Qn.useRef)(0),o=(0,Qn.useCallback)((l,c)=>(n.current?.(null),r.current+=1,t({id:r.current,methodLabel:l,identity:c}),new Promise(g=>{n.current=g})),[]),a=(0,Qn.useCallback)(l=>{let c=n.current;n.current=null,t(null),c?.(l)},[]);return(0,Qn.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,Qn.useState)(e.email?.trim()??""),g=(0,is.isValidEmail)(l.trim());return(0,fr.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,fr.jsxs)("div",{style:{fontWeight:700},children:["Continue with ",t]}),(0,fr.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",(0,fr.jsx)("input",{type:"email",autoComplete:"email","data-testid":"flopay-email",required:!0,value:l,onChange:y=>c(y.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]}),(0,fr.jsxs)("div",{style:{display:"flex",gap:"0.5rem"},children:[r&&(0,fr.jsx)("button",{type:"button",onClick:r,style:{flex:1,minHeight:42},children:"Cancel"}),(0,fr.jsxs)("button",{type:"button",disabled:!g||o,onClick:()=>{n(wn({...e,email:l.trim()}))},style:{flex:2,minHeight:42},children:["Continue with ",t]})]})]})}function Vl(e){if(e instanceof Error)return e.message;if(typeof e=="object"&&e!==null){let t=e.message;return typeof t=="string"?t:void 0}return typeof e=="string"?e:void 0}function Br(e){if(typeof e!="string")return;let t=e.trim();return/^[a-z0-9_.-]{1,64}$/i.test(t)?t:void 0}function gr(e){if(typeof e!="object"||e===null)return;let t=e;return Br(t.code)??Br(t.type)??Br(t.name)}function Qr(e){if(!(typeof e!="object"||e===null))return Br(e.decline_code)}function ko(e){return typeof e!="object"||e===null?!1:Br(e.type)?.toLowerCase()==="card_error"||Qr(e)!==void 0}function wr(e){let t=Vl(e)?.toLowerCase()??"",r=`${gr(e)?.toLowerCase()??""} ${t}`;return r.includes("popup")&&r.includes("block")}var ss=require("@flopay/shared"),Io=require("react");function hr(){return(0,Io.useContext)(Ln).flopay}function Qo(){return(0,Io.useContext)(Ln).paypalFlopay??null}function ls(){return(0,Io.useContext)(Zn)}function cs(){return(0,Io.useContext)(Ln).billingApiUrl||(0,ss.resolveBillingApiUrl)()}var ds=require("@flopay/shared"),Dr=require("react");function Qe(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"),Fr=typeof window>"u"?ea.useEffect:ea.useLayoutEffect;var jl={"checkout.mount":"checkout_mount","sdk.initialize.ready":"sdk_loaded","provider.ready":"sdk_loaded","checkout.rendered":"form_rendered","vault.widget.ready":"form_rendered","vault.submission.started":"tokenize","payment.tokenization.started":"tokenize","payment.processing.started":"process_attempt","payment.intent.started":"process_attempt","vault.action.required":"3ds_challenge","payment.three_ds.handoff":"3ds_challenge"};function Kl(e){return e==="stripe"||e==="paypal"?e:void 0}function Hl(e){let t=Kl(e.provider),n={schemaVersion:ds.FLO_INSTRUMENT_SCHEMA_VERSION,...t?{gateway:t}:{}};if(e.class==="lifecycle"){let r=jl[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,Dr.useRef)(e);n.current=e;let r=(0,Dr.useRef)(new Set),o=(0,Dr.useRef)(t),a=(0,Dr.useRef)(t);return Fr(()=>{a.current=t,o.current!==t&&(o.current=t,r.current.clear())},[t]),(0,Dr.useCallback)(l=>{if(a.current!==t)return;let c=Hl(l);if(c){if(Ka.has(c.name)){if(r.current.has(c.name))return;r.current.add(c.name)}Qe(()=>n.current?.(c))}},[t])}var Wl=Symbol.for("@flopay/js.telemetry.bridge.v1"),Gl=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function Yl(){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 Jl(e){let t=Yl(),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[Gl];return Jl(t?.(e)??{})}function Xt(e){if(e)return e[Wl]}var gn=require("react");function Ro(e){let t=(0,gn.useRef)(0),n=(0,gn.useRef)(null),r=(0,gn.useRef)(null),o=(0,gn.useCallback)((h=r.current)=>{h?.timer&&(clearTimeout(h.timer),h.timer=null)},[]),a=(0,gn.useCallback)(h=>{o();let w=t.current+1;return t.current=w,n.current=null,r.current={generation:w,method:h,timer:null,yieldedControl:!1},w},[o]),l=(0,gn.useCallback)(h=>{let w=r.current;return h!==void 0&&w?.generation!==h?!1:(o(w),r.current=null,(h===void 0||n.current===h)&&(n.current=null),!0)},[o]),c=(0,gn.useCallback)(h=>{let w=r.current,D=h??w?.generation??t.current;(h===void 0||w?.generation===h)&&(o(w),r.current=null),n.current=D},[o]),g=(0,gn.useCallback)(h=>n.current===(h??t.current),[]),y=(0,gn.useCallback)(h=>r.current?.generation===h&&n.current!==h,[]),m=(0,gn.useCallback)(()=>{let h=r.current;h&&(h.yieldedControl=!0,o(h))},[o]),v=(0,gn.useCallback)(()=>{let h=r.current;!h?.yieldedControl||document.visibilityState!=="visible"||(o(h),h.timer=setTimeout(()=>{h.timer=null,r.current?.generation===h.generation&&(r.current=null,n.current=h.generation,e(h.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}))},600))},[o,e]);return(0,gn.useEffect)(()=>{let h=()=>{document.visibilityState==="visible"?v():m()};return document.addEventListener("visibilitychange",h),window.addEventListener("blur",m),window.addEventListener("focus",v),()=>{document.removeEventListener("visibilitychange",h),window.removeEventListener("blur",m),window.removeEventListener("focus",v),o()}},[o,m,v]),{startAttempt:a,finishAttempt:l,invalidateAttempt:c,isAttemptInvalidated:g,isAttemptCurrent:y,generationRef:t}}var On=require("react/jsx-runtime"),ra=45,Xl=1e3,Zl=11e3,Ql=["https://www.paypal.com","https://www.sandbox.paypal.com"],us="We couldn't open PayPal. Try again or choose another payment method.",ec={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 ps(e){return e.includes("No ack for postMessage init()")&&Ql.some(t=>e.includes(t))&&e.includes("10000ms")}function tc(e){return e?`${us} Allow pop-ups for this site, then try again.`:us}function nc(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 rc(e){return e>=500?"5xx":e>=400?"4xx":e>=300?"3xx":"unknown"}function ys({sessionId:e,nonce:t,billingApiUrl:n,email:r,billingName:o,onBuyerIdentityReady:a,clientId:l,environment:c,currency:g,isSubscription:y,providerObjectType:m,onTokenizedBody:v,onComplete:h,onErrorChange:w,onDecline:D,onTechnicalFailure:N,isProcessing:ye=!1,onLoadStateChange:W,onInitializationStateChange:I,allowAutomaticRetry:ie=!0,onButtonClick:q,runBeforeButtonClick:ue,session:re,existingOrderId:le,telemetry:He,telemetryContext:ce,onInstrument:Rt,debug:Ge=!1}){let Te=hr(),xe=eo(Rt,e),oe=(0,A.useMemo)(()=>{if(Te)return null;let j=ta({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:Ot.SDK_VERSION,enabled:He!==!1});return j.setCheckoutContext(ce??{}),j.beginCheckout(ce??{}),j},[n,Te,He,ce?.checkoutMode,ce?.layout]),ae=(0,A.useMemo)(()=>Xt(Te),[Te]);(0,A.useEffect)(()=>()=>{oe&&oe.flush().catch(()=>{}).finally(()=>oe.destroy())},[oe]);let z=(0,A.useMemo)(()=>({error:j=>{ae?ae.error(j):oe?.error(j),xe({class:"technical_error",errorCode:j.requestCategory==="intent_create"?"PAYMENT_PROCESSING_FAILED":j.errorCode,requestCategory:j.requestCategory,provider:j.provider})},log:j=>{ae?ae.log(j):oe?.log(j),xe({class:"lifecycle",name:j.name,provider:j.provider})},performance:j=>{ae?ae.performance(j):oe?.performance(j)},terminal:j=>{ae?ae.terminal(j):oe?.terminal(j)},startTiming:()=>ae?.now()??oe?.now()??0,elapsed:j=>ae?.elapsed(j)??Math.max(0,(oe?.now()??j)-j)}),[xe,ae,oe]),De=(0,A.useRef)(null),Ne=(0,A.useRef)(0),Ee=(0,A.useRef)(null),Oe=(0,A.useRef)(!1),[ke,k]=(0,A.useState)(!1),[de,he]=(0,A.useState)(!1),[Y,L]=(0,A.useState)(0),Ie=(0,A.useRef)(0),[tt,gt]=(0,A.useState)(!1),Ye=(0,A.useRef)(!1),ee=(0,A.useRef)(!1),[J,$]=(0,A.useState)(!1),[qe,et]=(0,A.useState)(!1),{request:ve,collect:Je,finish:te}=Xr(),V=(0,A.useRef)({sessionId:e,required:!(0,Ot.isValidEmail)(r?.trim()||re?.customer?.email?.trim())});V.current.sessionId!==e&&(V.current={sessionId:e,required:!(0,Ot.isValidEmail)(r?.trim()||re?.customer?.email?.trim())});let nt=V.current.required,B=(0,A.useMemo)(()=>n.replace(/\/+$/,""),[n]),ze=re?.gateways?.paypal?.providerObjectType??m,pe=ze??(y?"subscription":"order"),lt=ze==="order"||ze==="setup_token",ct=(0,A.useMemo)(()=>JSON.stringify([B,l,g,c??"",pe,lt,e,le??""]),[B,l,g,c,le,pe,lt,e]),T=(0,A.useRef)(ct),O=T.current!==ct,kt=(0,A.useRef)(Ge),Le=(0,A.useRef)(null),[Ut,cn]=(0,A.useState)([]),X=(0,A.useCallback)(j=>{kt.current&&cn(Se=>[...Se,`${new Date().toISOString().slice(11,23)} ${j}`])},[]);(0,A.useEffect)(()=>{kt.current=Ge,Ge&&X("debug:enabled"),Le.current?.setEnabled(Ge)},[X,Ge]);let Ft=(0,A.useRef)(v),mt=(0,A.useRef)(h),qt=(0,A.useRef)(w),Gt=(0,A.useRef)(D),$t=(0,A.useRef)(N),kn=(0,A.useRef)(q),hn=(0,A.useRef)(W),Zt=(0,A.useRef)(I),$e=(0,A.useRef)(a),ht=(0,A.useRef)(ue),Qt=(0,A.useRef)(re),Dt=(0,A.useRef)(r),nn=(0,A.useRef)(o),Vt=(0,A.useRef)(t),Ze=(0,A.useRef)(null),Yt=(0,A.useRef)(new Map),vt=(0,A.useRef)(new Map),dn=(0,A.useRef)(!1);(0,A.useEffect)(()=>(dn.current=!0,()=>{dn.current=!1}),[]),(0,A.useEffect)(()=>{Ft.current=v},[v]),(0,A.useEffect)(()=>{$e.current=a},[a]),(0,A.useEffect)(()=>{mt.current=h},[h]),(0,A.useEffect)(()=>{qt.current=w},[w]),(0,A.useEffect)(()=>{Gt.current=D},[D]),(0,A.useEffect)(()=>{$t.current=N},[N]),(0,A.useEffect)(()=>{kn.current=q},[q]),(0,A.useEffect)(()=>{hn.current=W},[W]),(0,A.useEffect)(()=>{Zt.current=I},[I]),(0,A.useEffect)(()=>{ht.current=ue},[ue]),(0,A.useEffect)(()=>{Qt.current=re},[re]),(0,A.useEffect)(()=>{Dt.current=r},[r]),(0,A.useEffect)(()=>{nn.current=o},[o]),(0,A.useEffect)(()=>{Vt.current=t},[t]),(0,A.useEffect)(()=>{Ie.current=Y},[Y]),(0,A.useEffect)(()=>{tt&&Ee.current?.focus()},[tt,Y]);let at=(0,A.useCallback)(()=>{window.setTimeout(()=>{Ee.current?.focus()},0)},[]),jt=(0,A.useCallback)(()=>{k(!1),L(j=>j+1)},[]),Jt=(0,A.useCallback)(()=>{gt(!1),(De.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??De.current)?.focus?.()},[]);(0,A.useEffect)(()=>{!ke||!Oe.current||(Oe.current=!1,Jt())},[Jt,ke,Y]);let on=(0,A.useCallback)((j,Se)=>{let an=$t.current;if(an){an("paypal",j,Se);return}qt.current?.(tc(Se?.popupBlocked??wr(j)))},[]),In=(0,A.useCallback)((j,Se,an)=>{on(Se,an),gt(!0),jt(),at()},[at,on,jt]),{finishAttempt:Kt,invalidateAttempt:Rn,isAttemptCurrent:bt,isAttemptInvalidated:_,startAttempt:Et}=Ro(In),Ct=(0,A.useCallback)(()=>(gt(!1),Et("paypal")),[Et]),Nt=(0,A.useCallback)(j=>{Rn(j?.generation),j?.showRetry&&gt(!0),j?.remount&&jt(),j?.focus!==!1&&at()},[at,Rn,jt]),en=j=>{let Se=Ze.current;return Se&&vt.current.set(j,Se),j};(0,A.useEffect)(()=>{T.current!==ct&&(T.current=ct,Ye.current=!1,ee.current=!1,k(!1),he(!1),$(!1),Zt.current?.("loading"))},[ct]),(0,A.useEffect)(()=>{Qe(()=>hn.current?.(ke&&!J))},[ke,J]);let un=(0,Ot.normalizeGatewayEnvironment)(c);(0,A.useEffect)(()=>{let j=l?`${l.slice(0,6)}\u2026(len ${l.length})`:"(empty)",Se=typeof navigator>"u"?"(no navigator)":navigator.userAgent;if(X(`mount clientId=${j} env=${c??"(unset)"}\u2192${un??"live"} ccy=${g} sub=${y}`),X(`ua=${Se.slice(0,80)}${Se.length>80?"\u2026":""}`),!l){X("FAIL: clientId empty \u2014 gateway misconfigured"),$(!0),z.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(!De.current){X("FAIL: containerRef not attached");return}Ne.current=z.startTiming(),z.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let an=!1,cr=!1,Ve=()=>an||cr,Pr,qn=!1,dt=()=>{Pr=(0,Ot.generateIdempotencyKey)(),Pr||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),qn=!0},yt=null,$n=!1,Vn=null,dr=!1,En=()=>{!Vn||dr||(dr=!0,Vn.close().catch(()=>{}))},jn=null,ur=()=>{jn!==null&&(z.log({name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal"}),z.performance({stage:"overlay_return",durationMs:z.elapsed(jn),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal"}),jn=null)},Kn=!1,Ir=!1,pn=De.current,pr=null,_n=null,vn=[],_t=null,ot=!1,Tn=!1,xn=null,sn=b=>{if(!b||typeof b.getBoundingClientRect!="function")return"(no rect)";let u=b.getBoundingClientRect();return`${Math.round(u.width)}\xD7${Math.round(u.height)}`},Fn=b=>{if(!b)return"(empty)";try{let u=new URL(b,typeof window>"u"?"https://localhost":window.location.href),C=u.pathname.toLowerCase();return C.includes("checkcaptcha")||C.includes("captcha")?`CAPTCHA(${u.host}${C})`:C.includes("risk")||C.includes("challenge")?`RISK(${u.host}${C})`:C.includes("smart/buttons")?`smart-buttons(${u.host})`:`${u.host}${C}`.slice(0,100)}catch{return b.slice(0,80)}},je=b=>{let u=b.getAttribute("src"),C=b.getAttribute("srcdoc"),U=b.getAttribute("name"),f=b.getAttribute("sandbox"),E=[];return u&&E.push(`src=${Fn(u)}`),C&&E.push(`srcdoc[${C.length}ch]`),!u&&!C&&E.push("src=(empty) srcdoc=(empty)"),U&&E.push(`name=${U.slice(0,40)}`),f!==null&&E.push(`sandbox="${f.slice(0,40)}"`),E.join(" ")},mn=b=>{if(!(b instanceof HTMLIFrameElement))return"";try{let u=b.contentDocument;if(!u)return"cd=null";let C=u.body?.children.length??0,U=u.body?.innerHTML.length??0,f=u.head?.innerHTML.length??0;return`cd=same-origin readyState=${u.readyState} body[${C}children,${U}ch] head[${f}ch]`}catch(u){return`cd=cross-origin(${u.message.slice(0,30)})`}},Tt=[],nr=b=>{if(Ve())return;let u=b.message??String(b.error??"(no message)");u&&(u.toLowerCase().includes("paypal")||u.toLowerCase().includes("zoid")||u.toLowerCase().includes("postrobot")||u.toLowerCase().includes("storage"))&&(X(`window:error ${u.slice(0,140)}`),Tt.push(u))},Rr=b=>{if(Ve())return;let u=b.reason instanceof Error?b.reason.message:String(b.reason??"(no reason)");u&&(u.toLowerCase().includes("paypal")||u.toLowerCase().includes("zoid")||u.toLowerCase().includes("postrobot")||u.toLowerCase().includes("storage"))&&(X(`window:rejection ${u.slice(0,140)}`),Tt.push(u))},mr={value:0},Hn=()=>{pr?.disconnect(),pr=null,_n?.disconnect(),_n=null;for(let b of vn.splice(0))clearTimeout(b);Tn=!1,ot&&typeof window<"u"&&(window.removeEventListener("error",nr),window.removeEventListener("unhandledrejection",Rr)),ot=!1},Wn=()=>{if(!(ot||Ve()||Kn)){if(ot=!0,Tt.length=0,mr.value=0,typeof window<"u"&&(window.addEventListener("error",nr),window.addEventListener("unhandledrejection",Rr)),typeof PerformanceObserver<"u")try{_n=new PerformanceObserver(b=>{if(!Ve())for(let u of b.getEntries()){if(!u.name.toLowerCase().includes("paypal"))continue;mr.value+=1;let C=Math.round(u.duration);X(`net ${C}ms ${u.name.slice(0,90)}`)}}),_n.observe({type:"resource",buffered:!0})}catch{}xn?.()}},Mn=()=>{_t&&(clearTimeout(_t),_t=null)},Gn=()=>{Hn(),Mn()},Er={setEnabled:b=>{b?Wn():Hn()}};Le.current=Er,kt.current&&Wn();let An=b=>{if(!b)return!1;let u=b.toLowerCase();return u.includes("zoid destroyed")||u.includes("destroyed all components")||u.includes("window closed")||u.includes("detected container element removed")},Yn=b=>{if(Ve()||An(b))return;let u=Sr(b)??b;Qe(()=>qt.current?.(u))},ln=b=>{b!==null&&z.error({errorCode:b?"PROVIDER_RUNTIME_FAILED":"PROVIDER_LOAD_FAILED",stage:b?"provider_ready":"provider_load",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime"})},rt=(b,u=!1,C=!1)=>{if(an)return;let U=Ye.current||!ie;if($n)return;$n=!0,cr=!0,Gn(),En();let f=u||ps(b);if(f&&ie&&!Ye.current){Ye.current=!0,k(!1),et(!1),he(!0),Zt.current?.("retrying"),yt=setTimeout(()=>{an||L(E=>E+1)},Xl);return}if(f||U){if(k(!1),et(!1),he(!1),$(!0),(!f||C===!0)&&ln(C),Zt.current?.("exhausted"),!ee.current){ee.current=!0;let E="paypal_init_failure";ps(b)?E="paypal_init_timeout":u&&(E="paypal_render_timeout"),console.error("[FloPay] Direct PayPal initialization failed:",E)}return}$(!0),ln(C),console.error("[FloPay] DirectPayPal load/render failure:",b)};$(!1);let Cn=async(b,u=Ze.current)=>{if(Ve())return;let C=u?.sessionId??e;if(Ft.current){await Ft.current(b,{sessionId:C,accountPatch:u?.accountPatch,nonce:u?.nonce});return}let U=z.startTiming();z.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let f=()=>{z.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),z.performance({stage:"processing",durationMs:z.elapsed(U),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})};try{let E=Qt.current,Ae=u?.accountPatch?.email??Dt.current,it=u?.accountPatch?.userId??E?.customer?.id??E?.accountData?.userId??"",we=u?.accountPatch?.firstName??E?.customer?.firstName??E?.accountData?.firstName,Ce=u?.accountPatch?.lastName??E?.customer?.lastName??E?.accountData?.lastName,H=await new na.PaymentAPI(B,{telemetry:!1}).processPayment(it,{sessionId:C,nonce:u?.nonce??Vt.current,paymentMethodCategory:"paypal",tokenizedData:b,accountData:{userId:it,email:Ae??E?.customer?.email??"",...we?{firstName:we}:{},...Ce?{lastName:Ce}:{},country:u?.accountPatch?.country??E?.customer?.country??E?.accountData?.country??void 0,zip:u?.accountPatch?.zip??E?.customer?.zip??E?.accountData?.zip??void 0}});if(H.ok){if(cr||an&&dn.current)return;f(),z.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),Qe(()=>mt.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(Ve())return;let me=await H.json().catch(()=>null),ne=me?.message??"PayPal payment failed.",fe=Sr(ne)??ne;f(),H.status===400&&(typeof me?.declineCode=="string"||!Array.isArray(me?.fields))?z.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):H.status===400||H.status===422?z.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx"}):z.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:rc(H.status),failureCategory:H.status>=500?"server_error":void 0}),Yn(fe),Qe(()=>Gt.current?.(tn("paypal",fe,{code:me?.code,declineCode:me?.declineCode})));return}catch(E){if(Ve())return;f(),z.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let Ae=E instanceof Error?E.message:"PayPal payment failed.",it=Sr(Ae)??Ae;Yn(it),Qe(()=>Gt.current?.(tn("paypal",it)));return}},x=()=>new Ot.FloPayError("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),M=b=>Ve()?Promise.reject(x()):Promise.resolve(b),K=async b=>{if(Ve())throw x();qn||dt();let u=Ze.current,C=u?.sessionId??e,U=u?.nonce??Vt.current;z.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let f;try{f=await new na.PaymentAPI(B,{telemetry:!1}).createSessionIntent(C,U??"",lt?{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:Ot.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE,paymentMethodId:null,intentKind:pe==="setup_token"?"setup":"payment"}:{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"},{idempotencyKey:Pr})}catch(E){throw z.error({...(0,Ot.classifyTelemetryFailure)(E,"PAYMENT_PROCESSING_FAILED","unknown"),stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"}),E}if(Ve())throw x();if(f.provider!=="paypal"||f.providerObjectType!==pe)throw new Error(b);return z.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),f.providerObjectId},se=(b,u)=>{let C=u?.nonce??Vt.current;if(!C)return;let U=u?.sessionId??e,f=Qr(b)??gr(b)??"provider_declined";new na.PaymentAPI(B,{telemetry:!1}).reportSessionIntentDecline(U,C,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:f}).catch(()=>{})},Me=Y;X("loadScript:scheduled (deferred 1 tick)");let _e=null,Re=setTimeout(()=>{if(an){X("loadScript:skipped (cancelled before defer ran)");return}X("loadScript:start");let b=un==="live"?"production":un,u={};pe==="subscription"?u={intent:"subscription",vault:!0}:pe==="order"&&(u={intent:"capture"}),_e=(0,ms.loadScript)({clientId:l,currency:g,...u,...b?{environment:b}:{},...b==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}});let C=!1;_e.then(U=>{if(C=!0,X(`loadScript:resolved inactive=${Ve()} ns=${!!U} buttons=${!!U?.Buttons}`),Ve())return;if(!U?.Buttons){X("FAIL: namespace missing Buttons factory"),rt("PayPal SDK did not expose the Buttons factory.");return}z.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),z.performance({stage:"provider_ready",durationMs:z.elapsed(Ne.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),z.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let f=async(H,me)=>{if(Ve()||Ie.current!==Me)return;let ne=H.vaultSetupToken??H.subscriptionID??H.orderID??"",fe=ne?vt.current.get(ne):Yt.current.get(Me);if(!(!fe||!bt(fe.generation))&&Kt(fe.generation)){vt.current.delete(ne),Yt.current.delete(fe.surfaceKey),ur();try{if(et(!0),Qe(()=>qt.current?.(null)),!ne)throw new Ot.FloPayError("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});let st=Qt.current,Xe=Mr(nn.current??[st?.customer?.firstName,st?.customer?.lastName].filter(Boolean).join(" ")),be=wn({email:fe.accountPatch?.email?.trim()||Dt.current?.trim()||st?.customer?.email?.trim(),firstName:fe.accountPatch?.firstName?.trim()||Xe.firstName,lastName:fe.accountPatch?.lastName?.trim()||Xe.lastName});if(!(0,Ot.isValidEmail)(be.email)||!(be.firstName||be.lastName))try{let yn=nc(await me?.order?.get?.());be=wn({email:yn.email||be.email,firstName:yn.firstName||be.firstName,lastName:yn.lastName||be.lastName})}catch{}if(($e.current||nt)&&!(0,Ot.isValidEmail)(be.email)){let yn=await Je("PayPal",be);if(!yn)return;be=yn}(0,Ot.isValidEmail)(be.email)&&(fe.accountPatch=wn({...fe.accountPatch,...be}),await $e.current?.(be));let Pt;pe==="setup_token"?Pt={id:ne,type:"paypal_setup_token",isPaypal:!0,gateway:"paypal",paymentMethodType:Ot.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE}:lt?Pt={id:ne,isPaypal:!0,gateway:"paypal",paymentMethodType:Ot.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE}:Pt={id:ne,isPaypal:!0},await Cn(Pt,fe)}catch(st){Yn(st instanceof Error?st.message:"PayPal capture failed.")}finally{Ve()||et(!1)}}},E=H=>{let me=le?()=>M(le):()=>K(H);return async()=>en(await me())},Ae=U.Buttons({style:{layout:"horizontal",height:ra,tagline:!1},onClick:async(H,me)=>{if(Ve()){await me.reject();return}dt();let ne=ht.current,fe={};if(ne)try{let be=await ne("paypal");if(Ve()){await me.reject();return}if(!be.proceed){Ze.current=null,Yt.current.delete(Me),await me.reject();return}fe={sessionId:be.sessionId,accountPatch:be.accountPatch,nonce:be.nonce}}catch(be){X(`onClick:runBeforeButtonClick rejected msg=${(be instanceof Error?be.message:String(be)).slice(0,120)}`),Ze.current=null,Yt.current.delete(Me),await me.reject();return}Qe(()=>kn.current?.("paypal"));let Xe={generation:Ct(),surfaceKey:Me,...fe};Ze.current=Xe,Yt.current.set(Me,Xe),await me.resolve(),z.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),z.log({name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),z.log({name:"provider.overlay.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),jn=z.startTiming()},createOrder:pe==="order"?E("Failed to create PayPal order."):void 0,createSubscription:pe==="subscription"?E("Failed to create PayPal subscription."):void 0,createVaultSetupToken:pe==="setup_token"?async()=>en(await K("Failed to create PayPal setup token.")):void 0,onApprove:f,onCancel:()=>{if(Ve())return;let H=Yt.current.get(Me)??Ze.current;H&&Yt.current.delete(H.surfaceKey),Ze.current=null,ur(),z.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),Oe.current=!0,Nt({generation:H?.generation,remount:!0,focus:!1})},onError:H=>{if(Ve()||Ie.current!==Me)return;let me=H instanceof Error?H.message:"PayPal failed to render.";if(X(`onError rendered=${Kn} msg=${me.slice(0,120)}`),Kn){let ne=Yt.current.get(Me)??Ze.current;if(ne&&!bt(ne.generation)||!ne&&_())return;if(An(me)){Kt(ne?.generation);return}if(ur(),ko(H)){z.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),se(H,ne),Qe(()=>Gt.current?.(tn("paypal",me))),ne&&Yt.current.delete(ne.surfaceKey),Ze.current=null,Kt(ne?.generation);return}let fe=me.toLowerCase();z.error({errorCode:fe.includes("popup")&&fe.includes("block")?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),ne&&Yt.current.delete(ne.surfaceKey),Ze.current=null,Nt({generation:ne?.generation,remount:!0,showRetry:!0,focus:!0}),on(H,{code:"paypal_runtime_failed"});return}rt(me,!1,An(me)?null:Ir)}}),it=Ae.isEligible();if(X(`isEligible=${it}`),z.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!it){k(!1),rt("PayPal buttons are not eligible to render in this context (paypal_ineligible).",!1,null);return}Ir=!0,Vn=Ae,xn=()=>{if(!ot||Tn||Ve()||Kn)return;Tn=!0,X(`container:dims ${sn(pn)} visibility=${typeof document>"u"?"(no document)":document.visibilityState}`),typeof MutationObserver<"u"&&(pr=new MutationObserver(me=>{if(!Ve()){for(let ne of me)if(ne.type==="childList")ne.addedNodes.forEach(fe=>{if(!(fe instanceof Element))return;let st=fe.tagName.toLowerCase(),Xe=(fe.getAttribute("title")??"").slice(0,40),be=st==="iframe"?` ${je(fe)}`:"";X(`child+ ${st}${Xe?` title="${Xe}"`:""}${be} dims=${sn(fe)}`)});else if(ne.type==="attributes"&&ne.target instanceof Element){let fe=ne.target;if(fe.tagName.toLowerCase()!=="iframe")continue;let st=ne.attributeName;(st==="src"||st==="srcdoc")&&X(`attr~ iframe ${st}=${st==="srcdoc"?`[${(fe.getAttribute("srcdoc")??"").length}ch]`:Fn(fe.getAttribute("src"))} dims=${sn(fe)}`)}}}),pr.observe(pn,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let H=me=>{if(Ve()||Kn)return;let ne=pn.querySelectorAll("iframe"),fe=typeof document<"u"&&"hasStorageAccess"in document;X(`watchdog:${me} container=${sn(pn)} children=${pn.childElementCount} iframes=${ne.length} visibility=${typeof document>"u"?"(no document)":document.visibilityState} cookies=${typeof navigator>"u"?"?":navigator.cookieEnabled} hasStorageAccessApi=${fe} paypalNetRequests=${mr.value}`),ne.forEach((st,Xe)=>{let be=(st.getAttribute("title")??"").slice(0,40);X(` iframe[${Xe}] ${sn(st)}${be?` title="${be}"`:""} ${je(st)}`);let Pt=mn(st);Pt&&X(` ${Pt}`)}),Tt.length===0&&X(" (no PayPal/zoid window errors captured)")};vn.push(setTimeout(()=>H("3s"),3e3)),vn.push(setTimeout(()=>H("8s"),8e3)),vn.push(setTimeout(()=>H("15s"),15e3))},xn(),X("render:start");let Ce=z.startTiming();_t=setTimeout(()=>{Ve()||Kn||(X("watchdog:11s retryable render timeout"),rt("PayPal Buttons render did not settle within 11000ms.",!0,!0))},Zl);let F=Ae.render(pn);(async()=>{try{if(await F,X(`render:resolved inactive=${Ve()}`),Gn(),Ve()){En();return}Kn=!0,k(!0),he(!1),Zt.current?.("ready"),z.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),z.performance({stage:"checkout_render",durationMs:z.elapsed(Ce),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}catch(H){let me=H instanceof Error?H.message:"PayPal failed to render.";X(`render:rejected msg=${me.slice(0,120)}`),Gn(),rt(me,!1,An(me)?null:!0)}})()}).catch(U=>{let f=U instanceof Error?U.message:"PayPal operation failed.";X(`provider:failed msg=${f.slice(0,120)}`),rt(f,!1,C&&An(f)?null:Ir)})},0);return()=>{an=!0,clearTimeout(Re),yt&&clearTimeout(yt),Gn(),Le.current===Er&&(Le.current=null),En()}},[ie,B,l,g,c,pe,lt,e,le,Y,z,Je,nt,X]);let bn=Ge?(0,On.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=${ke} failed=${J})`,Ut.length===0?`
1
+ "use strict";var Ml=Object.create;var ta=Object.defineProperty;var Bl=Object.getOwnPropertyDescriptor;var Fl=Object.getOwnPropertyNames;var Dl=Object.getPrototypeOf,Ll=Object.prototype.hasOwnProperty;var Nl=(e,t)=>{for(var n in t)ta(e,n,{get:t[n],enumerable:!0})},ts=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Fl(t))!Ll.call(e,o)&&o!==n&&ta(e,o,{get:()=>t[o],enumerable:!(r=Bl(t,o))||r.enumerable});return e};var ns=(e,t,n)=>(n=e!=null?Ml(Dl(e)):{},ts(t||!e||!e.__esModule?ta(n,"default",{value:e,enumerable:!0}):n,e)),Ol=e=>ts(ta({},"__esModule",{value:!0}),e);var hd={};Nl(hd,{DirectPayPalButton:()=>Mo,FloPayAutomaticPaymentButton:()=>ll,FloPayCardSetup:()=>pl,FloPayCardSetupError:()=>Vo,FloPayCheckout:()=>Ta,FloPayProvider:()=>Fo,SplitCardForm:()=>Ia,VaultCardFields:()=>mo,dropThirdPartyOnlyError:()=>ml.dropThirdPartyOnlyError,useCheckout:()=>ms,useFloPay:()=>wr,usePayPalFloPay:()=>aa});module.exports=Ol(hd);var ml=require("@flopay/shared");var xa=require("@flopay/js"),Zn=require("@flopay/shared"),We=require("react");var Mt=require("react/jsx-runtime");function zl(){return(0,Mt.jsxs)(Mt.Fragment,{children:[(0,Mt.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,Mt.jsx)("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),(0,Mt.jsx)("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",(0,Mt.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,Mt.jsx)("path",{d:"M9 18l6-6-6-6"})})]})}function Ul(){return(0,Mt.jsx)(Mt.Fragment,{children:"Go back"})}function ql(){return(0,Mt.jsx)(Mt.Fragment,{children:"Secure card checkout"})}function Xr(e){return e!==void 0&&(e===""||e===null||e===!1)}function Zr({content:e}){return(0,Mt.jsx)(Mt.Fragment,{children:e===void 0?(0,Mt.jsx)(zl,{}):e})}function Qr({content:e}){return(0,Mt.jsx)(Mt.Fragment,{children:e===void 0?(0,Mt.jsx)(Ul,{}):e})}function Ro({content:e}){return(0,Mt.jsx)(Mt.Fragment,{children:e===void 0?(0,Mt.jsx)(ql,{}):e})}var zt=require("@flopay/shared"),$l="Checkout is temporarily unavailable. Please try again later.";function Wa(e){return{errorCode:"PROVIDER_LOAD_FAILED",failureCategory:e instanceof zt.FloPayError&&e.type==="authentication_error"?"invalid_response":"provider_runtime",stage:"provider_load",provider:"stripe",requestCategory:"provider_sdk"}}function jl(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 rs(){return new zt.FloPayError($l,"api_error",{code:"CheckoutInitializationFailed"})}function os(e,t,n){let r=e?.data.session,o=r?.gateways?.stripe?.enabledPaymentMethods??e?.data.stripe?.enabledPaymentMethods;return!!(n&&(r?.vault?.html||r?.gateways?.pcivault||o?.includes("card"))||t&&e?.data.paypal?.publishableKey)}function as(e,t){if(t&&(!(e instanceof zt.FloPayError)||e.type==="authentication_error"))return Wa(e);if(!(e instanceof zt.FloPayError&&jl(e))){if(!t&&!(e instanceof zt.FloPayError)&&(e instanceof TypeError||e instanceof SyntaxError))return{...(0,zt.classifyTelemetryFailure)(e,"NETWORK_REQUEST_FAILED"),stage:"session_read",requestCategory:"session_read"};if(!t&&e instanceof zt.FloPayError)return{errorCode:"NETWORK_REQUEST_FAILED",stage:"session_read",requestCategory:"session_read"};if(!(e instanceof zt.FloPayError))return{errorCode:"INTERNAL_SDK_ERROR",stage:"checkout_mount"}}}function eo(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,zt.isCardHolderNamePlaceholder)(l.firstName,l.lastName);if(!(0,zt.isValidEmail)(l.email))return Promise.reject(new zt.FloPayError("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}));let f={};for(let[y,p]of Object.entries(l)){if(c&&y.endsWith("Name")||typeof p!="string")continue;let b=p.trim();b&&(f[y]=b)}return o=e.claimCheckoutSession(t,n,{accountData:f}),o.catch(()=>{}),o}}function is(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 Ga(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 ss(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 Nr(e){if((0,zt.isCardHolderNamePlaceholder)(e))return{};let[t,...n]=e?.trim().split(/\s+/)??[];return t?{firstName:t,lastName:n.join(" ")||void 0}:{}}function Ya(e,t){return t?{...e,...t}:e}function cn(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 Vl=[{match:/^paypal authorization required\.?$/i,replacement:"For your additional security, please re-authenticate this payment via PayPal."}];function _r(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 Or(e,t){return e.status!=="authorized"?{status:"succeeded"}:{status:"authorized",paymentId:e.paymentId,sessionId:e.id||t||void 0,authorizationExpiresAt:e.authorizationExpiresAt}}function to(e){return e?.status==="authorized"||e?.status==="complete"}function ls(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function na(e){let t=ls(e);return new zt.FloPayError(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function ra(e){return e instanceof zt.FloPayError||typeof e=="object"&&e!==null&&"code"in e?e.code:void 0}function oa(e){let t=ls(e),n="checkout_processing_timeout";return t?n="authorization_expired":e?.status==="expired"&&(n="checkout_session_expired"),new zt.FloPayError(t?"Authorization has expired.":"Automatic payment failed. Please try again.","api_error",{code:n})}function _o(e,t){return e==="processing"||(0,zt.isMoneySettledOutcome)(e,t)}function cs(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}function ds(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 Ja(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 Eo(e){let t=[e?.id,e?.originalPaymentMethodId];for(let n of t)if(typeof n=="string"&&n.startsWith("pm_"))return n}var Rr=require("@flopay/js"),De=require("@flopay/shared"),C=ns(require("react"),1);var Xa=require("react"),Yn=(0,Xa.createContext)({flopay:null,paypalFlopay:null,billingApiUrl:""}),rr=(0,Xa.createContext)({session:null,loading:!1,error:null});var da=require("@flopay/js"),Ut=require("@flopay/shared"),gs=require("@paypal/paypal-js"),T=require("react");var us=require("@flopay/shared"),or=require("react"),Pr=require("react/jsx-runtime");function Dn(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 no(){let[e,t]=(0,or.useState)(null),n=(0,or.useRef)(null),r=(0,or.useRef)(0),o=(0,or.useCallback)((l,c)=>(n.current?.(null),r.current+=1,t({id:r.current,methodLabel:l,identity:c}),new Promise(f=>{n.current=f})),[]),a=(0,or.useCallback)(l=>{let c=n.current;n.current=null,t(null),c?.(l)},[]);return(0,or.useEffect)(()=>()=>{n.current?.(null),n.current=null},[]),{request:e,collect:o,finish:a}}function ro({identity:e,methodLabel:t,onComplete:n,onCancel:r,submitting:o=!1,testId:a="flopay-buyer-identity-pane"}){let[l,c]=(0,or.useState)(e.email?.trim()??""),f=(0,us.isValidEmail)(l.trim());return(0,Pr.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,Pr.jsxs)("div",{style:{fontWeight:700},children:["Continue with ",t]}),(0,Pr.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",(0,Pr.jsx)("input",{type:"email",autoComplete:"email","data-testid":"flopay-email",required:!0,value:l,onChange:y=>c(y.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]}),(0,Pr.jsxs)("div",{style:{display:"flex",gap:"0.5rem"},children:[r&&(0,Pr.jsx)("button",{type:"button",onClick:r,style:{flex:1,minHeight:42},children:"Cancel"}),(0,Pr.jsxs)("button",{type:"button",disabled:!f||o,onClick:()=>{n(Dn({...e,email:l.trim()}))},style:{flex:2,minHeight:42},children:["Continue with ",t]})]})]})}function Kl(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 zr(e){if(typeof e!="string")return;let t=e.trim();return/^[a-z0-9_.-]{1,64}$/i.test(t)?t:void 0}function Cr(e){if(typeof e!="object"||e===null)return;let t=e;return zr(t.code)??zr(t.type)??zr(t.name)}function oo(e){if(!(typeof e!="object"||e===null))return zr(e.decline_code)}function To(e){return typeof e!="object"||e===null?!1:zr(e.type)?.toLowerCase()==="card_error"||oo(e)!==void 0}function Sr(e){let t=Kl(e)?.toLowerCase()??"",r=`${Cr(e)?.toLowerCase()??""} ${t}`;return r.includes("popup")&&r.includes("block")}var ps=require("@flopay/shared"),xo=require("react");function wr(){return(0,xo.useContext)(Yn).flopay}function aa(){return(0,xo.useContext)(Yn).paypalFlopay??null}function ms(){return(0,xo.useContext)(rr)}function ys(){return(0,xo.useContext)(Yn).billingApiUrl||(0,ps.resolveBillingApiUrl)()}function ia(e){let t=e??(typeof navigator>"u"?"":navigator.userAgent),n=r=>({inAppBrowser:r!=="none",appFamily:r,popupCapability:"unknown"});return t?/FBAN|FBAV|FB_IAB|FBIOS/i.test(t)?n("facebook"):/Instagram/i.test(t)?n("instagram"):/musical_ly|BytedanceWebview|TikTok/i.test(t)?n("tiktok"):/Twitter|Snapchat|Pinterest|LinkedInApp|Line\/|MicroMessenger|GSA\//i.test(t)?n("other_in_app"):/Android.*;\s?wv\)/.test(t)||/(iPhone|iPad|iPod).*AppleWebKit(?!.*Safari)/.test(t)?n("generic_webview"):n("none"):n("none")}function sa(e,t,n){return!e.inAppBrowser||n!=="order"?"popup":t==="app_switch"||t==="redirect"?t:"popup"}var fs=require("@flopay/shared"),qr=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 la=require("react"),Ur=typeof window>"u"?la.useEffect:la.useLayoutEffect;var Hl={"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 Wl(e){return e==="stripe"||e==="paypal"?e:void 0}function Gl(e){let t=Wl(e.provider),n={schemaVersion:fs.FLO_INSTRUMENT_SCHEMA_VERSION,...t?{gateway:t}:{}};if(e.class==="lifecycle"){let r=Hl[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 Za=new Set(["checkout_mount","sdk_loaded","form_rendered","card_expanded"]);function ao(e,t){let n=(0,qr.useRef)(e);n.current=e;let r=(0,qr.useRef)(new Set),o=(0,qr.useRef)(t),a=(0,qr.useRef)(t);return Ur(()=>{a.current=t,o.current!==t&&(o.current=t,r.current.clear())},[t]),(0,qr.useCallback)(l=>{if(a.current!==t)return;let c=Gl(l);if(c){if(Za.has(c.name)){if(r.current.has(c.name))return;r.current.add(c.name)}nt(()=>n.current?.(c))}},[t])}var Yl=Symbol.for("@flopay/js.telemetry.bridge.v1"),Jl=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function Xl(){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 Zl(e){let t=Xl(),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 ca(e){let t=globalThis[Jl];return Zl(t?.(e)??{})}function sn(e){if(e)return e[Yl]}var En=require("react");function Ao(e){let t=(0,En.useRef)(0),n=(0,En.useRef)(null),r=(0,En.useRef)(null),o=(0,En.useCallback)((h=r.current)=>{h?.timer&&(clearTimeout(h.timer),h.timer=null)},[]),a=(0,En.useCallback)(h=>{o();let w=t.current+1;return t.current=w,n.current=null,r.current={generation:w,method:h,timer:null,yieldedControl:!1},w},[o]),l=(0,En.useCallback)(h=>{let w=r.current;return h!==void 0&&w?.generation!==h?!1:(o(w),r.current=null,(h===void 0||n.current===h)&&(n.current=null),!0)},[o]),c=(0,En.useCallback)(h=>{let w=r.current,B=h??w?.generation??t.current;(h===void 0||w?.generation===h)&&(o(w),r.current=null),n.current=B},[o]),f=(0,En.useCallback)(h=>n.current===(h??t.current),[]),y=(0,En.useCallback)(h=>r.current?.generation===h&&n.current!==h,[]),p=(0,En.useCallback)(()=>{let h=r.current;h&&(h.yieldedControl=!0,o(h))},[o]),b=(0,En.useCallback)(()=>{let h=r.current;!h?.yieldedControl||document.visibilityState!=="visible"||(o(h),h.timer=setTimeout(()=>{h.timer=null,r.current?.generation===h.generation&&(r.current=null,n.current=h.generation,e(h.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}))},600))},[o,e]);return(0,En.useEffect)(()=>{let h=()=>{document.visibilityState==="visible"?b():p()};return document.addEventListener("visibilitychange",h),window.addEventListener("blur",p),window.addEventListener("focus",b),()=>{document.removeEventListener("visibilitychange",h),window.removeEventListener("blur",p),window.removeEventListener("focus",b),o()}},[o,p,b]),{startAttempt:a,finishAttempt:l,invalidateAttempt:c,isAttemptInvalidated:f,isAttemptCurrent:y,generationRef:t}}var Jn=require("react/jsx-runtime"),ua=45,Ql=1e3,ec=11e3,tc=["https://www.paypal.com","https://www.sandbox.paypal.com"],Qa="We couldn't open PayPal. Try again or choose another payment method.",nc={width:"100%",minHeight:ua,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 rc(e){return e.includes("No ack for postMessage init()")&&tc.some(t=>e.includes(t))&&e.includes("10000ms")}var oc={script_rejected:{errorCode:"PROVIDER_LOAD_FAILED",stage:"provider_load",operationOutcome:"rejected"},namespace_unusable:{errorCode:"PROVIDER_LOAD_FAILED",stage:"provider_load",operationOutcome:"returned_error"},pre_ready_callback:{errorCode:"PROVIDER_RUNTIME_FAILED",stage:"provider_ready",operationOutcome:"returned_error"},render_rejected:{errorCode:"PROVIDER_RUNTIME_FAILED",stage:"provider_ready",operationOutcome:"rejected"},watchdog_expired:{errorCode:"PROVIDER_RUNTIME_FAILED",stage:"provider_ready",operationOutcome:"watchdog_expired"}};function ac(e){return!e.generationActive||e.kind==="teardown"?{action:"ignore"}:e.kind==="ineligible"?{action:"unavailable"}:e.automaticRetryAllowed&&!e.automaticRetryUsed?{action:"retry"}:{action:"exhaust",report:oc[e.kind]??null}}function ic(e,t){return e==="watchdog_expired"?"paypal_render_timeout":rc(t)?"paypal_init_timeout":"paypal_init_failure"}function sc(e,t=!1){return e?t?`${Qa} Open this page in your system browser, then try again.`:`${Qa} Allow pop-ups for this site, then try again.`:Qa}function lc(e){let t=To(e),n=Sr(e);return t?{errorCode:"PROVIDER_RUNTIME_FAILED",popupBlocked:n,providerDeclined:t,terminalReason:"provider_declined"}:{errorCode:n?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",popupBlocked:n,providerDeclined:t,terminalReason:n?"popup_blocked":"provider_error"}}function cc(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 dc(e){return e>=500?"5xx":e>=400?"4xx":e>=300?"3xx":"unknown"}function hs({sessionId:e,nonce:t,billingApiUrl:n,email:r,billingName:o,onBuyerIdentityReady:a,clientId:l,environment:c,currency:f,isSubscription:y,providerObjectType:p,approvalPresentation:b,onTokenizedBody:h,onComplete:w,onErrorChange:B,onDecline:N,onTechnicalFailure:de,isProcessing:K=!1,onLoadStateChange:I,onInitializationStateChange:re,allowAutomaticRetry:q=!0,onButtonClick:ie,runBeforeButtonClick:se,session:ee,existingOrderId:Oe,telemetry:ue,telemetryContext:Ct,onInstrument:st,debug:Se=!1}){let Re=wr(),he=ao(st,e),te=(0,T.useMemo)(()=>{if(Re)return null;let L=ca({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:Ut.SDK_VERSION,enabled:ue!==!1});return L.setCheckoutContext(Ct??{}),L.beginCheckout(Ct??{}),L},[n,Re,ue,Ct?.checkoutMode,Ct?.layout]),Te=(0,T.useMemo)(()=>sn(Re),[Re]);(0,T.useEffect)(()=>()=>{te&&te.flush().catch(()=>{}).finally(()=>te.destroy())},[te]);let fe=(0,T.useMemo)(()=>({error:L=>{Te?Te.error(L):te?.error(L),he({class:"technical_error",errorCode:L.requestCategory==="intent_create"?"PAYMENT_PROCESSING_FAILED":L.errorCode,requestCategory:L.requestCategory,provider:L.provider})},log:L=>{Te?Te.log(L):te?.log(L),he({class:"lifecycle",name:L.name,provider:L.provider})},performance:L=>{Te?Te.performance(L):te?.performance(L)},terminal:L=>{Te?Te.terminal(L):te?.terminal(L)},startTiming:()=>Te?.now()??te?.now()??0,elapsed:L=>Te?.elapsed(L)??Math.max(0,(te?.now()??L)-L)}),[he,Te,te]),we=(0,T.useRef)(null),xe=(0,T.useRef)(0),Le=(0,T.useRef)(null),_e=(0,T.useRef)(null),_=(0,T.useRef)(null),oe=(0,T.useRef)(!1),[me,J]=(0,T.useState)(!1),[O,Ce]=(0,T.useState)(!1),[Ke,_t]=(0,T.useState)(0),Qe=(0,T.useRef)(0),[Z,X]=(0,T.useState)(!1),$=(0,T.useRef)(!1),ze=(0,T.useRef)(!1),[Je,be]=(0,T.useState)(!1),[Xe,H]=(0,T.useState)(!1),{request:z,collect:rt,finish:D}=no(),j=(0,T.useRef)({sessionId:e,required:!(0,Ut.isValidEmail)(r?.trim()||ee?.customer?.email?.trim())});j.current.sessionId!==e&&(j.current={sessionId:e,required:!(0,Ut.isValidEmail)(r?.trim()||ee?.customer?.email?.trim())});let qe=j.current.required,ve=(0,T.useMemo)(()=>n.replace(/\/+$/,""),[n]),St=ee?.gateways?.paypal?.providerObjectType??p,P=St??(y?"subscription":"order"),[F]=(0,T.useState)(ia),qt=ee?.gateways?.paypal?.approvalPresentation??b,Ae=sa(F,qt==="app_switch"?"app_switch":void 0,P),Et=St==="order"||St==="setup_token",tn=(0,T.useMemo)(()=>JSON.stringify([ve,l,f,c??"",P,Et,Ae,e,Oe??""]),[ve,l,f,c,Oe,P,Et,Ae,e]),et=(0,T.useRef)(tn),nn=et.current!==tn,lt=(0,T.useRef)(Se),Wt=(0,T.useRef)(null),[dn,rn]=(0,T.useState)([]),ke=(0,T.useCallback)(L=>{lt.current&&rn(mt=>[...mt,`${new Date().toISOString().slice(11,23)} ${L}`])},[]);(0,T.useEffect)(()=>{lt.current=Se,Se&&ke("debug:enabled"),Wt.current?.setEnabled(Se)},[ke,Se]);let hn=(0,T.useRef)(h),bn=(0,T.useRef)(w),$e=(0,T.useRef)(B),ct=(0,T.useRef)(N),un=(0,T.useRef)(de),Gt=(0,T.useRef)(ie),pn=(0,T.useRef)(I),$t=(0,T.useRef)(re),wt=(0,T.useRef)(a),Qn=(0,T.useRef)(se),kt=(0,T.useRef)(ee),vn=(0,T.useRef)(r),ht=(0,T.useRef)(o),Yt=(0,T.useRef)(t),dt=(0,T.useRef)(null),Tt=(0,T.useRef)(new Map),Pn=(0,T.useRef)(new Map),Jt=(0,T.useRef)(!1);(0,T.useEffect)(()=>(Jt.current=!0,()=>{Jt.current=!1}),[]),(0,T.useEffect)(()=>{hn.current=h},[h]),(0,T.useEffect)(()=>{wt.current=a},[a]),(0,T.useEffect)(()=>{bn.current=w},[w]),(0,T.useEffect)(()=>{$e.current=B},[B]),(0,T.useEffect)(()=>{ct.current=N},[N]),(0,T.useEffect)(()=>{un.current=de},[de]),(0,T.useEffect)(()=>{Gt.current=ie},[ie]),(0,T.useEffect)(()=>{pn.current=I},[I]),(0,T.useEffect)(()=>{$t.current=re},[re]),(0,T.useEffect)(()=>{Qn.current=se},[se]),(0,T.useEffect)(()=>{kt.current=ee},[ee]),(0,T.useEffect)(()=>{vn.current=r},[r]),(0,T.useEffect)(()=>{ht.current=o},[o]),(0,T.useEffect)(()=>{Yt.current=t},[t]),(0,T.useEffect)(()=>{Qe.current=Ke},[Ke]),(0,T.useEffect)(()=>{Z&&_.current?.focus()},[Z,Ke]);let Cn=(0,T.useCallback)(()=>{window.setTimeout(()=>{_.current?.focus()},0)},[]),ut=(0,T.useCallback)(()=>{J(!1),_t(L=>L+1)},[]),E=(0,T.useCallback)(()=>{X(!1),(we.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??we.current)?.focus?.()},[]);(0,T.useEffect)(()=>{!me||!oe.current||(oe.current=!1,E())},[E,me,Ke]);let xt=(0,T.useCallback)((L,mt)=>{let pe=mt?.popupBlocked??Sr(L),xn=sc(pe,F.inAppBrowser),Sn=un.current;if(Sn){let wn=pe&&F.inAppBrowser?new Ut.FloPayError(xn,"api_error",{code:mt?.code??"paypal_popup_blocked"}):L;Sn("paypal",wn,mt);return}$e.current?.(xn)},[F.inAppBrowser]),ot=(0,T.useCallback)(L=>{let mt=Le.current,pe=_e.current;mt===null||!pe||(fe.log({...pe,name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:L}),fe.performance({...pe,stage:"overlay_return",durationMs:fe.elapsed(mt),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:L}),Le.current=null)},[fe]),Xt=(0,T.useCallback)((L,mt,pe)=>{let xn=_e.current;ot("overlay_timeout"),xn&&fe.error({...xn,errorCode:"REQUEST_TIMEOUT",failureCategory:"provider_runtime",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",statusClass:"timeout",terminalReason:"overlay_timeout"}),xt(mt,pe),X(!0),ut(),Cn()},[ot,Cn,xt,ut,fe]),{finishAttempt:on,generationRef:Ln,invalidateAttempt:Tn,isAttemptCurrent:Zt,isAttemptInvalidated:tt,startAttempt:Tr}=Ao(Xt),xr=(0,T.useCallback)(()=>(X(!1),Tr("paypal")),[Tr]),Un=(0,T.useCallback)(L=>{Tn(L?.generation),L?.showRetry&&X(!0),L?.remount&&ut(),L?.focus!==!1&&Cn()},[Cn,Tn,ut]),Ar=L=>{let mt=dt.current;return mt&&Pn.current.set(L,mt),L};(0,T.useEffect)(()=>{et.current!==tn&&(et.current=tn,$.current=!1,ze.current=!1,J(!1),Ce(!1),be(!1),$t.current?.("loading"))},[tn]),(0,T.useEffect)(()=>{nt(()=>pn.current?.(me&&!Je))},[me,Je]);let qn=(0,Ut.normalizeGatewayEnvironment)(c);(0,T.useEffect)(()=>{let L={attempt:Ln.current+1,...F,presentationMode:Ae},mt=()=>_e.current??L,pe={error:v=>fe.error({...v,...mt()}),log:v=>fe.log({...v,...mt()}),performance:v=>fe.performance({...v,...mt()}),terminal:v=>fe.terminal({...v,...mt()}),startTiming:fe.startTiming,elapsed:fe.elapsed},xn=l?`${l.slice(0,6)}\u2026(len ${l.length})`:"(empty)",Sn=typeof navigator>"u"?"(no navigator)":navigator.userAgent;if(ke(`mount clientId=${xn} env=${c??"(unset)"}\u2192${qn??"live"} ccy=${f} sub=${y}`),ke(`ua=${Sn.slice(0,80)}${Sn.length>80?"\u2026":""}`),!l){ke("FAIL: clientId empty \u2014 gateway misconfigured"),be(!0),pe.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(!we.current){ke("FAIL: containerRef not attached");return}xe.current=pe.startTiming(),pe.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let wn=!1,hr=!1,at=()=>wn||hr,Mr,er=!1,Br=()=>{Mr=(0,Ut.generateIdempotencyKey)(),Mr||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),er=!0},$n=null,jn=!1,jt=null,bt=!1,Nn=()=>{!jt||bt||(bt=!0,jt.close().catch(()=>{}))},mn=!1,On=!1,fn=we.current,Ue=null,ln=null,Ft=[],Vn=null,sr=!1,br=!1,Kn=null,An=v=>{if(!v||typeof v.getBoundingClientRect!="function")return"(no rect)";let m=v.getBoundingClientRect();return`${Math.round(m.width)}\xD7${Math.round(m.height)}`},Mn=v=>{if(!v)return"(empty)";try{let m=new URL(v,typeof window>"u"?"https://localhost":window.location.href),g=m.pathname.toLowerCase();return g.includes("checkcaptcha")||g.includes("captcha")?`CAPTCHA(${m.host}${g})`:g.includes("risk")||g.includes("challenge")?`RISK(${m.host}${g})`:g.includes("smart/buttons")?`smart-buttons(${m.host})`:`${m.host}${g}`.slice(0,100)}catch{return v.slice(0,80)}},lr=v=>{let m=v.getAttribute("src"),g=v.getAttribute("srcdoc"),ae=v.getAttribute("name"),Me=v.getAttribute("sandbox"),ce=[];return m&&ce.push(`src=${Mn(m)}`),g&&ce.push(`srcdoc[${g.length}ch]`),!m&&!g&&ce.push("src=(empty) srcdoc=(empty)"),ae&&ce.push(`name=${ae.slice(0,40)}`),Me!==null&&ce.push(`sandbox="${Me.slice(0,40)}"`),ce.join(" ")},Vr=v=>{if(!(v instanceof HTMLIFrameElement))return"";try{let m=v.contentDocument;if(!m)return"cd=null";let g=m.body?.children.length??0,ae=m.body?.innerHTML.length??0,Me=m.head?.innerHTML.length??0;return`cd=same-origin readyState=${m.readyState} body[${g}children,${ae}ch] head[${Me}ch]`}catch(m){return`cd=cross-origin(${m.message.slice(0,30)})`}},Hn=[],cr=v=>{if(at())return;let m=v.message??String(v.error??"(no message)");m&&(m.toLowerCase().includes("paypal")||m.toLowerCase().includes("zoid")||m.toLowerCase().includes("postrobot")||m.toLowerCase().includes("storage"))&&(ke(`window:error ${m.slice(0,140)}`),Hn.push(m))},gn=v=>{if(at())return;let m=v.reason instanceof Error?v.reason.message:String(v.reason??"(no reason)");m&&(m.toLowerCase().includes("paypal")||m.toLowerCase().includes("zoid")||m.toLowerCase().includes("postrobot")||m.toLowerCase().includes("storage"))&&(ke(`window:rejection ${m.slice(0,140)}`),Hn.push(m))},yt={value:0},kn=()=>{Ue?.disconnect(),Ue=null,ln?.disconnect(),ln=null;for(let v of Ft.splice(0))clearTimeout(v);br=!1,sr&&typeof window<"u"&&(window.removeEventListener("error",cr),window.removeEventListener("unhandledrejection",gn)),sr=!1},A=()=>{if(!(sr||at()||mn)){if(sr=!0,Hn.length=0,yt.value=0,typeof window<"u"&&(window.addEventListener("error",cr),window.addEventListener("unhandledrejection",gn)),typeof PerformanceObserver<"u")try{ln=new PerformanceObserver(v=>{if(!at())for(let m of v.getEntries()){if(!m.name.toLowerCase().includes("paypal"))continue;yt.value+=1;let g=Math.round(m.duration);ke(`net ${g}ms ${m.name.slice(0,90)}`)}}),ln.observe({type:"resource",buffered:!0})}catch{}Kn?.()}},x=()=>{Vn&&(clearTimeout(Vn),Vn=null)},U=()=>{kn(),x()},ne={setEnabled:v=>{v?A():kn()}};Wt.current=ne,lt.current&&A();let He=v=>{if(!v)return!1;let m=v.toLowerCase();return m.includes("zoid destroyed")||m.includes("destroyed all components")||m.includes("window closed")||m.includes("detected container element removed")},Ie=v=>{if(at()||He(v))return;let m=_r(v)??v;nt(()=>$e.current?.(m))},ye=(v,m)=>{if(wn||jn)return;jn=!0,hr=!0,U(),Nn();let g=ac({kind:v,generationActive:!0,automaticRetryAllowed:q,automaticRetryUsed:$.current});if(g.action==="retry"){$.current=!0,J(!1),H(!1),Ce(!0),$t.current?.("retrying"),$n=setTimeout(()=>{wn||_t(ae=>ae+1)},Ql);return}if(J(!1),H(!1),Ce(!1),be(!0),g.action!=="ignore"){if($t.current?.("exhausted"),g.action==="unavailable"){console.error("[FloPay] DirectPayPal load/render failure:",m);return}g.report&&pe.error({errorCode:g.report.errorCode,stage:g.report.stage,operationOutcome:g.report.operationOutcome,provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime"}),ze.current||(ze.current=!0,console.error("[FloPay] Direct PayPal initialization failed:",ic(v,m)))}};be(!1);let le=async(v,m=dt.current)=>{if(at())return;let g=m?.sessionId??e;if(hn.current){await hn.current(v,{sessionId:g,accountPatch:m?.accountPatch,nonce:m?.nonce});return}let ae=pe.startTiming();pe.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let Me=()=>{pe.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),pe.performance({stage:"processing",durationMs:pe.elapsed(ae),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})};try{let ce=kt.current,At=m?.accountPatch?.email??vn.current,In=m?.accountPatch?.userId??ce?.customer?.id??ce?.accountData?.userId??"",vt=m?.accountPatch?.firstName??ce?.customer?.firstName??ce?.accountData?.firstName,Dt=m?.accountPatch?.lastName??ce?.customer?.lastName??ce?.accountData?.lastName,Ee=await new da.PaymentAPI(ve,{telemetry:!1}).processPayment(In,{sessionId:g,nonce:m?.nonce??Yt.current,paymentMethodCategory:"paypal",tokenizedData:v,accountData:{userId:In,email:At??ce?.customer?.email??"",...vt?{firstName:vt}:{},...Dt?{lastName:Dt}:{},country:m?.accountPatch?.country??ce?.customer?.country??ce?.accountData?.country??void 0,zip:m?.accountPatch?.zip??ce?.customer?.zip??ce?.accountData?.zip??void 0}});if(Ee.ok){if(hr||wn&&Jt.current)return;Me(),pe.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}),nt(()=>bn.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(at())return;let je=await Ee.json().catch(()=>null),Be=je?.message??"PayPal payment failed.",Ne=_r(Be)??Be;Me(),Ee.status===400&&(typeof je?.declineCode=="string"||!Array.isArray(je?.fields))?pe.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:"approved"}):Ee.status===400||Ee.status===422?pe.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx",terminalReason:"approved"}):pe.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:dc(Ee.status),failureCategory:Ee.status>=500?"server_error":void 0}),Ie(Ne),nt(()=>ct.current?.(cn("paypal",Ne,{code:je?.code,declineCode:je?.declineCode})));return}catch(ce){if(at())return;Me(),pe.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let At=ce instanceof Error?ce.message:"PayPal payment failed.",In=_r(At)??At;Ie(In),nt(()=>ct.current?.(cn("paypal",In)));return}},W=()=>new Ut.FloPayError("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),M=v=>at()?Promise.reject(W()):Promise.resolve(v),ge=async v=>{if(at())throw W();er||Br();let m=dt.current,g=m?.sessionId??e,ae=m?.nonce??Yt.current;pe.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let Me;try{Me=await new da.PaymentAPI(ve,{telemetry:!1}).createSessionIntent(g,ae??"",Et?{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:Ut.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE,paymentMethodId:null,intentKind:P==="setup_token"?"setup":"payment"}:{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"},{idempotencyKey:Mr})}catch(ce){throw pe.error({...(0,Ut.classifyTelemetryFailure)(ce,"PAYMENT_PROCESSING_FAILED","unknown"),stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"}),ce}if(at())throw W();if(Me.provider!=="paypal"||Me.providerObjectType!==P)throw new Error(v);return pe.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),Me.providerObjectId},k=(v,m)=>{let g=m?.nonce??Yt.current;if(!g)return;let ae=m?.sessionId??e,Me=oo(v)??Cr(v)??"provider_declined";new da.PaymentAPI(ve,{telemetry:!1}).reportSessionIntentDecline(ae,g,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:Me}).catch(()=>{})},G=Ke;ke("loadScript:scheduled (deferred 1 tick)");let Ze=null,Vt=setTimeout(()=>{if(wn){ke("loadScript:skipped (cancelled before defer ran)");return}ke("loadScript:start");let v=qn==="live"?"production":qn,m={};P==="subscription"?m={intent:"subscription",vault:!0}:P==="order"&&(m={intent:"capture"}),Ze=(0,gs.loadScript)({clientId:l,currency:f,...m,...v?{environment:v}:{},...v==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}});let g=!1;Ze.then(ae=>{if(g=!0,ke(`loadScript:resolved inactive=${at()} ns=${!!ae} buttons=${!!ae?.Buttons}`),at())return;if(!ae?.Buttons){ke("FAIL: namespace missing Buttons factory"),ye("namespace_unusable","PayPal SDK did not expose the Buttons factory.");return}pe.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),pe.performance({stage:"provider_ready",durationMs:pe.elapsed(xe.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),pe.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let Me=async(Ee,je)=>{if(at()||Qe.current!==G)return;let Be=Ee.vaultSetupToken??Ee.subscriptionID??Ee.orderID??"",Ne=Be?Pn.current.get(Be):Tt.current.get(G);if(!(!Ne||!Zt(Ne.generation))&&on(Ne.generation)){Pn.current.delete(Be),Tt.current.delete(Ne.surfaceKey),ot("approved");try{if(H(!0),nt(()=>$e.current?.(null)),!Be)throw new Ut.FloPayError("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});let it=kt.current,Rn=Nr(ht.current??[it?.customer?.firstName,it?.customer?.lastName].filter(Boolean).join(" ")),Ge=Dn({email:Ne.accountPatch?.email?.trim()||vn.current?.trim()||it?.customer?.email?.trim(),firstName:Ne.accountPatch?.firstName?.trim()||Rn.firstName,lastName:Ne.accountPatch?.lastName?.trim()||Rn.lastName});if(!(0,Ut.isValidEmail)(Ge.email)||!(Ge.firstName||Ge.lastName))try{let dr=cc(await je?.order?.get?.());Ge=Dn({email:dr.email||Ge.email,firstName:dr.firstName||Ge.firstName,lastName:dr.lastName||Ge.lastName})}catch{}if((wt.current||qe)&&!(0,Ut.isValidEmail)(Ge.email)){let dr=await rt("PayPal",Ge);if(!dr)return;Ge=dr}(0,Ut.isValidEmail)(Ge.email)&&(Ne.accountPatch=Dn({...Ne.accountPatch,...Ge}),await wt.current?.(Ge));let Q;P==="setup_token"?Q={id:Be,type:"paypal_setup_token",isPaypal:!0,gateway:"paypal",paymentMethodType:Ut.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE}:Et?Q={id:Be,isPaypal:!0,gateway:"paypal",paymentMethodType:Ut.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE}:Q={id:Be,isPaypal:!0},await le(Q,Ne)}catch(it){Ie(it instanceof Error?it.message:"PayPal capture failed.")}finally{at()||H(!1)}}},ce=Ee=>{let je=Oe?()=>M(Oe):()=>ge(Ee);return async()=>Ar(await je())},At=ae.Buttons({style:{layout:"horizontal",height:ua,tagline:!1},...Ae==="app_switch"?{appSwitchWhenAvailable:!0}:{},onClick:async(Ee,je)=>{if(at()){await je.reject();return}Br();let Be=Qn.current,Ne={};if(Be)try{let Ge=await Be("paypal");if(at()){await je.reject();return}if(!Ge.proceed){dt.current=null,Tt.current.delete(G),await je.reject();return}Ne={sessionId:Ge.sessionId,accountPatch:Ge.accountPatch,nonce:Ge.nonce}}catch(Ge){ke(`onClick:runBeforeButtonClick rejected msg=${(Ge instanceof Error?Ge.message:String(Ge)).slice(0,120)}`),dt.current=null,Tt.current.delete(G),await je.reject();return}nt(()=>Gt.current?.("paypal"));let it=xr(),Rn={generation:it,surfaceKey:G,...Ne};dt.current=Rn,Tt.current.set(G,Rn),_e.current={...L,attempt:it},await je.resolve(),pe.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),pe.log({name:"provider.handoff.requested",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),Le.current=pe.startTiming()},createOrder:P==="order"?ce("Failed to create PayPal order."):void 0,createSubscription:P==="subscription"?ce("Failed to create PayPal subscription."):void 0,createVaultSetupToken:P==="setup_token"?async()=>Ar(await ge("Failed to create PayPal setup token.")):void 0,onApprove:Me,onCancel:()=>{if(at())return;let Ee=Tt.current.get(G)??dt.current;Ee&&Tt.current.delete(Ee.surfaceKey),dt.current=null,ot("cancelled"),pe.terminal({outcome:"payment_cancelled",terminalReason:"cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),oe.current=!0,Un({generation:Ee?.generation,remount:!0,focus:!1})},onError:Ee=>{if(at()||Qe.current!==G)return;let je=Ee instanceof Error?Ee.message:"PayPal failed to render.";if(ke(`onError rendered=${mn} msg=${je.slice(0,120)}`),mn){let Be=Tt.current.get(G)??dt.current;if(Be&&!Zt(Be.generation)||!Be&&tt())return;if(He(je)){on(Be?.generation);return}let{errorCode:Ne,popupBlocked:it,providerDeclined:Rn,terminalReason:Ge}=lc(Ee);if(ot(Ge),Rn){pe.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal",terminalReason:Ge}),k(Ee,Be),nt(()=>ct.current?.(cn("paypal",je))),Be&&Tt.current.delete(Be.surfaceKey),dt.current=null,on(Be?.generation);return}pe.error({errorCode:Ne,failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",terminalReason:Ge}),Be&&Tt.current.delete(Be.surfaceKey),dt.current=null,Un({generation:Be?.generation,remount:!0,showRetry:!0,focus:!0}),xt(Ee,{code:"paypal_runtime_failed",popupBlocked:it});return}ye(He(je)?"teardown":"pre_ready_callback",je)}}),In=At.isEligible();if(ke(`isEligible=${In}`),pe.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!In){J(!1),ye("ineligible","PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}On=!0,jt=At,Kn=()=>{if(!sr||br||at()||mn)return;br=!0,ke(`container:dims ${An(fn)} visibility=${typeof document>"u"?"(no document)":document.visibilityState}`),typeof MutationObserver<"u"&&(Ue=new MutationObserver(je=>{if(!at()){for(let Be of je)if(Be.type==="childList")Be.addedNodes.forEach(Ne=>{if(!(Ne instanceof Element))return;let it=Ne.tagName.toLowerCase(),Rn=(Ne.getAttribute("title")??"").slice(0,40),Ge=it==="iframe"?` ${lr(Ne)}`:"";ke(`child+ ${it}${Rn?` title="${Rn}"`:""}${Ge} dims=${An(Ne)}`)});else if(Be.type==="attributes"&&Be.target instanceof Element){let Ne=Be.target;if(Ne.tagName.toLowerCase()!=="iframe")continue;let it=Be.attributeName;(it==="src"||it==="srcdoc")&&ke(`attr~ iframe ${it}=${it==="srcdoc"?`[${(Ne.getAttribute("srcdoc")??"").length}ch]`:Mn(Ne.getAttribute("src"))} dims=${An(Ne)}`)}}}),Ue.observe(fn,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let Ee=je=>{if(at()||mn)return;let Be=fn.querySelectorAll("iframe"),Ne=typeof document<"u"&&"hasStorageAccess"in document;ke(`watchdog:${je} container=${An(fn)} children=${fn.childElementCount} iframes=${Be.length} visibility=${typeof document>"u"?"(no document)":document.visibilityState} cookies=${typeof navigator>"u"?"?":navigator.cookieEnabled} hasStorageAccessApi=${Ne} paypalNetRequests=${yt.value}`),Be.forEach((it,Rn)=>{let Ge=(it.getAttribute("title")??"").slice(0,40);ke(` iframe[${Rn}] ${An(it)}${Ge?` title="${Ge}"`:""} ${lr(it)}`);let Q=Vr(it);Q&&ke(` ${Q}`)}),Hn.length===0&&ke(" (no PayPal/zoid window errors captured)")};Ft.push(setTimeout(()=>Ee("3s"),3e3)),Ft.push(setTimeout(()=>Ee("8s"),8e3)),Ft.push(setTimeout(()=>Ee("15s"),15e3))},Kn(),ke("render:start");let Dt=pe.startTiming();Vn=setTimeout(()=>{at()||mn||(ke("watchdog:11s retryable render timeout"),ye("watchdog_expired","PayPal Buttons render did not settle within 11000ms."))},ec);let an=At.render(fn);(async()=>{try{if(await an,ke(`render:resolved inactive=${at()}`),U(),at()){Nn();return}mn=!0,J(!0),Ce(!1),$t.current?.("ready"),pe.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),pe.performance({stage:"checkout_render",durationMs:pe.elapsed(Dt),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}catch(Ee){let je=Ee instanceof Error?Ee.message:"PayPal failed to render.";ke(`render:rejected msg=${je.slice(0,120)}`),U(),ye(He(je)?"teardown":"render_rejected",je)}})()}).catch(ae=>{let Me=ae instanceof Error?ae.message:"PayPal operation failed.";ke(`provider:failed msg=${Me.slice(0,120)}`);let ce="script_rejected";g&&He(Me)?ce="teardown":g&&On&&(ce="render_rejected"),ye(ce,Me)})},0);return()=>{wn=!0,clearTimeout(Vt),$n&&clearTimeout($n),U(),Wt.current===ne&&(Wt.current=null),Nn(),Le.current=null,_e.current=null}},[q,ve,l,f,c,P,Ae,Et,e,Oe,Ke,fe,rt,qe,ke,ot]);let pt=Se?(0,Jn.jsxs)("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:Je?"#fef2f2":"#f3f4f6",border:`1px solid ${Je?"#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=${me} failed=${Je})`,dn.length===0?`
2
2
  (waiting for first lifecycle event\u2026)`:`
3
- ${Ut.join(`
4
- `)}`]}):null;return J&&!O?Ge?(0,On.jsx)("div",{children:bn}):null:(0,On.jsxs)("div",{children:[bn,ve&&(0,On.jsx)(Zr,{identity:ve.identity,methodLabel:ve.methodLabel,testId:"flopay-direct-paypal-identity-pane",onComplete:te,onCancel:()=>te(null)}),(0,On.jsxs)("div",{"aria-hidden":de||ve?!0:void 0,style:de||ve?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:ra},children:[!ke&&!de&&(0,On.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,On.jsx)("div",{ref:De,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,role:"group","aria-label":"PayPal payment method",style:{minHeight:ra,display:"flex",opacity:ke?1:0},"aria-busy":qe||ye},Y)]},Y),tt&&(0,On.jsx)("button",{ref:Ee,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:Jt,style:ec,children:"Try PayPal again"})]})}function Eo(e){return(0,On.jsx)(ys,{...e})}function fs(e){return(0,On.jsx)(ys,{...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 Wa=":idempotency-key";function Ga(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 Ya(e,t){if(!no())return null;try{let n=window.sessionStorage.getItem(e+Wa);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{Ga(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{Ya(e,t)&&window.sessionStorage.removeItem(e+Wa)}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+Wa,JSON.stringify({canonicalIdentity:t,idempotencyKey:n}))}catch(r){console.warn("[FloPayCheckout] Failed to persist checkout idempotency key.",r)}}function Ha(e,t){return`${e}:${t.totalAmount??""}:${t.overrideAmount??""}:${t.quantity??1}:${t.currency??""}`}function oc(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=>Ha(`${o.type??""}:${o.code??o.providerItemId??o.providerPlanId??""}`,o)).sort(),i:e?.items?.map(o=>Ha(o.code??o.providerItemId??"",o)).sort(),s:e?.subscriptions?.map(o=>Ha(o.code??o.providerPlanId??"",o)).sort(),couponCodes:e?.couponCodes?[...e.couponCodes].sort():void 0,checkoutMetadata:oc(e?.checkoutMetadata),...t?{tagsData:e?.tagsData,utmMetadata:e?.utmMetadata,tokenizedData:e?.tokenizedData,checkoutMode:e?.checkoutMode??"full"}:{}};return JSON.stringify(r)}function gs(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 hs(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(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,m)=>`${y.code}:${y.type??""}`.localeCompare(`${m.code}:${m.type??""}`)),l=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,m)=>`${y.code}:${y.type??""}`.localeCompare(`${m.code}:${m.type??""}`));if(a.length!==l.length)return!1;for(let[y,m]of a.entries()){let v=l[y];if(v===void 0||m.code!==v.code||m.type!==void 0&&m.type!==v.type||m.quantity!==v.quantity||m.totalAmount!==v.totalAmount||m.overrideAmount!==v.overrideAmount||m.currency!==v.currency)return!1}let c=[...t.couponCodes??[]].sort(),g=[...e.coupons??[]].sort();return c.length===g.length&&c.every((y,m)=>y===g[m])}var Wt=require("react/jsx-runtime");var ac={panel:{background:"white"},spinnerTrackColor:"#e5e7eb",spinnerAccentColor:"#4A49FF",labelColors:{processing:"#374151",success:"#16a34a",error:"#dc2626"},noteColor:"#6b7280"};function zn({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=ac}){let g={fontSize:13,color:c.noteColor,fontWeight:400,maxWidth:260,lineHeight:1.4,margin:0};return(0,Wt.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,Wt.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,Wt.jsxs)("div",{style:{width:48,height:48,position:"relative"},children:[e==="processing"&&(0,Wt.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,Wt.jsx)("circle",{cx:"12",cy:"12",r:"10",stroke:c.spinnerTrackColor,strokeWidth:"3"}),(0,Wt.jsx)("path",{d:"M4 12a8 8 0 018-8v3a5 5 0 00-5 5H4z",fill:c.spinnerAccentColor})]}),e==="success"&&(0,Wt.jsx)("div",{style:{animation:"flopay-pop 0.4s cubic-bezier(0.34,1.56,0.64,1)"},children:(0,Wt.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,Wt.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#22c55e"}),(0,Wt.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,Wt.jsx)("div",{style:{animation:"flopay-shake 0.4s ease"},children:(0,Wt.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,Wt.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#ef4444"}),(0,Wt.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,Wt.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,Wt.jsx)("p",{style:g,children:l}),e==="error"&&t&&(0,Wt.jsx)("p",{style:g,children:t}),(0,Wt.jsx)("style",{children:`
3
+ ${dn.join(`
4
+ `)}`]}):null;return Je&&!nn?Se?(0,Jn.jsx)("div",{children:pt}):null:(0,Jn.jsxs)("div",{children:[pt,z&&(0,Jn.jsx)(ro,{identity:z.identity,methodLabel:z.methodLabel,testId:"flopay-direct-paypal-identity-pane",onComplete:D,onCancel:()=>D(null)}),(0,Jn.jsxs)("div",{"aria-hidden":O||z?!0:void 0,style:O||z?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:ua},children:[!me&&!O&&(0,Jn.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,Jn.jsx)("div",{ref:we,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,role:"group","aria-label":"PayPal payment method",style:{minHeight:ua,display:"flex",opacity:me?1:0},"aria-busy":Xe||K},Ke)]},Ke),Z&&(0,Jn.jsx)("button",{ref:_,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:E,style:nc,children:"Try PayPal again"})]})}function Mo(e){return(0,Jn.jsx)(hs,{...e})}function bs(e){return(0,Jn.jsx)(hs,{...e})}var Bo=require("react/jsx-runtime");function io({children:e,margin:t,icon:n=!0,styleOverride:r}){return(0,Bo.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,Bo.jsx)("svg",{"aria-hidden":"true",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:(0,Bo.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 pa=require("@flopay/shared");function so(){return typeof window<"u"&&typeof window.sessionStorage<"u"}var ti=":idempotency-key";function ni(e,t){if(!so())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 ri(e,t){if(!so())return null;try{let n=window.sessionStorage.getItem(e+ti);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 ma(e,t){if(so())try{ni(e,t)&&window.sessionStorage.removeItem(e)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout session cache.",n)}}function ya(e,t){if(ma(e,t),!!so())try{ri(e,t)&&window.sessionStorage.removeItem(e+ti)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout idempotency key.",n)}}function fa(e,t,n,r){if(so())try{window.sessionStorage.setItem(e,JSON.stringify(r?{canonicalIdentity:t,sid:n,nonce:r}:{canonicalIdentity:t,sid:n}))}catch(o){console.warn("[FloPayCheckout] Failed to persist checkout session cache.",o)}}function ga(e,t,n){if(so())try{window.sessionStorage.setItem(e+ti,JSON.stringify({canonicalIdentity:t,idempotencyKey:n}))}catch(r){console.warn("[FloPayCheckout] Failed to persist checkout idempotency key.",r)}}function ei(e,t){return`${e}:${t.totalAmount??""}:${t.overrideAmount??""}:${t.quantity??1}:${t.currency??""}`}function uc(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 lo(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=>ei(`${o.type??""}:${o.code??o.providerItemId??o.providerPlanId??""}`,o)).sort(),i:e?.items?.map(o=>ei(o.code??o.providerItemId??"",o)).sort(),s:e?.subscriptions?.map(o=>ei(o.code??o.providerPlanId??"",o)).sort(),couponCodes:e?.couponCodes?[...e.couponCodes].sort():void 0,checkoutMetadata:uc(e?.checkoutMetadata),...t?{tagsData:e?.tagsData,utmMetadata:e?.utmMetadata,tokenizedData:e?.tokenizedData,checkoutMode:e?.checkoutMode??"full"}:{}};return JSON.stringify(r)}function vs(e,t=!1){let n=lo(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,pa.resolveSessionCurrency)(t.currency,t.items,t.subscriptions,t.products);if(!o||e.currency.toUpperCase()!==o.toUpperCase())return!1;let a=(t.products??(0,pa.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,p)=>`${y.code}:${y.type??""}`.localeCompare(`${p.code}:${p.type??""}`)),l=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,p)=>`${y.code}:${y.type??""}`.localeCompare(`${p.code}:${p.type??""}`));if(a.length!==l.length)return!1;for(let[y,p]of a.entries()){let b=l[y];if(b===void 0||p.code!==b.code||p.type!==void 0&&p.type!==b.type||p.quantity!==b.quantity||p.totalAmount!==b.totalAmount||p.overrideAmount!==b.overrideAmount||p.currency!==b.currency)return!1}let c=[...t.couponCodes??[]].sort(),f=[...e.coupons??[]].sort();return c.length===f.length&&c.every((y,p)=>y===f[p])}var en=require("react/jsx-runtime");var pc={panel:{background:"white"},spinnerTrackColor:"#e5e7eb",spinnerAccentColor:"#4A49FF",labelColors:{processing:"#374151",success:"#16a34a",error:"#dc2626"},noteColor:"#6b7280"};function Xn({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=pc}){let f={fontSize:13,color:c.noteColor,fontWeight:400,maxWidth:260,lineHeight:1.4,margin:0};return(0,en.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,en.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,en.jsxs)("div",{style:{width:48,height:48,position:"relative"},children:[e==="processing"&&(0,en.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,en.jsx)("circle",{cx:"12",cy:"12",r:"10",stroke:c.spinnerTrackColor,strokeWidth:"3"}),(0,en.jsx)("path",{d:"M4 12a8 8 0 018-8v3a5 5 0 00-5 5H4z",fill:c.spinnerAccentColor})]}),e==="success"&&(0,en.jsx)("div",{style:{animation:"flopay-pop 0.4s cubic-bezier(0.34,1.56,0.64,1)"},children:(0,en.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,en.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#22c55e"}),(0,en.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,en.jsx)("div",{style:{animation:"flopay-shake 0.4s ease"},children:(0,en.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,en.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#ef4444"}),(0,en.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,en.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,en.jsx)("p",{style:f,children:l}),e==="error"&&t&&(0,en.jsx)("p",{style:f,children:t}),(0,en.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 bs=require("@flopay/shared"),rn=require("react");var vs=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,g]=(0,rn.useState)(t instanceof Promise||!t?null:t),y=(0,rn.useRef)(null),m=(0,rn.useRef)(null),v=eo(r);(0,rn.useEffect)(()=>{v({class:"lifecycle",name:"checkout.mount"})},[v]),(0,rn.useEffect)(()=>{a&&v({class:"lifecycle",name:"sdk.initialize.ready"})},[v,a]),(0,rn.useEffect)(()=>{if(a)return Xt(a)?.subscribe?.(v)},[v,a]),(0,rn.useEffect)(()=>{if(!(!c||c===a))return Xt(c)?.subscribe?.(v)},[v,a,c]),(0,rn.useEffect)(()=>{if(!a)return;let D=Xt(a);return y.current=D?.beginCheckout()??D?.now()??0,D?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{D?.log({name:"checkout.unmount",stage:"unmount"})}},[a]),(0,rn.useEffect)(()=>{let D=!1;return e instanceof Promise?e.then(N=>{D||l(N)},()=>{D||v({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"})}):l(e),()=>{D=!0}},[v,e]),(0,rn.useEffect)(()=>{let D=!1;if(!t){g(null);return}return t instanceof Promise?t.then(N=>{D||g(N)},()=>{D||v({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED",provider:"paypal"})}):g(t),()=>{D=!0}},[v,t]),(0,rn.useEffect)(()=>{if(!a||m.current===a)return;m.current=a;let D=Xt(a);D?.log({name:"checkout.rendered",stage:"checkout_render"}),v({class:"lifecycle",name:"checkout.rendered"}),D?.performance({stage:"checkout_render",durationMs:D.elapsed(y.current??0),durationMode:"machine"})},[v,a]);let h=(0,bs.resolveBillingApiUrl)(n?.billingApiUrl),w=(0,rn.useMemo)(()=>({flopay:a,paypalFlopay:c,billingApiUrl:h,emitInstrument:v}),[a,c,h,v]);return(0,vs.jsx)(Ln.Provider,{value:w,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 Ja(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"),Ue=require("@flopay/shared");var Mo="card";async function ic(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 sc(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 Za(e,t){return Object.assign(e,{checkoutMethod:t})}function br(e,t){let n=e instanceof Ue.FloPayError?e:new Ue.FloPayError(e instanceof Error?e.message:"Payment provider failed.","api_error",{code:"provider_runtime_failure"});return Object.assign(n,{checkoutMethod:t,telemetryFailureCategory:"provider_runtime",telemetryRequestCategory:"provider_sdk"})}async function xo(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 lc(e){return e.status==="succeeded"||e.status==="declined"}async function Ss(e){if(typeof document>"u"||typeof window>"u")throw new Ue.FloPayError("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});if(e.signal?.aborted)throw new Ue.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"});let t=3e5,n=1e3,r=15e3,o=`${e.billingApiUrl.replace(/\/$/,"")}/v1/checkouts/sessions/${encodeURIComponent(e.sessionId)}/3ds/complete`,a=async()=>{let m=new AbortController,v=()=>m.abort();e.signal?.aborted?m.abort():e.signal?.addEventListener("abort",v);let h=window.setTimeout(()=>m.abort(),r);try{let w=await fetch(o,{method:"POST",headers:{"x-checkout-session-token":e.nonce,"content-type":"application/json"},body:"{}",signal:m.signal});if(!w.ok)return{status:"unknown"};let D=await w.json().catch(()=>null);return cc(D)}catch{return{status:"unknown"}}finally{window.clearTimeout(h),e.signal?.removeEventListener("abort",v)}},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 g=document.createElement("iframe");g.setAttribute("title","Card authentication"),g.setAttribute("allow","payment"),g.tabIndex=0,g.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(";"),g.src=e.nextActionRedirectUrl,c.appendChild(g),document.body.appendChild(c),g.focus();let y=null;try{y=new URL(e.billingApiUrl,window.location.href).origin}catch{y=null}try{let m=await new Promise((v,h)=>{let w=!1,D=0,N=0,ye=0,W=!1,I=()=>{window.clearTimeout(D),window.clearInterval(N),window.clearTimeout(ye),window.removeEventListener("message",re),g.removeEventListener("load",q),e.signal?.removeEventListener("abort",ue)},ie=async()=>{if(!(w||W)){W=!0;try{let le=await a();if(w||!lc(le))return;w=!0,I(),v(le)}finally{W=!1}}},q=()=>{window.clearTimeout(ye),ye=window.setTimeout(()=>{ie()},250)},ue=()=>{w||(w=!0,I(),h(new Ue.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"})))},re=le=>{if(le.source!==g.contentWindow||y&&le.origin!==y)return;let He=le.data;!He||typeof He!="object"||He.source!=="flopay-vault-3ds-return"||w||(w=!0,I(),v(null))};D=window.setTimeout(()=>{w||(w=!0,I(),h(new Ue.FloPayError("Card authentication timed out.","api_error",{code:"three_ds_timeout"})))},t),N=window.setInterval(()=>{ie()},n),g.addEventListener("load",q),window.addEventListener("message",re),e.signal?.addEventListener("abort",ue),e.signal?.aborted&&ue()});return m||await a()}finally{c.parentNode?.removeChild(c),l?.isConnected&&l.focus()}}function cc(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 Za(new Ue.FloPayError(a,"api_error",{code:(0,Ue.normalizeCheckoutFailureOutcome)(e?.outcome)??(0,Ue.normalizeCheckoutFailureOutcome)(e?.type)??e?.gatewayErrorCode}),r)}function Xa(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 ws(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 g=c,y=[g.stripeClientSecret,g.clientSecret];for(let m of y)if(typeof m=="string"&&m.length>0&&(!t?.requirePaymentIntentClientSecret||da(m)))return m}}}}async function dc({billingApiUrl:e,sessionId:t,nonce:n,responseJson:r}){let o=ws(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(/\/+$/,""),g=t??n.id,y=r??n.clientSecret,m=n.customer?.id??n.accountData?.userId??"",v=n.customer?.email??n.accountData?.email??"",h=n.customer?.firstName??n.accountData?.firstName??"",w=n.customer?.lastName??n.accountData?.lastName??"",D=n.customer?.country??n.accountData?.country??void 0,N=n.customer?.zip??n.accountData?.zip??void 0,W=await new ao.PaymentAPI(c,l===!1?{telemetry:!1}:void 0).processPayment(m,{sessionId:g,nonce:y,paymentMethodCategory:"saved",tokenizedData:o,accountData:{userId:m,email:v,firstName:h,lastName:w,country:D,zip:N},returnUrl:a??Xa(n)});if(W.ok){let q=typeof W.json=="function"?await W.json().catch(()=>null):null;return(0,Ue.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:g,authorizationExpiresAt:typeof q?.authorizationExpiresAt=="string"?q.authorizationExpiresAt:n.authorizationExpiresAt,paymentMethodId:wo(o),checkoutMethod:Cs(o)}}:{type:"success",result:{status:"succeeded",paymentIntentId:o?.threeDSecureActionResultTokenId,paymentMethodId:wo(o),checkoutMethod:Cs(o)}}}let I;try{I=await W.json()}catch(q){throw new Ue.FloPayError("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:W.status,cause:q})}if(I?.type==="paypal_redirect_required"||I?.type==="3ds_required"){let q=ws(I);if(!q)throw new Ue.FloPayError("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:W.status});return{type:I.type,threeDSecureToken:q,paymentMethodId:I.paymentMethodId}}if(I?.gatewayErrorCode==="authentication_required"){let q=await dc({billingApiUrl:c,sessionId:g,nonce:y,responseJson:I});if(q)return q;throw Za(new Ue.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}let ie=new Ue.FloPayError(I?.message??"Payment failed. Please try again.","api_error",{code:I?.code??I?.gatewayErrorCode,declineCode:I?.declineCode??I?.gatewayDeclineReason,statusCode:W.status});throw Object.assign(ie,{telemetryOutcome:(0,Ue.classifyPaymentRejection)(W.status,I)})}async function ua(e,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:a,session:l,returnUrl:c,telemetry:g}){let y=t?.getRawProvider();if(!y)throw br(new Ue.FloPayError("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!r||!e.threeDSecureToken)throw Za(new Ue.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let m=(0,Ue.isSetupIntentClientSecret)(e.threeDSecureToken),v=null,h=e.paymentMethodId,w=await xo(()=>ic(y,e.threeDSecureToken,m),"card");if(w){if(w.error)throw br(new Ue.FloPayError(w.error.message??`Failed to retrieve 3DS ${m?"setup":"payment"} status.`,"api_error",{code:w.error.code}),"card");let N=w.intent;!h&&N?.payment_method&&(typeof N.payment_method=="string"?h=N.payment_method:"id"in N.payment_method&&(h=N.payment_method.id??void 0))}let D=h?await xo(()=>sc(y,e.threeDSecureToken,{payment_method:h,return_url:c??Xa(l)??window.location.href},m),"card"):null;if(D){if(D.error)throw br(new Ue.FloPayError(D.error.message??"3DS authentication failed.","api_error",{code:D.error.code}),"card");v=D.intent}else{let N=await xo(()=>y.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(N.error)throw br(new Ue.FloPayError(N.error.message??"3DS authentication failed.","api_error",{code:N.error.code}),"card");v=(m?N.setupIntent:N.paymentIntent)??null}if(v&&(v.status==="requires_capture"||v.status==="succeeded"||v.status==="processing")){let N=await io({billingApiUrl:o,sessionId:a,session:l,telemetry:g,tokenizedData:{id:v.id,type:"card",threeDSecureActionResultTokenId:v.id},returnUrl:c});return N.type==="success"?{...N.result,paymentIntentId:N.result.paymentIntentId??v.id,paymentMethodId:N.result.paymentMethodId??h}:ua(N,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:a,session:l,returnUrl:c,telemetry:g})}throw br(new Ue.FloPayError("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let m=(n??t)?.getRawProvider();if(!m)throw br(new Ue.FloPayError("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:h}=await xo(()=>m.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(h)throw br(new Ue.FloPayError(h.message??"PayPal authorization failed.","api_error",{code:h.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:v}=await xo(()=>m.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:c??Xa(l)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(v)throw br(new Ue.FloPayError(v.message??"PayPal authorization failed.","api_error",{code:v.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new Ue.FloPayError("Unsupported payment redirect state.","api_error")}function Ao(e){if(e instanceof Ue.FloPayError){let r=Sr(e.message);return r&&r!==e.message?Object.assign(new Ue.FloPayError(r,e.type,{code:e.code,declineCode:e.declineCode,param:e.param,statusCode:e.statusCode}),{checkoutMethod:e.checkoutMethod,telemetryFailureCategory:e.telemetryFailureCategory,telemetryOutcome:e.telemetryOutcome,telemetryRequestCategory:e.telemetryRequestCategory}):e}let t=e instanceof Error?e.message:"Payment failed. Please try again.",n=Sr(t)??t;return new Ue.FloPayError(n,"api_error")}function Qa(e){let t=e.data.stripe?.publishableKey,n=!!e.data.paypal?.publishableKey;if(!t&&!n)throw new Ue.FloPayError("Session advertises no supported gateways (expected `gateways.stripe` and/or `gateways.paypal`).","validation_error");return t?{publishableKey:t,paypalPublishableKey:e.data.stripe?.paypalPublishableKey??t}:{}}function Cs(e){if(e)return e.isPaypal?"paypal":"card"}async function ei({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(y=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",y),null)):Promise.resolve(null)]);if(!l)throw new Ue.FloPayError("The payment provider did not initialize.","authentication_error");let g=null;return a?g=c:t&&(g=l),{flopay:l,paypalFlopay:g}}var vr=require("@flopay/js"),p=require("@flopay/shared"),zt=require("@stripe/react-stripe-js"),s=Xi(require("react"),1);function ks(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 Is={alipay:"https://cdn.flopay.com/sdk-logos/v1/alipay.svg",bancontact:"https://cdn.flopay.com/sdk-logos/v1/bancontact.svg",blik:"https://cdn.flopay.com/sdk-logos/v1/blik.svg",eps:"https://cdn.flopay.com/sdk-logos/v1/eps.svg",giropay:"https://cdn.flopay.com/sdk-logos/v1/giropay.svg",ideal:"https://cdn.flopay.com/sdk-logos/v1/ideal.svg",klarna:"https://cdn.flopay.com/sdk-logos/v1/klarna.svg",p24:"https://cdn.flopay.com/sdk-logos/v1/p24.svg",sepa_debit:"https://cdn.flopay.com/sdk-logos/v1/sepa_debit.svg",wechat_pay:"https://cdn.flopay.com/sdk-logos/v1/wechat_pay.svg"};var ar=require("react");function Rs(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 uc=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 pc(e){let t=e.replace(/^(Webkit|Moz|ms)(?=[A-Z])/,"");return uc.has(t.charAt(0).toLowerCase()+t.slice(1))}function mc(e,t){return typeof t=="number"&&t!==0&&!pc(e)?`${t}px`:String(t).trim()}function Es(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]=mc(n,r)}}}var _s=require("react/jsx-runtime");function so({capture:e,html:t,messageToken:n,expectedOrigin:r,theme:o,containerStyle:a,onReady:l,onError:c,onValidation:g}){let y=(0,ar.useRef)(null),m=(0,ar.useRef)(l),v=(0,ar.useRef)(c),h=(0,ar.useRef)(g);m.current=l,v.current=c,h.current=g;let w=(0,ar.useRef)(o);w.current=o;let D=(0,ar.useRef)(null);return(0,ar.useEffect)(()=>{let N=y.current;if(!N)return;let ye=!0,W=!1,I=()=>{!ye||W||(W=!0,m.current?.())},ie=e.on("ready",()=>{I()}),q=e.on("error",le=>{v.current?.(le.message??"There was a problem loading the secure card form.")}),ue=e.on("validation",le=>{h.current?.(le.message??null)}),re={html:t,...n?{messageToken:n}:{},...r?{expectedOrigin:r}:{},...w.current?{theme:w.current}:{}};return D.current=w.current??null,e.mount(N,re).then(()=>{I()}).catch(le=>{ye&&v.current?.(le instanceof Error?le.message:"Failed to load the secure card form.")}),()=>{ye=!1,ie(),q(),ue(),e.unmount()}},[e,t,n,r]),Fr(()=>{let N=y.current;N&&Es(N,a)},[a]),(0,ar.useEffect)(()=>{o!==void 0&&(o===null&&D.current===null||(D.current=o,e.applyTheme?.(o)))},[e,o]),(0,_s.jsx)("div",{ref:y,"data-testid":"flopay-vault-card-fields"})}var xs=/^#([0-9a-f]{6})$/i,yc=/^#([0-9a-f]{3})$/i,Ms=/^rgb\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)$/i,As=/^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,fc=/^linear-gradient\(\s*(-?\d+(?:\.\d+)?)deg\s*,\s*(.+)\)$/i,gc=/^(-?\d+(?:\.\d+)?)(?:px)?$/,hc=/^(-?\d+(?:\.\d+)?)em$/,bc=/^blur\(\s*(\d+(?:\.\d+)?)(?:px)?\s*\)$/i,vc=/^[a-z][a-z0-9 -]{0,31}$/i,Cc=new Set(["none","uppercase","lowercase","capitalize"]);function Bs(e){if(typeof e!="string")return null;let t=e.trim(),n=xs.exec(t);if(n){let m=Number.parseInt(n[1],16);return{r:m>>16&255,g:m>>8&255,b:m&255,a:null}}let r=yc.exec(t);if(r){let[m,v,h]=r[1].split("").map(w=>Number.parseInt(w+w,16));return{r:m,g:v,b:h,a:null}}let o=Ms.exec(t),a=o?null:As.exec(t),l=o??a;if(!l)return null;let c=Number(l[1]),g=Number(l[2]),y=Number(l[3]);return c>255||g>255||y>255?null:{r:c,g,b:y,a:a?Number(a[4]):null}}function Fs({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(xs.test(t)||Ms.test(t))return t;let n=As.exec(t);if(n&&/^\d/.test(n[4]))return t;let r=Bs(t);return r?Fs(r):void 0}function pa(e,t=.12){let n=Bs(e);if(!n)return e;let r=Math.max(0,Math.min(1,1-t));return Fs({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 Nr(e,t,n){if(typeof e!="number"&&typeof e!="string")return;let r=gc.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=hc.exec(e.trim());if(!r)return;let o=Number(r[1]);return Number.isFinite(o)&&o>=t&&o<=n?o:void 0}function Sc(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,g=a[1]===void 0?c:Number(/^(\d+(?:\.\d+)?)%$/.exec(a[1])?.[1]),y=n[n.length-1]?.position??-1;if(!Number.isFinite(g)||g<0||g>100||g<y)return;n.push({color:l,position:g})}return{type:"linearGradient",angle:0,stops:n}}function wc(e){if(typeof e!="string")return;let t=e.trim(),n=Bo(t);if(n)return{type:"solid",color:n};let r=fc.exec(t);if(!r)return;let o=Number(r[1]);if(!Number.isFinite(o)||o<0||o>360)return;let a=Sc(r[2]);return a&&a.type==="linearGradient"?{...a,angle:o}:void 0}function kc(e){return e.type==="solid"?{type:"solid",color:pa(e.color)}:{...e,stops:e.stops.map(t=>({...t,color:pa(t.color)}))}}function Ic(e){let t=!1,n,r=[];for(let g of Fo(e," ")){if(g.toLowerCase()==="inset"){t=!0;continue}let y=Bo(g);if(y){n=y;continue}let m=Nr(g,-128,128);if(m===void 0)return;r.push(m)}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 Rc(e){if(typeof e!="string")return;let t=e.trim();if(t.toLowerCase()==="none")return[];let n=Fo(t,",").map(Ic);if(!(n.length===0||n.length>4))return n.every(r=>r!==void 0)?n:void 0}function Ts(e){if(typeof e!="string")return;let t=Fo(e,",").map(n=>n.replace(/^['"]|['"]$/g,"").trim()).filter(n=>vc.test(n)).slice(0,4);return t.length>0?t:void 0}function Ec(e){let t=typeof e=="string"?e.trim().split(/\s+/):[e],n=Nr(t[0],0,64),r=Nr(t[1]??t[0],0,64);if(!(n===void 0||r===void 0))return{paddingBlock:n,paddingInline:r}}function _c(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 Ds({appearance:e,buttonsStyles:t,fontFamily:n}){let r=t.submitButton;if(!r)return;let o=e?.variables,a=wc(r.background??r.backgroundColor),l=Bo(o?.colorPrimaryHover),c=l?{type:"solid",color:l}:a&&kc(a),g={fontFamilies:Ts(r.fontFamily)??Ts(n),fontSize:Nr(r.fontSize??t.submitButtonFontSize,10,32)??16,fontWeight:_c(r.fontWeight)??600,letterSpacing:Pc(r.letterSpacing,-.1,.5)??.01,lineHeight:Nr(r.lineHeight,.8,2)??1,textTransform:Cc.has(String(r.textTransform))?r.textTransform:"uppercase"},y=Ec(r.padding),m=Rc(r.boxShadow),v=Nr(r.borderRadius,0,9999),h=typeof r.backdropFilter=="string"?Nr(bc.exec(r.backdropFilter.trim())?.[1],0,40):void 0;return{foregroundColor:Bo(r.color)??"#FFFFFF",...a?{background:a,disabledBackground:a}:{},...c?{hoverBackground:c}:{},typography:g,...y?{spacing:y}:{},...m?{shadow:m}:{},...v===void 0?{}:{borderRadius:v},disabledOpacity:e?.theme==="night"?.8:.6,...h===void 0?{}:{backdropBlur:h}}}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)?pa(r,t):e}function ti(e){if(typeof e=="number"||typeof e=="string")return e}function ma({appearance:e,buttonsStyles:t,layout:n="default"}){let r=e?.variables,o=v=>typeof v=="string"&&v?v:void 0,a=t.submitButton,l=o(r?.colorPrimary)??o(a?.backgroundColor)??"#4A49FF",c=n==="buttons",g=t.nameInput,y=o(g?.fontFamily)??o(r?.fontFamily)??"Poppins, sans-serif",m=Ds({appearance:e,buttonsStyles:t,fontFamily:y});return{primaryColor:l,primaryHoverColor:o(r?.colorPrimaryHover)??lo(l,.12),inputBackgroundColor:o(t.cardInputBackground)??o(r?.colorBackground)??"#ffffff",textColor:o(t.cardInputColor)??o(g?.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:y,fontSize:o(t.cardInputFontSize)??o(r?.fontSizeBase)??"16px",fontWeight:String(ti(g?.fontWeight)??400),borderRadius:o(r?.borderRadius)??"8px",...m?{submitButton:m}:{}}}var d=require("react/jsx-runtime"),ir="flopay_stripe_resume",Ns="flopay_wallet_resume",Hs="fw1",Tc=300*1e3,xc=900,Mc=25e3,Ac=25e3,ni={},ri={};function Bc(e){return e==="provider_sdk"?"PROVIDER_RUNTIME_FAILED":"REQUEST_TIMEOUT"}function Ws(e){return e instanceof p.FloPayError&&(e.type==="validation_error"||e.statusCode===400||e.statusCode===422)}async function fa(e,t,...n){let r=n[2].provider;t?.({class:"lifecycle",name:"payment.intent.started",provider:r});try{return await new vr.PaymentAPI(e,{telemetry:!1}).createSessionIntent(...n)}catch(o){throw Ws(o)||t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"intent_create",provider:r}),o}}var Do="flopay_paypal_resume",Fc=250,Ls="Just a moment \u2014 we are finalizing your order. Please press pay again.";function li(e,t,n){e?.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:"provider_runtime",stage:"provider_load",provider:t,paymentMethodCategory:n,requestCategory:"provider_sdk"})}async function ga({billingApiUrl:e,sessionId:t,nonce:n,request:r}){if(!(!t||!n))try{await new vr.PaymentAPI(e,{telemetry:!1}).reportSessionIntentDecline(t,n,r)}catch{}}function Dc(e){return e instanceof p.FloPayError&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function oi(e){return e?.html?{html:e.html,...e.messageToken?{messageToken:e.messageToken}:{},...e.expectedOrigin?{expectedOrigin:e.expectedOrigin}:{}}:null}function Gs({event:e,fallbackEmail:t,fallbackName:n}){let r=e.billingDetails,o=t?.trim(),a=Mr(n),l=a.firstName?a:Mr(r?.name);return wn({email:(0,p.isValidEmail)(o)?o:r?.email?.trim(),firstName:l.firstName,lastName:l.lastName})}async function Nc({event:e,prepared:t,email:n,billingName:r,methodLabel:o,collect:a}){let l=Gs({event:e,fallbackEmail:t?.accountPatch?.email??n,fallbackName:[t?.accountPatch?.firstName,t?.accountPatch?.lastName].join(" ").trim()||r});return(0,p.isValidEmail)(l.email)?l:a(o,l)}var Lc=`
9
+ `})]})})}var Cs=require("@flopay/shared"),yn=require("react");var Ss=require("react/jsx-runtime");function Fo({flopay:e,paypalFlopay:t,options:n,onInstrument:r,children:o}){let[a,l]=(0,yn.useState)(e instanceof Promise?null:e),[c,f]=(0,yn.useState)(t instanceof Promise||!t?null:t),y=(0,yn.useRef)(null),p=(0,yn.useRef)(null),b=ao(r);(0,yn.useEffect)(()=>{b({class:"lifecycle",name:"checkout.mount"})},[b]),(0,yn.useEffect)(()=>{a&&b({class:"lifecycle",name:"sdk.initialize.ready"})},[b,a]),(0,yn.useEffect)(()=>{if(a)return sn(a)?.subscribe?.(b)},[b,a]),(0,yn.useEffect)(()=>{if(!(!c||c===a))return sn(c)?.subscribe?.(b)},[b,a,c]),(0,yn.useEffect)(()=>{if(!a)return;let B=sn(a);return y.current=B?.beginCheckout()??B?.now()??0,B?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{B?.log({name:"checkout.unmount",stage:"unmount"})}},[a]),(0,yn.useEffect)(()=>{let B=!1;return e instanceof Promise?e.then(N=>{B||l(N)},()=>{B||b({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"})}):l(e),()=>{B=!0}},[b,e]),(0,yn.useEffect)(()=>{let B=!1;if(!t){f(null);return}return t instanceof Promise?t.then(N=>{B||f(N)},()=>{B||b({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED",provider:"paypal"})}):f(t),()=>{B=!0}},[b,t]),(0,yn.useEffect)(()=>{if(!a||p.current===a)return;p.current=a;let B=sn(a);B?.log({name:"checkout.rendered",stage:"checkout_render"}),b({class:"lifecycle",name:"checkout.rendered"}),B?.performance({stage:"checkout_render",durationMs:B.elapsed(y.current??0),durationMode:"machine"})},[b,a]);let h=(0,Cs.resolveBillingApiUrl)(n?.billingApiUrl),w=(0,yn.useMemo)(()=>({flopay:a,paypalFlopay:c,billingApiUrl:h,emitInstrument:b}),[a,c,h,b]);return(0,Ss.jsx)(Yn.Provider,{value:w,children:o})}var ha="flopay_recent_completion_";function co(e){if(!(!e||typeof window>"u"))try{let t={expiresAt:Date.now()+6e4};window.sessionStorage.setItem(ha+e,JSON.stringify(t))}catch{}}function oi(e){if(!e||typeof window>"u")return!1;try{let t=window.sessionStorage.getItem(ha+e);if(!t)return!1;let n=JSON.parse(t);return typeof n?.expiresAt!="number"||n.expiresAt<=Date.now()?(window.sessionStorage.removeItem(ha+e),!1):!0}catch{return!1}}var uo=require("@flopay/js"),Ve=require("@flopay/shared");var Lo="card";async function mc(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 yc(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 ii(e,t){return Object.assign(e,{checkoutMethod:t})}function kr(e,t){let n=e instanceof Ve.FloPayError?e:new Ve.FloPayError(e instanceof Error?e.message:"Payment provider failed.","api_error",{code:"provider_runtime_failure"});return Object.assign(n,{checkoutMethod:t,telemetryFailureCategory:"provider_runtime",telemetryRequestCategory:"provider_sdk"})}async function Do(e,t){try{return await e()}catch(n){throw kr(n,t)}}function ks(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 fc(e){return e.status==="succeeded"||e.status==="declined"}async function Is(e){if(typeof document>"u"||typeof window>"u")throw new Ve.FloPayError("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});if(e.signal?.aborted)throw new Ve.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"});let t=3e5,n=1e3,r=15e3,o=`${e.billingApiUrl.replace(/\/$/,"")}/v1/checkouts/sessions/${encodeURIComponent(e.sessionId)}/3ds/complete`,a=async()=>{let p=new AbortController,b=()=>p.abort();e.signal?.aborted?p.abort():e.signal?.addEventListener("abort",b);let h=window.setTimeout(()=>p.abort(),r);try{let w=await fetch(o,{method:"POST",headers:{"x-checkout-session-token":e.nonce,"content-type":"application/json"},body:"{}",signal:p.signal});if(!w.ok)return{status:"unknown"};let B=await w.json().catch(()=>null);return gc(B)}catch{return{status:"unknown"}}finally{window.clearTimeout(h),e.signal?.removeEventListener("abort",b)}},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 f=document.createElement("iframe");f.setAttribute("title","Card authentication"),f.setAttribute("allow","payment"),f.tabIndex=0,f.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(";"),f.src=e.nextActionRedirectUrl,c.appendChild(f),document.body.appendChild(c),f.focus();let y=null;try{y=new URL(e.billingApiUrl,window.location.href).origin}catch{y=null}try{let p=await new Promise((b,h)=>{let w=!1,B=0,N=0,de=0,K=!1,I=()=>{window.clearTimeout(B),window.clearInterval(N),window.clearTimeout(de),window.removeEventListener("message",se),f.removeEventListener("load",q),e.signal?.removeEventListener("abort",ie)},re=async()=>{if(!(w||K)){K=!0;try{let ee=await a();if(w||!fc(ee))return;w=!0,I(),b(ee)}finally{K=!1}}},q=()=>{window.clearTimeout(de),de=window.setTimeout(()=>{re()},250)},ie=()=>{w||(w=!0,I(),h(new Ve.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"})))},se=ee=>{if(ee.source!==f.contentWindow||y&&ee.origin!==y)return;let Oe=ee.data;!Oe||typeof Oe!="object"||Oe.source!=="flopay-vault-3ds-return"||w||(w=!0,I(),b(null))};B=window.setTimeout(()=>{w||(w=!0,I(),h(new Ve.FloPayError("Card authentication timed out.","api_error",{code:"three_ds_timeout"})))},t),N=window.setInterval(()=>{re()},n),f.addEventListener("load",q),window.addEventListener("message",se),e.signal?.addEventListener("abort",ie),e.signal?.aborted&&ie()});return p||await a()}finally{c.parentNode?.removeChild(c),l?.isConnected&&l.focus()}}function gc(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 Er(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=_r(o)??o;return ii(new Ve.FloPayError(a,"api_error",{code:(0,Ve.normalizeCheckoutFailureOutcome)(e?.outcome)??(0,Ve.normalizeCheckoutFailureOutcome)(e?.type)??e?.gatewayErrorCode}),r)}function ai(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function ba(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}function Rs(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let o of n)if(typeof o=="string"&&o.length>0&&(!t?.requirePaymentIntentClientSecret||ba(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||ba(c)))return c;let l=o.gateways;if(l&&typeof l=="object"){let c=l.stripe;if(c&&typeof c=="object"){let f=c,y=[f.stripeClientSecret,f.clientSecret];for(let p of y)if(typeof p=="string"&&p.length>0&&(!t?.requirePaymentIntentClientSecret||ba(p)))return p}}}}async function hc({billingApiUrl:e,sessionId:t,nonce:n,responseJson:r}){let o=Rs(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 uo.PaymentAPI(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(ba(c))return{type:"3ds_required",threeDSecureToken:c}}catch{}return null}async function po({billingApiUrl:e,sessionId:t,session:n,nonce:r,tokenizedData:o,returnUrl:a,telemetry:l}){let c=e.replace(/\/+$/,""),f=t??n.id,y=r??n.clientSecret,p=n.customer?.id??n.accountData?.userId??"",b=n.customer?.email??n.accountData?.email??"",h=n.customer?.firstName??n.accountData?.firstName??"",w=n.customer?.lastName??n.accountData?.lastName??"",B=n.customer?.country??n.accountData?.country??void 0,N=n.customer?.zip??n.accountData?.zip??void 0,K=await new uo.PaymentAPI(c,l===!1?{telemetry:!1}:void 0).processPayment(p,{sessionId:f,nonce:y,paymentMethodCategory:"saved",tokenizedData:o,accountData:{userId:p,email:b,firstName:h,lastName:w,country:B,zip:N},returnUrl:a??ai(n)});if(K.ok){let q=typeof K.json=="function"?await K.json().catch(()=>null):null;return(0,Ve.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:f,authorizationExpiresAt:typeof q?.authorizationExpiresAt=="string"?q.authorizationExpiresAt:n.authorizationExpiresAt,paymentMethodId:Eo(o),checkoutMethod:ws(o)}}:{type:"success",result:{status:"succeeded",paymentIntentId:o?.threeDSecureActionResultTokenId,paymentMethodId:Eo(o),checkoutMethod:ws(o)}}}let I;try{I=await K.json()}catch(q){throw new Ve.FloPayError("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:K.status,cause:q})}if(I?.type==="paypal_redirect_required"||I?.type==="3ds_required"){let q=Rs(I);if(!q)throw new Ve.FloPayError("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:K.status});return{type:I.type,threeDSecureToken:q,paymentMethodId:I.paymentMethodId}}if(I?.gatewayErrorCode==="authentication_required"){let q=await hc({billingApiUrl:c,sessionId:f,nonce:y,responseJson:I});if(q)return q;throw ii(new Ve.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}let re=new Ve.FloPayError(I?.message??"Payment failed. Please try again.","api_error",{code:I?.code??I?.gatewayErrorCode,declineCode:I?.declineCode??I?.gatewayDeclineReason,statusCode:K.status});throw Object.assign(re,{telemetryOutcome:(0,Ve.classifyPaymentRejection)(K.status,I)})}async function va(e,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:a,session:l,returnUrl:c,telemetry:f}){let y=t?.getRawProvider();if(!y)throw kr(new Ve.FloPayError("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!r||!e.threeDSecureToken)throw ii(new Ve.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let p=(0,Ve.isSetupIntentClientSecret)(e.threeDSecureToken),b=null,h=e.paymentMethodId,w=await Do(()=>mc(y,e.threeDSecureToken,p),"card");if(w){if(w.error)throw kr(new Ve.FloPayError(w.error.message??`Failed to retrieve 3DS ${p?"setup":"payment"} status.`,"api_error",{code:w.error.code}),"card");let N=w.intent;!h&&N?.payment_method&&(typeof N.payment_method=="string"?h=N.payment_method:"id"in N.payment_method&&(h=N.payment_method.id??void 0))}let B=h?await Do(()=>yc(y,e.threeDSecureToken,{payment_method:h,return_url:c??ai(l)??window.location.href},p),"card"):null;if(B){if(B.error)throw kr(new Ve.FloPayError(B.error.message??"3DS authentication failed.","api_error",{code:B.error.code}),"card");b=B.intent}else{let N=await Do(()=>y.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(N.error)throw kr(new Ve.FloPayError(N.error.message??"3DS authentication failed.","api_error",{code:N.error.code}),"card");b=(p?N.setupIntent:N.paymentIntent)??null}if(b&&(b.status==="requires_capture"||b.status==="succeeded"||b.status==="processing")){let N=await po({billingApiUrl:o,sessionId:a,session:l,telemetry:f,tokenizedData:{id:b.id,type:"card",threeDSecureActionResultTokenId:b.id},returnUrl:c});return N.type==="success"?{...N.result,paymentIntentId:N.result.paymentIntentId??b.id,paymentMethodId:N.result.paymentMethodId??h}:va(N,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:a,session:l,returnUrl:c,telemetry:f})}throw kr(new Ve.FloPayError("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let p=(n??t)?.getRawProvider();if(!p)throw kr(new Ve.FloPayError("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:h}=await Do(()=>p.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(h)throw kr(new Ve.FloPayError(h.message??"PayPal authorization failed.","api_error",{code:h.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:b}=await Do(()=>p.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:c??ai(l)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(b)throw kr(new Ve.FloPayError(b.message??"PayPal authorization failed.","api_error",{code:b.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new Ve.FloPayError("Unsupported payment redirect state.","api_error")}function No(e){if(e instanceof Ve.FloPayError){let r=_r(e.message);return r&&r!==e.message?Object.assign(new Ve.FloPayError(r,e.type,{code:e.code,declineCode:e.declineCode,param:e.param,statusCode:e.statusCode}),{checkoutMethod:e.checkoutMethod,telemetryFailureCategory:e.telemetryFailureCategory,telemetryOutcome:e.telemetryOutcome,telemetryRequestCategory:e.telemetryRequestCategory}):e}let t=e instanceof Error?e.message:"Payment failed. Please try again.",n=_r(t)??t;return new Ve.FloPayError(n,"api_error")}function si(e){let t=e.data.stripe?.publishableKey,n=!!e.data.paypal?.publishableKey;if(!t&&!n)throw new Ve.FloPayError("Session advertises no supported gateways (expected `gateways.stripe` and/or `gateways.paypal`).","validation_error");return t?{publishableKey:t,paypalPublishableKey:e.data.stripe?.paypalPublishableKey??t}:{}}function ws(e){if(e)return e.isPaypal?"paypal":"card"}async function li({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,uo.loadFloPay)(e,{billingApiUrl:n,locale:r,telemetry:o}),a?(0,uo.loadFloPay)(a,{billingApiUrl:n,locale:r,telemetry:o}).catch(y=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",y),null)):Promise.resolve(null)]);if(!l)throw new Ve.FloPayError("The payment provider did not initialize.","authentication_error");let f=null;return a?f=c:t&&(f=l),{flopay:l,paypalFlopay:f}}var Ir=require("@flopay/js"),u=require("@flopay/shared"),Ht=require("@stripe/react-stripe-js"),s=ns(require("react"),1);var _s={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 mr=require("react");function Es(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 bc=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 vc(e){let t=e.replace(/^(Webkit|Moz|ms)(?=[A-Z])/,"");return bc.has(t.charAt(0).toLowerCase()+t.slice(1))}function Pc(e,t){return typeof t=="number"&&t!==0&&!vc(e)?`${t}px`:String(t).trim()}function Ts(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]=Pc(n,r)}}}var xs=require("react/jsx-runtime");function mo({capture:e,html:t,messageToken:n,expectedOrigin:r,theme:o,containerStyle:a,onReady:l,onError:c,onValidation:f}){let y=(0,mr.useRef)(null),p=(0,mr.useRef)(l),b=(0,mr.useRef)(c),h=(0,mr.useRef)(f);p.current=l,b.current=c,h.current=f;let w=(0,mr.useRef)(o);w.current=o;let B=(0,mr.useRef)(null);return(0,mr.useEffect)(()=>{let N=y.current;if(!N)return;let de=!0,K=!1,I=()=>{!de||K||(K=!0,p.current?.())},re=e.on("ready",()=>{I()}),q=e.on("error",ee=>{b.current?.(ee.message??"There was a problem loading the secure card form.")}),ie=e.on("validation",ee=>{h.current?.(ee.message??null)}),se={html:t,...n?{messageToken:n}:{},...r?{expectedOrigin:r}:{},...w.current?{theme:w.current}:{}};return B.current=w.current??null,e.mount(N,se).then(()=>{I()}).catch(ee=>{de&&b.current?.(ee instanceof Error?ee.message:"Failed to load the secure card form.")}),()=>{de=!1,re(),q(),ie(),e.unmount()}},[e,t,n,r]),Ur(()=>{let N=y.current;N&&Ts(N,a)},[a]),(0,mr.useEffect)(()=>{o!==void 0&&(o===null&&B.current===null||(B.current=o,e.applyTheme?.(o)))},[e,o]),(0,xs.jsx)("div",{ref:y,"data-testid":"flopay-vault-card-fields"})}var Ms=/^#([0-9a-f]{6})$/i,Cc=/^#([0-9a-f]{3})$/i,Bs=/^rgb\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)$/i,Fs=/^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,Sc=/^linear-gradient\(\s*(-?\d+(?:\.\d+)?)deg\s*,\s*(.+)\)$/i,wc=/^(-?\d+(?:\.\d+)?)(?:px)?$/,kc=/^(-?\d+(?:\.\d+)?)em$/,Ic=/^blur\(\s*(\d+(?:\.\d+)?)(?:px)?\s*\)$/i,Rc=/^[a-z][a-z0-9 -]{0,31}$/i,_c=new Set(["none","uppercase","lowercase","capitalize"]);function Ds(e){if(typeof e!="string")return null;let t=e.trim(),n=Ms.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=Cc.exec(t);if(r){let[p,b,h]=r[1].split("").map(w=>Number.parseInt(w+w,16));return{r:p,g:b,b:h,a:null}}let o=Bs.exec(t),a=o?null:Fs.exec(t),l=o??a;if(!l)return null;let c=Number(l[1]),f=Number(l[2]),y=Number(l[3]);return c>255||f>255||y>255?null:{r:c,g:f,b:y,a:a?Number(a[4]):null}}function Ls({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 Oo(e){if(typeof e!="string")return;let t=e.trim();if(Ms.test(t)||Bs.test(t))return t;let n=Fs.exec(t);if(n&&/^\d/.test(n[4]))return t;let r=Ds(t);return r?Ls(r):void 0}function Pa(e,t=.12){let n=Ds(e);if(!n)return e;let r=Math.max(0,Math.min(1,1-t));return Ls({r:Math.round(n.r*r),g:Math.round(n.g*r),b:Math.round(n.b*r),a:n.a})}function zo(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 $r(e,t,n){if(typeof e!="number"&&typeof e!="string")return;let r=wc.exec(String(e).trim());if(!r)return;let o=Number(r[1]);return Number.isFinite(o)&&o>=t&&o<=n?o:void 0}function Ec(e,t,n){if(typeof e!="string")return;let r=kc.exec(e.trim());if(!r)return;let o=Number(r[1]);return Number.isFinite(o)&&o>=t&&o<=n?o:void 0}function Tc(e){let t=zo(e,",");if(t.length<2||t.length>5)return;let n=[];for(let[r,o]of t.entries()){let a=zo(o," "),l=Oo(a[0]);if(!l)return;let c=r/(t.length-1)*100,f=a[1]===void 0?c:Number(/^(\d+(?:\.\d+)?)%$/.exec(a[1])?.[1]),y=n[n.length-1]?.position??-1;if(!Number.isFinite(f)||f<0||f>100||f<y)return;n.push({color:l,position:f})}return{type:"linearGradient",angle:0,stops:n}}function xc(e){if(typeof e!="string")return;let t=e.trim(),n=Oo(t);if(n)return{type:"solid",color:n};let r=Sc.exec(t);if(!r)return;let o=Number(r[1]);if(!Number.isFinite(o)||o<0||o>360)return;let a=Tc(r[2]);return a&&a.type==="linearGradient"?{...a,angle:o}:void 0}function Ac(e){return e.type==="solid"?{type:"solid",color:Pa(e.color)}:{...e,stops:e.stops.map(t=>({...t,color:Pa(t.color)}))}}function Mc(e){let t=!1,n,r=[];for(let f of zo(e," ")){if(f.toLowerCase()==="inset"){t=!0;continue}let y=Oo(f);if(y){n=y;continue}let p=$r(f,-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 Bc(e){if(typeof e!="string")return;let t=e.trim();if(t.toLowerCase()==="none")return[];let n=zo(t,",").map(Mc);if(!(n.length===0||n.length>4))return n.every(r=>r!==void 0)?n:void 0}function As(e){if(typeof e!="string")return;let t=zo(e,",").map(n=>n.replace(/^['"]|['"]$/g,"").trim()).filter(n=>Rc.test(n)).slice(0,4);return t.length>0?t:void 0}function Fc(e){let t=typeof e=="string"?e.trim().split(/\s+/):[e],n=$r(t[0],0,64),r=$r(t[1]??t[0],0,64);if(!(n===void 0||r===void 0))return{paddingBlock:n,paddingInline:r}}function Dc(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 Ns({appearance:e,buttonsStyles:t,fontFamily:n}){let r=t.submitButton;if(!r)return;let o=e?.variables,a=xc(r.background??r.backgroundColor),l=Oo(o?.colorPrimaryHover),c=l?{type:"solid",color:l}:a&&Ac(a),f={fontFamilies:As(r.fontFamily)??As(n),fontSize:$r(r.fontSize??t.submitButtonFontSize,10,32)??16,fontWeight:Dc(r.fontWeight)??600,letterSpacing:Ec(r.letterSpacing,-.1,.5)??.01,lineHeight:$r(r.lineHeight,.8,2)??1,textTransform:_c.has(String(r.textTransform))?r.textTransform:"uppercase"},y=Fc(r.padding),p=Bc(r.boxShadow),b=$r(r.borderRadius,0,9999),h=typeof r.backdropFilter=="string"?$r(Ic.exec(r.backdropFilter.trim())?.[1],0,40):void 0;return{foregroundColor:Oo(r.color)??"#FFFFFF",...a?{background:a,disabledBackground:a}:{},...c?{hoverBackground:c}:{},typography:f,...y?{spacing:y}:{},...p?{shadow:p}:{},...b===void 0?{}:{borderRadius:b},disabledOpacity:e?.theme==="night"?.8:.6,...h===void 0?{}:{backdropBlur:h}}}function yo(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)?Pa(r,t):e}function ci(e){if(typeof e=="number"||typeof e=="string")return e}function Ca({appearance:e,buttonsStyles:t,layout:n="default"}){let r=e?.variables,o=b=>typeof b=="string"&&b?b:void 0,a=t.submitButton,l=o(r?.colorPrimary)??o(a?.backgroundColor)??"#4A49FF",c=n==="buttons",f=t.nameInput,y=o(f?.fontFamily)??o(r?.fontFamily)??"Poppins, sans-serif",p=Ns({appearance:e,buttonsStyles:t,fontFamily:y});return{primaryColor:l,primaryHoverColor:o(r?.colorPrimaryHover)??yo(l,.12),inputBackgroundColor:o(t.cardInputBackground)??o(r?.colorBackground)??"#ffffff",textColor:o(t.cardInputColor)??o(f?.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:y,fontSize:o(t.cardInputFontSize)??o(r?.fontSizeBase)??"16px",fontWeight:String(ci(f?.fontWeight)??400),borderRadius:o(r?.borderRadius)??"8px",...p?{submitButton:p}:{}}}var d=require("react/jsx-runtime"),yr="flopay_stripe_resume",Os="flopay_wallet_resume",Gs="fw1",Lc=300*1e3,Nc=900,Oc=25e3,zc=25e3,di={},ui={};function Uc(e){return e==="provider_sdk"?"PROVIDER_RUNTIME_FAILED":"REQUEST_TIMEOUT"}function Ys(e){return e instanceof u.FloPayError&&(e.type==="validation_error"||e.statusCode===400||e.statusCode===422)}async function wa(e,t,...n){let r=n[2].provider;t?.({class:"lifecycle",name:"payment.intent.started",provider:r});try{return await new Ir.PaymentAPI(e,{telemetry:!1}).createSessionIntent(...n)}catch(o){throw Ys(o)||t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"intent_create",provider:r}),o}}var Uo="flopay_paypal_resume",qc=250,zs="Just a moment \u2014 we are finalizing your order. Please press pay again.";function gi(e,t,n){e?.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:"provider_runtime",stage:"provider_load",provider:t,paymentMethodCategory:n,requestCategory:"provider_sdk"})}async function ka({billingApiUrl:e,sessionId:t,nonce:n,request:r}){if(!(!t||!n))try{await new Ir.PaymentAPI(e,{telemetry:!1}).reportSessionIntentDecline(t,n,r)}catch{}}function $c(e){return e instanceof u.FloPayError&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function pi(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=Nr(n),l=a.firstName?a:Nr(r?.name);return Dn({email:(0,u.isValidEmail)(o)?o:r?.email?.trim(),firstName:l.firstName,lastName:l.lastName})}async function jc({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 Vc=`
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 @@ ${Ut.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
- `,ya=44,No=280,Os=`flopay-card-enter ${No}ms cubic-bezier(0, 0, 0.2, 1) both`,zs=`flopay-card-exit ${No}ms cubic-bezier(0.4, 0, 0.2, 1) both`,Oc=`flopay-buttons-enter ${No}ms cubic-bezier(0, 0, 0.2, 1) both`,zc=`flopay-buttons-exit ${No}ms cubic-bezier(0.4, 0, 0.2, 1) both`;function Uc(e){return e.gateway==="stripe"?"stripe":e.gateway==="paypal"||e.isPaypal?"paypal":void 0}function ci(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 qc={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"};function $c(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 Ys={width:"100%",minHeight:ya,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 Vc(e){switch(e){case"paypal":return"PayPal";case"apple_pay":return"Apple Pay";case"google_pay":return"Google Pay";default:return"Card"}}function Us(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function ii(e){return e==="paypal"?"PayPal":(0,p.getStripeMethodDisplayName)(e)}function jc(e,t){let n=`We couldn't open ${ii(e)}. Try again or choose another payment method.`;return t?`${n} Allow pop-ups for this site, then try again.`:n}function Kc(e){let t=(0,p.getPostalCodeExample)(e);return`Enter a valid ${(0,p.getPostalCodeLabel)(e)}${t?` (e.g. ${t})`:""}`}function Hc(e,t,n){let r=(0,p.isPostalCodeSupported)(e),o=t.trim(),a=n&&r,l=a&&!o,c=a&&!!o&&!(0,p.isValidPostalCode)(e,o);return{visible:n,supported:r,required:a,empty:l,malformed:c}}function Wc(e,t){let n=e.trim(),r=t&&!n,o=t&&!!n&&!(0,p.isValidEmail)(n);return{required:t,empty:r,malformed:o,value:n}}function qs(e,t){return t instanceof p.FloPayError?t:new p.FloPayError(t instanceof Error?t.message:`${Vc(e)} before-click hook failed.`,"validation_error")}function ai(){return(0,d.jsx)("style",{children:Lc})}function Gc(e){return typeof e=="number"?`${e}px`:e}function Js(e,t){let n=e.availablePaymentMethods;return n&&t.some(r=>n[r])?"ready":"unavailable"}function Xs({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 $s(e){return e!=="unavailable"&&e!=="load_error"}function ha(e){return(0,d.jsx)(Jc,{...e})}function Vs({sessionId:e,nonce:t,email:n,billingApiUrl:r,onTokenizedBody:o,onErrorChange:a,isProcessing:l=!1,onButtonClick:c,onDecline:g,onTechnicalFailure:y,runBeforeButtonClick:m,billingName:v,onBuyerIdentityReady:h,onLoadStateChange:w,placeholderBorderRadius:D}){let N=hr(),{emitInstrument:ye}=(0,s.useContext)(Ln),W=(0,zt.useStripe)(),I=(0,zt.useElements)(),[ie,q]=(0,s.useState)("loading");(0,s.useEffect)(()=>{w?.(ie)},[ie,w]);let[ue,re]=(0,s.useState)(!1),le=!(0,p.isValidEmail)(n?.trim())||!v?.trim(),{request:He,collect:ce,finish:Rt}=Xr(),Ge=(0,s.useRef)(!1),Te=(0,s.useRef)(null),xe=(0,s.useRef)(null),[oe,ae]=(0,s.useState)(0),[z,De]=(0,s.useState)(!1),Ne=(0,s.useRef)(!1),Ee=(0,s.useRef)(new Map),{startAttempt:Oe,finishAttempt:ke,invalidateAttempt:k,isAttemptInvalidated:de,isAttemptCurrent:he}=Ro((ee,J,$)=>{y?.(ee,J,{...$,popupBlocked:$?.popupBlocked??wr(J)}),De(!0),ae(qe=>qe+1)});(0,s.useEffect)(()=>{z&&xe.current?.focus()},[z,oe]);let Y=(0,s.useCallback)(()=>{ae(ee=>ee+1)},[]),L=(0,s.useCallback)((ee,J,$)=>{k($),y?.("paypal",ee,{code:J,popupBlocked:wr(ee)}),De(!0),Y()},[k,y,Y]),Ie=(0,s.useCallback)(()=>{window.setTimeout(()=>{(Te.current?.querySelector("iframe")??Te.current)?.focus()},0)},[]);(0,s.useEffect)(()=>{Ne.current&&(Ne.current=!1,Ie())},[Ie,oe]);let tt=(0,s.useCallback)(()=>{De(!1),a?.(null),Ie()},[Ie,a]);(0,s.useEffect)(()=>{if(!W||Ge.current)return;let ee=new URLSearchParams(window.location.search),J=ee.get("payment_intent"),$=ee.get("payment_intent_client_secret"),qe=ee.get("redirect_status");if(!J||!$)return;Ge.current=!0;let et;try{let Je=localStorage.getItem(Do);if(Je){let te=JSON.parse(Je);te.clientSecret===$&&(et={...te.accountPatch?{accountPatch:te.accountPatch}:{},...te.sessionId?{sessionId:te.sessionId}:{},...te.nonce?{nonce:te.nonce}:{}})}}catch{}try{localStorage.removeItem(Do)}catch{}let ve=new URL(window.location.href);ve.searchParams.delete("payment_intent"),ve.searchParams.delete("payment_intent_client_secret"),ve.searchParams.delete("redirect_status"),window.history.replaceState({},"",ve.toString()),(async()=>{try{if(re(!0),qe==="failed"){let V="PayPal payment was declined. Please try again.";a?.(V),g?.(tn("paypal",V));return}let{paymentIntent:Je,error:te}=await W.retrievePaymentIntent($);if(te){a?.(te.message??"Failed to retrieve PayPal payment status.");return}if(Je&&(Je.status==="requires_capture"||Je.status==="succeeded")){let V=typeof Je.payment_method=="string"?Je.payment_method:Je.payment_method?.id;o({id:V??Je.id,type:"card",threeDSecureActionResultTokenId:Je.id,isPaypal:!0},et)}else{let V="PayPal payment was not completed. Please try again.";a?.(V),g?.(tn("paypal",V))}}catch(Je){a?.(Je instanceof Error?Je.message:"Failed to complete PayPal payment.")}finally{re(!1)}})()},[W,o,a,g]);let gt=(0,s.useCallback)(async ee=>{if(l||ue){ee.reject();return}let J=m?await m("paypal"):{proceed:!0};if(!J.proceed){Ee.current.delete(oe),ee.reject();return}let $=Oe("paypal");Ee.current.set(oe,{generation:$,accountPatch:J.accountPatch,sessionId:J.sessionId,nonce:J.nonce}),De(!1),c?.("paypal"),ee.resolve()},[l,c,m,Oe,ue,oe]),Ye=(0,s.useCallback)(async ee=>{if(!W||!I)return;let J=Ee.current.get(oe);if(J&&!he(J.generation)){Ee.current.delete(oe);return}if(!J&&de()||J&&!ke(J.generation))return;J||ke();let $=J??null;if(Ee.current.delete(oe),!$&&m){let V=await m("paypal");if(!V.proceed){ee.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}$={accountPatch:V.accountPatch,sessionId:V.sessionId,nonce:V.nonce}}let qe=$?.sessionId??e,et=$?.nonce??t,ve=await Nc({event:ee,prepared:$,email:n,billingName:v,methodLabel:"PayPal",collect:ce});if(!ve){ee.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let Je=ve.email,te={...$?.accountPatch,...wn(ve,!0)};try{if(re(!0),a?.(null),!qe||!(0,p.isValidEmail)(Je))throw new Error("Missing sessionId or email for PayPal payment");await h?.(ve);let V=W.createPaymentMethod,{error:nt,paymentMethod:B}=await V({type:"paypal"});if(nt){L(nt,"stripe_paypal_create_payment_method_failed",J?.generation),ee.paymentFailed({reason:"fail"});return}let Q=await fa(r,ye,qe,et??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:B?.id??null,intentKind:"payment"});if(Q.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let ze=Q.clientSecret,pe={return_url:window.location.href};if(B?.id&&(pe.payment_method=B.id),typeof window<"u")try{localStorage.setItem(Do,JSON.stringify({clientSecret:ze,sessionId:qe,nonce:et,accountPatch:te}))}catch{}let{error:lt,paymentIntent:ct}=await W.confirmPayment({clientSecret:ze,confirmParams:pe,redirect:"if_required"});if(lt){if(typeof window<"u")try{localStorage.removeItem(Do)}catch{}if(ko(lt)){let O=lt.message??"Your payment was declined.";a?.(O),g?.(tn("paypal",O,{code:gr(lt),declineCode:Qr(lt)})),await ga({billingApiUrl:r,sessionId:qe,nonce:et,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:gr(lt)??"provider_declined"}})}else L(lt,"stripe_paypal_confirm_failed",J?.generation);return}if(typeof window<"u")try{localStorage.removeItem(Do)}catch{}let T=typeof ct?.payment_method=="string"?ct.payment_method:ct?.payment_method?.id;o({id:T??ct?.id,type:"card",threeDSecureActionResultTokenId:ct?.id,isPaypal:!0},{accountPatch:te,paymentMethodCategory:"paypal",sessionId:qe,nonce:et});return}catch(V){L(V,"stripe_paypal_failed",J?.generation)}finally{re(!1)}},[W,I,e,t,n,v,ce,h,r,ye,o,a,g,m,L,ke,he,de,oe]);return(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)(Xs,{state:ie,placeholderTestId:"flopay-paypal-placeholder",borderRadius:D,children:(0,d.jsxs)("div",{ref:Te,tabIndex:-1,"data-testid":"flopay-paypal-focus-target",role:"group","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[z&&(0,d.jsx)("button",{ref:xe,type:"button","data-testid":"flopay-paypal-retry-button",onClick:tt,style:Ys,children:"Try PayPal again"}),He&&(0,d.jsx)(Zr,{identity:He.identity,methodLabel:He.methodLabel,onComplete:Rt,onCancel:()=>Rt(null)},He.id),(0,d.jsx)("div",{style:{display:He?"none":void 0},children:(0,d.jsx)(zt.ExpressCheckoutElement,{onReady:ee=>q(Js(ee,["paypal"])),onLoadError:()=>{q("load_error"),li(Xt(N),"paypal","paypal")},onClick:gt,onConfirm:Ye,onCancel:()=>{let ee=Ee.current.get(oe);Ee.current.delete(oe),Xt(N)?.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),k(ee?.generation),De(!1),Ne.current=!0,Y()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:le,emailRequired:le,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},oe)})]})}),ue&&(0,d.jsx)(zn,{status:"processing"})]})}function js({sessionId:e,nonce:t,email:n,billingApiUrl:r,intentKind:o,expressMethods:a,onTokenizedBody:l,onErrorChange:c,onButtonClick:g,onDecline:y,onTechnicalFailure:m,runBeforeButtonClick:v,billingName:h,onBuyerIdentityReady:w,onLoadStateChange:D,placeholderBorderRadius:N}){let ye=hr(),{emitInstrument:W}=(0,s.useContext)(Ln),I=(0,zt.useStripe)(),ie=(0,zt.useElements)(),[q,ue]=(0,s.useState)("loading");(0,s.useEffect)(()=>{D?.(q)},[q,D]);let[re,le]=(0,s.useState)(!1),He=(0,s.useRef)(!(0,p.isValidEmail)(n?.trim())||!h?.trim()).current,{request:ce,collect:Rt,finish:Ge}=Xr(),Te=(0,s.useRef)(null),xe=(0,s.useRef)(null),[oe,ae]=(0,s.useState)(0),[z,De]=(0,s.useState)(!1),[Ne,Ee]=(0,s.useState)("google_pay"),Oe=(0,s.useRef)(!1),ke=(0,s.useRef)("google_pay"),k=(0,s.useRef)("google_pay"),de=(0,s.useRef)(null),he=(0,s.useRef)(new Set);(0,s.useEffect)(()=>()=>{for(let V of he.current)window.clearTimeout(V);he.current.clear()},[]);let Y=(0,s.useRef)(new Map),{startAttempt:L,finishAttempt:Ie,invalidateAttempt:tt,isAttemptInvalidated:gt,isAttemptCurrent:Ye,generationRef:ee}=Ro((V,nt,B)=>{m?.(V,nt,{...B,popupBlocked:B?.popupBlocked??wr(nt)}),Ee(V),De(!0),ae(Q=>Q+1)});(0,s.useEffect)(()=>{z&&xe.current?.focus()},[z,oe]);let J=(0,s.useCallback)(()=>{ae(V=>V+1)},[]),$=(0,s.useCallback)((V,nt,B,Q)=>{tt(Q),m?.(V,nt,{code:B,popupBlocked:wr(nt)}),Ee(V),De(!0),J()},[tt,m,J]),qe=(0,s.useCallback)(()=>{window.setTimeout(()=>{(Te.current?.querySelector("iframe")??Te.current)?.focus()},0)},[]);(0,s.useEffect)(()=>{Oe.current&&(Oe.current=!1,qe())},[qe,oe]);let et=(0,s.useCallback)(()=>{De(!1),c?.(null),qe()},[qe,c]),ve=(0,s.useCallback)(async V=>{let nt=!1,B=$e=>{nt||(nt=!0,V.paymentFailed({reason:"fail",...$e?{message:$e}:{}}))};if(!I||!ie){B();return}let Q=Y.current.get(oe);if(Q&&!Ye(Q.generation)){Y.current.delete(oe),B();return}if(!Q&&gt()){B();return}if(Q&&!Ie(Q.generation)){B();return}Q||Ie();let ze=V.expressPaymentType??Q?.method??ke.current,pe=Q??null,lt=Us(ze),ct;ze==="apple_pay"?ct="apple_pay":ze==="google_pay"&&(ct="google_pay");let T=Q?.generation??ee.current,O=Xt(ye),kt=O?.now()??globalThis.performance?.now()??Date.now(),Le=new AbortController,Ut=!1,cn=!1,X=null,Ft=e,mt="processing",qt="other",Gt="provider_runtime",$t,kn=new Promise(($e,ht)=>{$t=ht}),hn=window.setTimeout(()=>{Ut=!0,Le.abort(),$t(ni)},Mc),Zt=async($e,ht,Qt)=>{mt=$e,qt=ht,Gt=ht==="intent_create"||ht==="session_claim"?"transport_error":"provider_runtime";let Dt=O?.now()??globalThis.performance?.now()??Date.now();try{return await Promise.race([Qt,kn])}finally{let nn=O?.now()??globalThis.performance?.now()??Date.now();O?.performance({stage:$e,durationMs:Math.max(0,nn-Dt),durationMode:"machine",requestCategory:ht,paymentMethodCategory:"wallet",provider:"stripe",...Ut?{statusClass:"timeout"}:{}})}};try{if(le(!0),c?.(null),!pe&&v){let _=await Zt("processing","other",v(lt));if(!_.proceed){B();return}pe={accountPatch:_.accountPatch,sessionId:_.sessionId,nonce:_.nonce}}let $e=pe?.sessionId??e;Ft=$e;let ht=pe?.nonce??t,Qt=de.current??pe?.accountPatch,Dt=Gs({event:V,fallbackEmail:Qt?.email??n,fallbackName:[Qt?.firstName,Qt?.lastName].join(" ").trim()||h});if(!(0,p.isValidEmail)(Dt.email)){B("Buyer details are required."),Rt(ii(ze),Dt).then(_=>{_&&(de.current=_)});return}de.current=null;let nn={...pe?.accountPatch,...wn(Dt,!0)};await Zt("processing","session_claim",Promise.resolve(w?.(Dt)));let{error:Vt}=await Zt("tokenization","provider_sdk",ie.submit());if(Vt){B(),$(ze,Vt,"stripe_wallet_submit_failed",Q?.generation);return}if(!$e)throw new Error("Missing sessionId or email for payment.");let Ze=await Zt("processing","intent_create",fa(r,W,$e,ht??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:ze,paymentMethodId:null,intentKind:o},{signal:Le.signal}));if(Ze.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Yt=Ze.clientSecret;window.clearTimeout(hn),cn=!0,O?.performance({stage:"callback",durationMs:Math.max(0,(O?.now()??globalThis.performance?.now()??Date.now())-kt),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe"});let vt=O?.now()??globalThis.performance?.now()??Date.now(),dn={stage:"provider_confirmation",provider:"stripe",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",...ct?{walletType:ct}:{},attempt:T},at=!1;O?.log({name:"payment.provider_confirmation.started",...dn}),X=window.setTimeout(()=>{X!==null&&he.current.delete(X),at=!0;let _=O?.now()??globalThis.performance?.now()??Date.now();O?.error({errorCode:"PROVIDER_RUNTIME_FAILED",...dn,operationOutcome:"watchdog_expired",checkoutSessionId:$e,durationMs:Math.max(0,_-vt),statusClass:"timeout",failureCategory:"provider_runtime"}),O?.flush?.().catch(()=>{})},Ac),he.current.add(X);let jt=_=>{X!==null&&(window.clearTimeout(X),he.current.delete(X),X=null);let Et=O?.now()??globalThis.performance?.now()??Date.now(),Ct=Math.max(0,Et-vt),Nt=_;return at&&(_==="resolved"?Nt="resolved_late":_==="returned_error"?Nt="returned_error_late":Nt="rejected_late"),O?.log({name:"payment.provider_confirmation.returned",...dn,operationOutcome:Nt}),O?.performance({...dn,durationMs:Ct,durationMode:"buyer",operationOutcome:Nt}),{durationMs:Ct,operationOutcome:Nt}},Jt=!1,on=_=>{if(!_||typeof _!="object")return null;let Et=_;if(Et.error)return null;let Ct=Et.setupIntent??Et.paymentIntent,Nt=Ct?.id,en=Ct?.status,un=Et.setupIntent?en==="succeeded":So(typeof en=="string"?en:void 0),bn=Ct?.payment_method,j=null;return typeof bn=="string"?j=bn:typeof bn?.id=="string"&&(j=bn.id),!un||typeof Nt!="string"||!j?null:{intentId:Nt,paymentMethodId:j}},In=_=>{if(Jt||Q&&ee.current!==Q.generation)return;let Et=on(_);if(!Et)return;let{intentId:Ct,paymentMethodId:Nt}=Et;Jt=!0;let en=`${Hs}:${$e}`;if(typeof window<"u")try{localStorage.setItem(en,JSON.stringify({createdAt:Date.now(),sessionId:$e,nonce:ht,accountPatch:nn,paymentMethodId:Nt,providerIntentId:Ct,paymentMethodType:ze}))}catch{}try{l({id:Nt,type:"card",threeDSecureActionResultTokenId:Ct},{accountPatch:nn,paymentMethodCategory:"wallet",sessionId:$e,nonce:ht})}finally{if(typeof window<"u")try{localStorage.removeItem(en)}catch{}}},Kt,Rn;try{let _=await((0,p.isSetupIntentClientSecret)(Yt)?I.confirmSetup({elements:ie,clientSecret:Yt,redirect:"if_required"}):I.confirmPayment({elements:ie,clientSecret:Yt,redirect:"if_required"}));if(!_||typeof _!="object"||(Kt=_,!Kt.error&&!on(Kt)))throw ri;Rn=jt(Kt.error?"returned_error":"resolved")}catch(_){let Et=_===ri,Ct=jt(Et?"returned_error":"rejected");throw O?.error({...Et?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response"}:Va(_),...dn,operationOutcome:Ct.operationOutcome,checkoutSessionId:$e,durationMs:Ct.durationMs,statusClass:"unknown"}),_}let bt=Kt.error;if(bt){if(ko(bt)){let _=bt.message??"Your payment was declined.";B(_),c?.(_),y?.(tn(lt,_,{code:gr(bt),declineCode:Qr(bt)})),ga({billingApiUrl:r,sessionId:$e,nonce:ht,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:ze,providerDeclineReason:gr(bt)??"provider_declined",...Ze.intentKind==="payment"&&Ze.providerObjectId.startsWith("pi_")?{providerIntentId:Ze.providerObjectId}:{}}})}else O?.error({...Va(bt),...dn,operationOutcome:Rn.operationOutcome,checkoutSessionId:$e,durationMs:Rn.durationMs,statusClass:"unknown"}),B(),$(ze,bt,"stripe_wallet_confirm_failed",Q?.generation);return}if(In(Kt),!Jt)throw new Error("Invalid provider returned for APM intent")}catch($e){if($e===ni){let ht=O?.now()??globalThis.performance?.now()??Date.now();O?.error({errorCode:Bc(qt),stage:mt,requestCategory:qt,paymentMethodCategory:"wallet",provider:"stripe",...ct?{walletType:ct}:{},operationOutcome:"watchdog_expired",checkoutSessionId:Ft,durationMs:Math.max(0,ht-kt),statusClass:"timeout",failureCategory:Gt,attempt:T}),O?.flush?.().catch(()=>{})}B(),$(ze,$e,$e===ni?"stripe_wallet_authorization_timeout":"stripe_wallet_failed",Q?.generation)}finally{if(window.clearTimeout(hn),X!==null&&(window.clearTimeout(X),he.current.delete(X)),!cn){let $e=O?.now()??globalThis.performance?.now()??Date.now();O?.performance({stage:"callback",durationMs:Math.max(0,$e-kt),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe",...Ut?{statusClass:"timeout"}:{}})}le(!1)}},[I,ie,e,t,n,h,Rt,w,r,W,o,l,c,y,v,$,Ie,Ye,gt,ee,ye,oe]),Je=(0,s.useMemo)(()=>{let V=["applePay","googlePay","paypal","link","amazonPay","klarna"],nt=new Set(["applePay","googlePay"]),B=new Set(a.map(p.stripeExpressMethodToOptionKey)),Q={};for(let ze of V)B.has(ze)?Q[ze]=nt.has(ze)?"always":"auto":Q[ze]="never";return Q},[a]),te=(0,s.useMemo)(()=>a.map(p.stripeExpressMethodToOptionKey),[a]);return(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)(Xs,{state:q,placeholderTestId:"flopay-wallet-placeholder",borderRadius:N,children:(0,d.jsxs)("div",{ref:Te,tabIndex:-1,"data-testid":"flopay-wallet-focus-target",role:"group","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[z&&(0,d.jsxs)("button",{ref:xe,type:"button","data-testid":"flopay-wallet-retry-button",onClick:et,style:Ys,children:["Try ",ii(Ne)," again"]}),ce&&(0,d.jsx)(Zr,{identity:ce.identity,methodLabel:ce.methodLabel,onComplete:Ge,onCancel:()=>Ge(null)},ce.id),(0,d.jsx)("div",{style:{display:ce?"none":void 0},children:(0,d.jsx)(zt.ExpressCheckoutElement,{onReady:V=>{ue(Js(V,te))},onLoadError:V=>{ue("load_error"),li(Xt(ye),"stripe","wallet")},onClick:async V=>{ke.current=V.expressPaymentType,k.current=Us(V.expressPaymentType);let nt=!0,B=window.setTimeout(()=>{nt=!1,V.reject()},xc),Q=v?await v(k.current):{proceed:!0};if(window.clearTimeout(B),!nt)return;if(!Q.proceed){Y.current.delete(oe),V.reject();return}let ze=L(V.expressPaymentType);Y.current.set(oe,{generation:ze,method:V.expressPaymentType,accountPatch:Q.accountPatch,sessionId:Q.sessionId,nonce:Q.nonce}),De(!1),g?.(k.current),V.resolve()},onConfirm:ve,onCancel:()=>{let V=Y.current.get(oe);Y.current.delete(oe),Xt(ye)?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet"}),tt(V?.generation),De(!1),Oe.current=!0,J()},options:{buttonType:{applePay:"plain",googlePay:"plain"},paymentMethods:Je,emailRequired:He,billingAddressRequired:He,layout:{maxColumns:1,overflow:"never"}}},oe)})]})}),re&&(0,d.jsx)(zn,{status:"processing"})]})}function Zs(e,t){return{...e,paymentMethodTypes:[t],...t==="revolut_pay"||t==="sepa_debit"||t==="us_bank_account"?{setupFutureUsage:"off_session"}:null}}function Yc({method:e,themeId:t,submitting:n=!1,disabled:r=!1,highlighted:o=!1,hasNextStep:a=!1,onClick:l,backgroundColor:c,borderColor:g,textColor:y,borderRadius:m,fontFamily:v}){let h=(0,p.resolveStripeMethodBrandVariant)(e,t),w=Is[e],[D,N]=(0,s.useState)(!1),ye=!!w&&!D,W=h?.backgroundColor??c??"#ffffff",I=h?.borderColor??g??"#d1d5db",ie=h?.textColor??y??"#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:ya,padding:"0 1rem",backgroundColor:W,color:ie,border:`1px solid ${I}`,borderRadius:m??8,fontSize:"0.95rem",fontWeight:600,fontFamily:v,cursor:n||r?"not-allowed":"pointer",opacity:r&&!n?.55:1,animation:n?"flopay-pulse 1.5s ease-in-out infinite":void 0,display:"flex",alignItems:"center",justifyContent:"center",gap:8,transition:"transform 0.1s, opacity 140ms ease-out, border-color 140ms ease-out",boxShadow:o?"0 0 0 2px rgba(74, 73, 255, 0.15)":void 0},children:n?(0,d.jsx)("span",{style:{margin:"0 auto"},children:`Connecting to ${(0,p.getStripeMethodDisplayName)(e)}\u2026`}):(0,d.jsxs)(d.Fragment,{children:[(0,d.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:(0,p.hasVendoredStripeMethodLogo)(e)?8:0},children:[ye?(0,d.jsx)("img",{src:w,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,!ye&&h?.logoSvg?(0,d.jsx)("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:h.logoSvg}}):null,(0,d.jsx)("span",{children:(0,p.getStripeMethodDisplayName)(e)})]}),a&&(0,d.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:ie,strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{position:"absolute",right:"1rem",top:"50%",transform:"translateY(-50%)",flexShrink:0,opacity:.7},"aria-hidden":"true",children:(0,d.jsx)("path",{d:"M9 18l6-6-6-6"})})]})})}function si({method:e,sessionId:t,nonce:n,email:r,billingName:o,onBuyerIdentityReady:a,billingApiUrl:l,onTokenizedBody:c,onErrorChange:g,onDecline:y,onCancel:m,runBeforeButtonClick:v,onButtonClick:h,isProcessing:w,submitButtonColor:D,submitButtonBorderRadius:N,submitButtonStyle:ye,errorText:W}){let I=hr(),{emitInstrument:ie}=(0,s.useContext)(Ln),q=(0,zt.useStripe)(),ue=(0,zt.useElements)(),[re,le]=(0,s.useState)(!1),He=(0,s.useRef)(!1),[ce,Rt]=(0,s.useState)(!1),[Ge,Te]=(0,s.useState)("loading"),[xe,oe]=(0,s.useState)(""),ae=!(0,p.isValidEmail)(r?.trim()),z=!ae||(0,p.isValidEmail)(xe.trim()),De=(0,s.useCallback)(async()=>{if(!q||!ue||w||He.current||!ce)return;He.current=!0,le(!0);let Ne=v?await v("card"):{proceed:!0};if(!Ne.proceed){He.current=!1,le(!1);return}h?.("card");let Ee=Ne.sessionId??t,Oe=Ne.nonce??n,ke=Mr(o?.trim()),k=wn({email:Ne.accountPatch?.email?.trim()||r?.trim()||xe.trim(),firstName:Ne.accountPatch?.firstName?.trim()||ke.firstName,lastName:Ne.accountPatch?.lastName?.trim()||ke.lastName}),de=k.email,he=wn({...Ne.accountPatch,...k});try{if(g?.(null),!(0,p.isValidEmail)(de))throw new Error("A valid email address is required for payment.");await a?.(k);let Y=await ue.submit();if(Y.error){g?.(Y.error.message??"Payment failed.");return}let L=[k.firstName,k.lastName].filter(Boolean).join(" "),Ie=await q.createPaymentMethod({elements:ue,params:{billing_details:{email:de,...L?{name:L}:{}}}});if(Ie.error||!Ie.paymentMethod){g?.(Ie.error?.message??"Failed to create payment method.");return}let tt=Ie.paymentMethod;if(!Ee||!de)throw new Error("Missing sessionId or email for payment.");let gt=tt.type||e,Ye=await fa(l,ie,Ee,Oe??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:gt,paymentMethodId:null,intentKind:"payment"});if(Ye.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let ee=Ye.clientSecret;if(typeof window<"u")try{localStorage.setItem(ir,JSON.stringify({clientSecret:ee,sessionId:Ee,nonce:Oe,accountPatch:he,paymentMethodId:tt.id,paymentMethodType:tt.type??e,gateway:"stripe"}))}catch{}let{error:J,paymentIntent:$}=await q.confirmPayment({clientSecret:ee,confirmParams:{return_url:window.location.href,payment_method:tt.id},redirect:"if_required"});if(J){if(typeof window<"u")try{localStorage.removeItem(ir)}catch{}let ve=J.message??"Payment failed.";g?.(ve),y?.(tn("card",ve,{code:J.code})),await ga({billingApiUrl:l,sessionId:Ee,nonce:Oe,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:J.code??"provider_declined"}});return}let qe=$?.status;if(!So(qe)){if(typeof window<"u")try{localStorage.removeItem(ir)}catch{}let ve=qe==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";g?.(ve),y?.(tn("card",ve,{code:qe??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(ir)}catch{}let et=typeof $?.payment_method=="string"?$.payment_method:$?.payment_method?.id;c({id:et??tt.id,type:"card",threeDSecureActionResultTokenId:$?.id,gateway:"stripe",paymentMethodType:tt.type??e},{accountPatch:he,paymentMethodCategory:"apm",sessionId:Ee,nonce:Oe})}catch(Y){g?.(Y instanceof Error?Y.message:"Payment failed. Please try again.")}finally{He.current=!1,le(!1)}},[q,ue,w,ce,v,h,t,n,r,o,xe,a,l,ie,e,c,g,y]);return(0,d.jsxs)("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[ae&&(0,d.jsx)("div",{"data-testid":"flopay-apm-identity-fields",style:{display:"flex",flexDirection:"column",gap:"0.75rem",marginBottom:"0.75rem"},children:ae&&(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:xe,onChange:Ne=>oe(Ne.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]})}),(0,d.jsx)(zt.PaymentElement,{onReady:()=>Te("ready"),onLoadError:()=>{Te("load_error"),li(Xt(I),"stripe","apm")},onChange:Ne=>{Rt(!!Ne.complete)},options:{layout:{type:"accordion",defaultCollapsed:!1,radios:"never"},fields:{billingDetails:{email:"never"}},defaultValues:{billingDetails:{...o?.trim()?{name:o.trim()}:{},...(0,p.isValidEmail)(r?.trim())?{email:r?.trim()}:{}}}}}),(0,d.jsx)("button",{type:"button","data-testid":`flopay-stripe-method-pay-${e}`,onClick:()=>{De()},disabled:!ce||!z||re||w||Ge!=="ready",style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:D,color:"white",border:"none",borderRadius:N,fontSize:"1rem",fontWeight:600,cursor:!ce||!z||re||w||Ge!=="ready"?"not-allowed":"pointer",opacity:!ce||!z||re||w||Ge!=="ready"?.5:1,transition:"opacity 120ms ease-out",...ye??{}},children:re?"Processing\u2026":`Pay with ${(0,p.getStripeMethodDisplayName)(e)}`}),W&&(0,d.jsx)(to,{margin:"0.75rem 0 0",children:W})]})}function Ks({sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:a,paymentElementMethods:l,stripeInstance:c,paymentElementBaseOptions:g,onTokenizedBody:y,onErrorChange:m,onButtonClick:v,onDecline:h,runBeforeButtonClick:w,onLoadStateChange:D,isProcessing:N=!1,submitButtonColor:ye="#4A49FF",submitButtonBorderRadius:W=8,submitButtonStyle:I,buttonAppearance:ie,themeId:q,onExpandApm:ue,expandedApmMethod:re}){let{emitInstrument:le}=(0,s.useContext)(Ln),[He,ce]=(0,s.useState)(null),[Rt,Ge]=(0,s.useState)(null),Te=(0,s.useRef)(!1),{request:xe,collect:oe,finish:ae}=Xr();(0,s.useEffect)(()=>{l.length>0&&c?D?.("ready"):c||D?.("loading")},[l.length,c,D]);let z=(0,s.useCallback)(async k=>{if(!c||Te.current||N)return;Te.current=!0,Ge(k);let de=w?await w("card"):{proceed:!0};if(!de.proceed){Te.current=!1,Ge(null);return}v?.("card");let he=de.sessionId??e,Y=de.nonce??t,L=Mr([de.accountPatch?.firstName,de.accountPatch?.lastName].filter(Boolean).join(" ")||r),Ie=wn({email:de.accountPatch?.email?.trim()||n?.trim(),firstName:de.accountPatch?.firstName?.trim()||L.firstName,lastName:de.accountPatch?.lastName?.trim()||L.lastName});if(!(0,p.isValidEmail)(Ie.email)){Ge(null);let Ye=await oe((0,p.getStripeMethodDisplayName)(k),Ie);if(!Ye){Te.current=!1;return}Ie=Ye,Ge(k)}let tt=Ie.email,gt=wn({...de.accountPatch,...Ie});try{if(m?.(null),!he||!(0,p.isValidEmail)(tt))throw new Error("Missing sessionId or email for payment.");await o?.(Ie);let Ye=await fa(a,le,he,Y??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:k,paymentMethodId:null,intentKind:"payment"});if(Ye.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let ee=Ye.clientSecret;if(typeof window<"u")try{localStorage.setItem(ir,JSON.stringify({clientSecret:ee,sessionId:he,nonce:Y,accountPatch:gt,paymentMethodType:k,gateway:"stripe"}))}catch{}let{error:J,paymentIntent:$}=await c.confirmPayment({clientSecret:ee,confirmParams:{return_url:window.location.href,payment_method_data:{type:k,billing_details:{name:[Ie.firstName,Ie.lastName].filter(Boolean).join(" "),...tt?{email:tt}:{}}}},redirect:"if_required"});if(J){if(typeof window<"u")try{localStorage.removeItem(ir)}catch{}let ve=J.message??"Payment failed.";m?.(ve),h?.(tn("card",ve,{code:J.code})),await ga({billingApiUrl:a,sessionId:he,nonce:Y,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:k,providerDeclineReason:J.code??"provider_declined"}});return}let qe=$?.status;if(!So(qe)){if(typeof window<"u")try{localStorage.removeItem(ir)}catch{}let ve=qe==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";m?.(ve),h?.(tn("card",ve,{code:qe??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(ir)}catch{}let et=typeof $?.payment_method=="string"?$.payment_method:$?.payment_method?.id;y({id:et??$?.id,type:"card",threeDSecureActionResultTokenId:$?.id,gateway:"stripe",paymentMethodType:k},{accountPatch:gt,paymentMethodCategory:"apm",sessionId:he,nonce:Y})}catch(Ye){m?.(Ye instanceof Error?Ye.message:"Payment failed. Please try again.")}finally{Te.current=!1,Ge(null)}},[c,N,w,v,e,t,n,oe,a,le,r,o,y,m,h]),[De,Ne]=(0,s.useState)(null),Ee=ue?re??null:De,Oe=(0,s.useCallback)(k=>{Te.current||N||Ee&&Ee!==k||((0,p.needsStripeMethodExplicitConfirm)(k)?ue?ue(k):Ne(k):z(k))},[Ee,N,z,ue]),ke=(0,s.useMemo)(()=>De?Zs(g,De):null,[De,g]);return(0,d.jsx)("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:xe?(0,d.jsx)(Zr,{identity:xe.identity,methodLabel:xe.methodLabel,onComplete:ae,onCancel:()=>ae(null)},xe.id):l.map(k=>{let de=re===k,he=Rt===k,Y=Rt!==null&&Rt!==k||re!=null&&re!==k;return(0,d.jsxs)(s.default.Fragment,{children:[(0,d.jsx)(Yc,{method:k,themeId:q,submitting:he,disabled:Y,highlighted:de,hasNextStep:(0,p.needsStripeMethodExplicitConfirm)(k),onClick:()=>Oe(k),backgroundColor:ie?.backgroundColor,borderColor:ie?.borderColor,textColor:ie?.textColor,borderRadius:ie?.borderRadius,fontFamily:ie?.fontFamily}),!ue&&De===k&&ke&&c&&(0,d.jsx)(zt.Elements,{stripe:c,options:ke,children:(0,d.jsx)(si,{method:k,sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:a,onTokenizedBody:y,onErrorChange:m,onDecline:h,onCancel:()=>Ne(null),runBeforeButtonClick:w,onButtonClick:v,isProcessing:N,submitButtonColor:ye,submitButtonBorderRadius:W,submitButtonStyle:I})},k)]},k)})})}function Jc({sessionId:e,nonce:t,billingApiUrl:n,email:r,userId:o,onComplete:a,onError:l,onDecline:c,onTokenizedBody:g,firstName:y,lastName:m,chv:v,className:h,isProcessing:w,error:D,onErrorChange:N,showPayPal:ye=!0,showStripe:W=!0,enabledPaymentMethods:I,enabledPaymentMethodCountries:ie,showApplePay:q=!0,showGooglePay:ue=!0,layout:re="default",theme:le,buttonsTheme:He,buttonsStyles:ce,appearance:Rt,cardButtonContent:Ge,cardBackButtonContent:Te,cardTitleContent:xe,showSecurityFooter:oe,onButtonClick:ae,onBeforeButtonClick:z,onBuyerIdentityReady:De,enableAVS:Ne,cardFieldOrder:Ee,cardPreFormSlot:Oe,avsLayout:ke="row",country:k,zip:de,addressLine1:he,addressLine2:Y,city:L,state:Ie,onCountryChange:tt,onZipChange:gt,avsCheck:Ye,checkoutType:ee,checkoutLayout:J,totalAmount:$=0,currency:qe="usd",initialCardOpen:et=!1,directPaypal:ve,isSubscription:Je=!1,session:te,dataAttachmentPending:V=!1,dataAttachmentRequiresIdentity:nt=!1,debug:B=!1}){let Q=hr(),ze=Qo(),pe=(0,s.useContext)(Zn),{emitInstrument:lt}=(0,s.useContext)(Ln),ct=te??pe.session,T=ct?.gateways?.paypal?.providerObjectType??ve?.providerObjectType,O=V||pe.claimPending===!0,kt=nt||pe.claimRequiresIdentity===!0,Le=O&&!kt,Ut=cs(),[cn,X]=(0,s.useState)(!1),[Ft,mt]=(0,s.useState)(null),[qt,Gt]=(0,s.useState)(k??"US"),[$t,kn]=(0,s.useState)(de??""),[hn,Zt]=(0,s.useState)(he??""),[$e,ht]=(0,s.useState)(Y??""),[Qt,Dt]=(0,s.useState)(L??""),[nn,Vt]=(0,s.useState)(Ie??""),[Ze,Yt]=(0,s.useState)(""),[vt,dn]=(0,s.useState)({}),at=(0,s.useRef)(de??""),jt=(0,s.useRef)(k??"US"),Jt=(0,s.useRef)(he??""),on=(0,s.useRef)(Y??""),In=(0,s.useRef)(L??""),Kt=(0,s.useRef)(Ie??""),Rn=(0,s.useRef)(""),bt=(0,s.useRef)({});(0,s.useEffect)(()=>{let i=(S,G,Be,Z,Pe)=>{if(bt.current[S])return;let Ht=G?.trim();!Ht||Ht===Be.current||(Be.current=Ht,Z(Ht),Pe?.(Ht))};i("country",k,jt,Gt,tt),i("zip",de,at,kn,gt),i("addressLine1",he,Jt,Zt),i("addressLine2",Y,on,ht),i("city",L,In,Dt),i("state",Ie,Kt,Vt)},[k,de,he,Y,L,Ie,tt,gt]);let _=(0,s.useMemo)(()=>(0,p.resolveAVSConfig)(Ne),[Ne]),Et=_!==null,Ct=(0,s.useMemo)(()=>(0,p.isAuthorizationOnlySession)(te),[te]),Nt=!!te?.vault?.html,en=!!te?.gateways?.pcivault,bn=!!(te?.gateways?.stripe?.enabledPaymentMethods??I)?.includes("card"),j=Nt||bn||en,Se=!!(W&&j&&Q&&e),[an,cr]=(0,s.useState)(()=>re!=="buttons"||et?e??null:null),[Ve,Pr]=(0,s.useState)(0),qn=re!=="buttons"||et||!!e&&an===e,dt=(0,s.useMemo)(()=>!Q||!Se||!e||!qn?null:Q.cardCapture({sessionId:e,captureMethod:te?.captureMethod}),[Q,Se,e,qn,te?.captureMethod]),yt=(0,s.useMemo)(()=>{let i=qt,S=_?(0,p.isAVSFieldVisible)(_.postal_code,i):!1;return Hc(i,$t,S)},[_,qt,$t]),{avsInvalid:$n,invalidAvsFields:Vn}=(0,s.useMemo)(()=>{let i={line1:!1,city:!1,state:!1,zip:!1};if(!Se||!_)return{avsInvalid:!1,invalidAvsFields:i};let S=qt,G=(Pe,Ht)=>(0,p.isAVSFieldVisible)(Pe,S)&&!Ht.trim(),Be={line1:G(_.address_line_1,hn),city:G(_.city,Qt),state:G(_.state,nn),zip:yt.empty||yt.malformed};return{avsInvalid:Be.line1||Be.city||Be.state||Be.zip,invalidAvsFields:Be}},[Se,_,qt,hn,Qt,nn,yt]),[dr,En]=(0,s.useState)(!1),[jn,ur]=(0,s.useState)(!1),[Kn,Ir]=(0,s.useState)(!1),[pn,pr]=(0,s.useState)({line1:!1,city:!1,state:!1}),_n=(0,s.useRef)(!1),vn=(0,s.useRef)({email:!1,line1:!1,city:!1,state:!1,zip:!1}),_t=(0,s.useRef)(!1),ot=(0,s.useCallback)(i=>{vn.current[i]=!0,_t.current=!0},[]),Tn=(0,s.useCallback)(i=>!_n.current&&vn.current[i],[]),xn=(0,s.useCallback)(i=>{Tn(i)&&pr(S=>S[i]?S:{...S,[i]:!0})},[Tn]),[sn,Fn]=(0,s.useState)(()=>oi(te?.vault)),[je,mn]=(0,s.useState)(et&&j?"card":"buttons"),[Tt,nr]=(0,s.useState)(null),Rr=je==="expanding"||je==="card",mr=te?.gateways?.stripe?"stripe":void 0,Hn=(0,s.useCallback)(()=>{lt?.({class:"card_surface",provider:mr})},[mr,lt]),Wn=(0,s.useRef)(null),Mn=(0,s.useCallback)(i=>{Wn.current&&clearTimeout(Wn.current),Wn.current=setTimeout(()=>{Wn.current=null,i()},No)},[]);(0,s.useEffect)(()=>()=>{Wn.current&&clearTimeout(Wn.current)},[]);let Gn=(0,s.useCallback)(()=>{Hn(),cr(e??null),Pr(i=>i+1),mn("expanding"),Mn(()=>mn("card"))},[Mn,Hn,e]),Er=(0,s.useCallback)(()=>{mn("collapsing"),Mn(()=>mn("buttons"))},[Mn]),An=(0,s.useCallback)(i=>{nr(i),mn("apm-expanding"),Mn(()=>mn("apm-form"))},[Mn]),Yn=(0,s.useCallback)(()=>{mn("apm-collapsing"),Mn(()=>{mn("buttons"),nr(null)})},[Mn]);(0,s.useEffect)(()=>{re==="buttons"&&et&&j&&(cr(e??null),mn("card"))},[re,et,j,e]);let[ln,rt]=(0,s.useState)(null),Cn=(0,s.useRef)(!1),x=(0,s.useRef)(null),M=(0,s.useRef)("idle"),[K,se]=(0,s.useState)(null),Me=(0,s.useRef)(K);(0,s.useEffect)(()=>{Me.current=K},[K]);let _e=n||Ut,Re=(0,s.useRef)(null),b=(0,s.useMemo)(()=>{if(De||pe.claimBuyerIdentity||te?.buyerIdentified!==!1||!e||!t)return;let i=`${_e}|${e}|${t}`;Re.current?.key!==i&&(Re.current={key:i,claim:Yr(new vr.PaymentAPI(_e,{telemetry:!1}),e,t,{...o?{userId:o}:{},...y?{firstName:y}:{},...m?{lastName:m}:{}})});let S=Re.current.claim;return async G=>{await S(G)}},[De,pe.claimBuyerIdentity,te?.buyerIdentified,e,t,_e,o,y,m]),u=De??pe.claimBuyerIdentity??b,C=D??Ft,U=(0,s.useMemo)(()=>(0,p.resolveTheme)(le),[le]),f=(0,s.useMemo)(()=>{let i=U?.buttonsLayout??(0,p.resolveButtonsLayoutTheme)(He);return ce?{...i,...ce,cardButton:{...i.cardButton,...ce.cardButton},cardFormContainer:{...i.cardFormContainer,...ce.cardFormContainer},backButton:{...i.backButton,...ce.backButton},backButtonIcon:{...i.backButtonIcon,...ce.backButtonIcon},submitButton:{...i.submitButton,...ce.submitButton},title:{...i.title,...ce.title}}:i},[U,He,ce]),E=Rt??U?.appearance,Ae=(0,s.useMemo)(()=>ma({appearance:E,buttonsStyles:f,layout:re}),[E,f,re]),it=pe.inlineSessionPatchProcessing??!1,we=(w??cn)||it,Ce=_e.replace(/\/+$/,""),F=(0,s.useMemo)(()=>$a({userId:o,email:r,firstName:y,lastName:m,country:k,zip:de},vt),[o,r,y,m,k,de,vt]),H=[F.firstName,F.lastName].filter(i=>!!i?.trim()).join(" "),me=!(0,p.isValidEmail)(F.email?.trim()),ne=(0,s.useRef)(null);Se&&ne.current===null&&(ne.current=me);let fe=Se&&(ne.current??me),st=(0,s.useMemo)(()=>Wc(Ze,fe),[Ze,fe]),Xe=st.empty||st.malformed,be=(0,s.useMemo)(()=>Q?Q.getRawProvider():null,[Q]),Pt=(0,s.useMemo)(()=>ze?ze.getRawProvider():null,[ze]),yn=$||100,Or=qe.toLowerCase(),ka=(0,s.useMemo)(()=>E?(0,vr.toStripeAppearance)(E):null,[E]),zr=ka,bi=(0,s.useMemo)(()=>{let i=ka??{},S=i.rules??{};return{...i,rules:{...S,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...S[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...S[".AccordionItemContents"]??{}}}}},[ka]),vi=(0,s.useMemo)(()=>({...as($,te?.captureMethod),currency:Or,...zr?{appearance:zr}:null}),[$,Or,te?.captureMethod,zr]),Ci=(0,s.useMemo)(()=>({mode:"payment",amount:yn,currency:Or,captureMethod:"manual",setupFutureUsage:"off_session",...zr?{appearance:zr}:null}),[yn,Or,zr]),ge=(0,s.useCallback)(i=>{mt(i),N?.(i)},[N]),Ia=(0,s.useRef)(""),[Pi,pl]=(0,s.useState)(!1),Ra=(0,s.useCallback)(()=>{pl(!0)},[]);(0,s.useEffect)(()=>{if(!Se||!fe||!u||!Pi||Xe||Ia.current)return;let i=wn({email:(0,p.isValidEmail)(F.email?.trim())?F.email?.trim():Rn.current.trim(),firstName:F.firstName?.trim(),lastName:F.lastName?.trim()});Ia.current=JSON.stringify(i),dn(S=>({...S,...i})),Promise.resolve(u(i)).catch(S=>{Ia.current="",ge(S instanceof Error?S.message:"Failed to attach buyer details.")})},[Se,fe,u,Pi,Xe,F.email,F.firstName,F.lastName,ge]),(0,s.useEffect)(()=>{!Se||!dt||dt.setCardFieldOrder?.(Ee??null,_==null&&!fe)},[Se,dt,Ee,_,fe]),(0,s.useEffect)(()=>{(je==="expanding"||je==="collapsing"||je==="apm-expanding"||je==="apm-collapsing")&&ge(null)},[je,ge]);let Jn=(0,s.useCallback)((i,S,G)=>{c?.(tn(i,S,G))},[c]),Ur=(0,s.useCallback)((i,S,G)=>{let Be=G?.popupBlocked??wr(S),Z=jc(i,Be),Pe=Br(G?.code)??gr(S)??"external_payment_method_failed",Ht=new p.FloPayError(Z,"api_error",{code:"external_payment_method_failed",param:i});rt(null),re==="buttons"&&(mn("buttons"),nr(null)),ge(Z),l?.(Ht),console.error("[FloPay] External payment method failed:",{method:i,code:Pe,popupBlocked:Be})},[re,l,ge]);(0,s.useEffect)(()=>{if(!Se||!e){Fn(null);return}let i=oi(te?.vault);if(i){Fn(i);return}if(!qn){Fn(null);return}Fn(null);let S=!0;return new vr.PaymentAPI(Ce).getVaultCapture(e,t).then(G=>{if(!S)return;let Be=oi(G);Be?Fn(Be):ge("Failed to load the secure card form.")}).catch(G=>{S&&ge(G instanceof Error?G.message:"Failed to load the secure card form.")}),()=>{S=!1}},[Se,qn,Ve,e,te?.vault,Ce,t,ge]);let rr=(0,s.useRef)({onComplete:a,onError:l,updateError:ge,emitDecline:Jn,resolvedAccount:F,avsConfig:_,avsCheckProp:Ye,sessionId:e,nonce:t,baseUrl:Ce,captureMethod:te?.captureMethod,paymentId:te?.paymentId,authorizationExpiresAt:te?.authorizationExpiresAt});rr.current={onComplete:a,onError:l,updateError:ge,emitDecline:Jn,resolvedAccount:F,avsConfig:_,avsCheckProp:Ye,sessionId:e,nonce:t,baseUrl:Ce,captureMethod:te?.captureMethod,paymentId:te?.paymentId,authorizationExpiresAt:te?.authorizationExpiresAt};let Ea=(0,s.useRef)(!1),Si=(0,s.useCallback)(()=>{let i=rr.current,S=i.resolvedAccount.email?.trim(),G=(0,p.isValidEmail)(S)?S:Rn.current.trim();if(!(0,p.isValidEmail)(G))return null;let Be=i.resolvedAccount.firstName?.trim(),Z=i.resolvedAccount.lastName?.trim(),Pe=jt.current||i.resolvedAccount.country||"US",Ht=i.avsConfig?(0,p.isAVSFieldVisible)(i.avsConfig.state,Pe):!1,We=i.avsConfig?(0,p.isAVSFieldVisible)(i.avsConfig.address_line_1,Pe):!1,Mt=i.avsConfig?(0,p.isAVSFieldVisible)(i.avsConfig.postal_code,Pe):!1,ft=i.avsConfig?(0,p.isAVSFieldVisible)(i.avsConfig.city,Pe):!1,St=i.avsConfig?(0,p.isAVSFieldVisible)(i.avsConfig.address_line_2,Pe):!1,wt=We&&!Ht&&Mt?(0,p.getStateFromPostalCode)(Pe,(at.current??"").trim()):null,yr=Ht?Kt.current:wt;return{accountData:{userId:i.resolvedAccount.userId??"",email:G,...Be?{firstName:Be}:{},...Z?{lastName:Z}:{},...Mt&&at.current?{zip:at.current}:{},...ft&&In.current?{city:In.current}:{},...yr?{state:yr}:{},...We&&Jt.current?{addressLine1:Jt.current}:{},...St&&on.current?{addressLine2:on.current}:{},country:Pe},...i.avsCheckProp===void 0?{}:{avsCheck:i.avsCheckProp},...i.avsConfig?{avsConfig:{country:(0,p.isAVSFieldVisible)(i.avsConfig.country,Pe),postal_code:Mt,address_line_1:We,address_line_2:St,city:ft,state:Ht}}:{}}},[]),wi=(0,s.useRef)(O);wi.current=O,(0,s.useEffect)(()=>{O||C!==Ls||rr.current.updateError(null)},[O,C]),(0,s.useEffect)(()=>{!Se||!dt||dt.setSubmitGate?.($n||O||Xe)},[Se,dt,$n,O,Xe]),(0,s.useEffect)(()=>{if(!Se||!dt)return;Ea.current=!1;let i=null,S=()=>{i&&clearTimeout(i),i=setTimeout(()=>{i=null,M.current="idle",rt(null)},1500)},G=dt.on("submitting",()=>{En(!0),x.current&&clearTimeout(x.current),M.current="validation-window",x.current=setTimeout(()=>{x.current=null,M.current==="validation-window"&&(M.current="processing")},Fc),rt("processing");let We=rr.current;if(!We.sessionId||!We.nonce)return;let Mt=Si();if(!Mt){We.updateError("Enter a valid email address."),M.current="idle",rt(null);return}new vr.PaymentAPI(We.baseUrl).patchAccountSnapshot(We.sessionId,We.nonce,Mt,{telemetryMode:"best_effort"}).catch(ft=>{if(!Dc(ft))return;let St=ft instanceof Error?ft.message:"Please check your billing address and try again.";We.updateError(St),M.current="idle",rt(null),We.onError?.(ft instanceof p.FloPayError?ft:new p.FloPayError(St,"api_error"))})}),Be=dt.on("complete",async We=>{if(oo(We.sessionId??rr.current.sessionId),M.current="terminal",rt("success"),await new Promise(St=>setTimeout(St,1200)),Ea.current)return;Ea.current=!0;let Mt=rr.current,ft=(0,p.isAuthorizationOnlySession)(Mt)||We.outcome==="authorized";rr.current.onComplete?.(ft?{status:"authorized",paymentIntentId:We.intentId,paymentId:We.paymentId??Mt.paymentId,sessionId:We.sessionId??Mt.sessionId,authorizationExpiresAt:We.authorizationExpiresAt??Mt.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",paymentIntentId:We.intentId,checkoutMethod:"card"})}),Z=dt.on("decline",We=>{let Mt=rr.current,ft=We.message??"Your payment was declined. Please try another card or contact your bank.";M.current="terminal",Mt.updateError(ft),rt("error");let St=We.failureOutcome??(0,p.normalizeCheckoutFailureOutcome)(We.declineReason)??"authorization_declined";Mt.emitDecline("card",ft,{code:St,declineCode:St}),S()}),Pe=dt.on("error",We=>{let Mt=rr.current,ft=We.message??"There was a problem processing your payment. Please try again.";M.current="terminal",Mt.updateError(ft),rt("error"),Mt.onError?.(new p.FloPayError(ft,"api_error",{code:We.failureOutcome??"capture_failed"})),S()}),Ht=dt.on("blocked",()=>{if(!wi.current){En(!0);return}Ra(),rr.current.updateError(Ls)});return()=>{i&&(clearTimeout(i),i=null),x.current&&(clearTimeout(x.current),x.current=null),M.current="idle",rt(null),G(),Be(),Z(),Pe(),Ht()}},[Se,dt,Ra,Si]);let or=!!ve?.clientId,co=Array.isArray(I),Uo=co&&I.length>0,ml=co&&I.includes("paypal"),{expressMethods:qo,paymentElementMethods:uo}=(0,s.useMemo)(()=>(0,p.partitionStripeMethods)(I,{excludePaypal:or}),[I,or]),ki=or||!!ze,yl=(0,s.useMemo)(()=>ki?qo.filter(i=>i!=="paypal"):qo,[qo,ki]),fl=(0,s.useMemo)(()=>{let i=[];return q&&i.push("apple_pay"),ue&&i.push("google_pay"),i},[q,ue]),qr=co?yl:fl,gl=W&&qr.length>0,_a=Et?qt:k,$o=(0,s.useMemo)(()=>{let i=_a?.trim().toUpperCase();return i?ie?uo.filter(S=>{let G=ie[S];return!G||G.length===0||G.includes(i)}):(0,p.filterStripeMethodsByCountry)(uo,_a):uo},[uo,_a,ie]),Ta=(0,s.useMemo)(()=>({mode:"payment",amount:yn,currency:Or,paymentMethodCreation:"manual",appearance:bi}),[yn,Or,bi]),[Ii,Ri]=(0,s.useState)("loading"),[Ei,_i]=(0,s.useState)("loading"),[Ti,xi]=(0,s.useState)("loading"),[hl,xa]=(0,s.useState)(!1),[Mi,Ma]=(0,s.useState)("loading"),[Vo,bl]=(0,s.useState)();(0,s.useEffect)(()=>{bl(ks())},[]);let Ai=ye&&(or||(co?ml:Vo===!1)),Bi=W&&gl,po=!Le&&Ai&&or,Fi=Mi==="retrying"||Mi==="exhausted",mo=!Le&&Ai&&!!Pt&&(!or||Fi),$r=!Le&&Bi&&!!be,yo=!Le&&W&&Uo&&$o.length>0&&!!be,vl=po&&!Fi?hl:mo&&$s(Ii),Cl=$r&&$s(Ei),Pl=yo&&Ti!=="load_error",Di=i=>i==="loading"||i==="ready",Ni=po||mo&&Di(Ii)||$r&&Di(Ei)||yo&&Ti!=="load_error",jo=(0,s.useRef)(!1);(0,s.useEffect)(()=>{if(!jo.current){if(!W&&!ye){jo.current=!0;let i=new p.FloPayError("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");l?.(i),ge(i.message)}else if(!W&&ye&&!or&&!Pt){jo.current=!0;let i=new p.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(Vo!==void 0&&!Le&&!j&&!Ni){jo.current=!0;let i=new p.FloPayError("FloPay: this checkout session has no vault card capability and no usable supported non-card payment methods. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});l?.(i),ge(i.message)}}},[W,ye,or,Pt,Vo,Le,j,Ni,l,ge]);let Li=(0,s.useRef)(!1);(0,s.useEffect)(()=>{if(Li.current||!Uo)return;let i=[];q!==!0&&i.push("showApplePay"),ue!==!0&&i.push("showGooglePay"),i.length!==0&&(Li.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,ue]);let Oi=(0,s.useCallback)((i,S)=>pe.applyInlineSessionPatch?pe.applyInlineSessionPatch(i).then(G=>({error:null,sessionId:G.sessionId||e,nonce:G.session?.clientSecret||t})).catch(G=>{let Be=qs(S,G);return ge(Be.message),l?.(Be),{error:Be,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[pe.applyInlineSessionPatch,t,l,e,ge]),Xn=(0,s.useCallback)(async i=>{if(!z)return{proceed:!0};try{let S=await z({method:i,sessionId:e||void 0,createSession:pe.inlineSessionDraft});if(S===!1)return{proceed:!1};if(S&&typeof S=="object"){S.account&&dn(Be=>({...Be??{},...S.account}));let G=await Oi(S,i);return G.error?{proceed:!1,accountPatch:S.account}:{proceed:!0,accountPatch:S.account,sessionId:G.sessionId,nonce:G.nonce}}return{proceed:!0}}catch(S){let G=qs(i,S);return ge(G.message),l?.(G),{proceed:!1}}},[Oi,pe.inlineSessionDraft,z,l,e,ge]),zi=(0,s.useCallback)(async(i,S)=>{if(Cn.current)return;Cn.current=!0,X(!0),rt("processing"),ge(null);let G=S?.sessionId??e,Be=S?.nonce??t,Z=$a(F,S?.accountPatch),Pe=S?.completionPaymentMethodId??wo(i),Ht=i.originalPaymentMethodId?{...i,originalPaymentMethodId:void 0}:i,We=Uc(i),Mt=()=>{lt?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"process_payment",provider:We})};try{let St=await new vr.PaymentAPI(Ce).processPayment(Z.userId??"",{sessionId:G,nonce:Be,paymentMethodCategory:S?.paymentMethodCategory??$c(i),tokenizedData:Ht,accountData:{...S?.accountPatch,userId:Z.userId??"",email:Z.email??"",firstName:Z.firstName||void 0,lastName:Z.lastName||void 0,..._?(()=>{let ut=jt.current,Nn=(0,p.isAVSFieldVisible)(_.state,ut),fn=(0,p.isAVSFieldVisible)(_.address_line_1,ut),At=(0,p.isAVSFieldVisible)(_.postal_code,ut),xr=fn&&!Nn&&At?(0,p.getStateFromPostalCode)(ut,(at.current??"").trim()):null,Co=Nn?Kt.current:xr;return{country:ut,...At&&at.current?{zip:at.current}:{},...(0,p.isAVSFieldVisible)(_.city,ut)&&In.current?{city:In.current}:{},...Co?{state:Co}:{},...fn&&Jt.current?{addressLine1:Jt.current}:{},...(0,p.isAVSFieldVisible)(_.address_line_2,ut)&&on.current?{addressLine2:on.current}:{}}})():{}},chv:v,avsCheck:Ye??!1,checkoutType:ee,checkoutLayout:J,avsConfig:_?{country:(0,p.isAVSFieldVisible)(_.country,jt.current),postal_code:(0,p.isAVSFieldVisible)(_.postal_code,jt.current),address_line_1:(0,p.isAVSFieldVisible)(_.address_line_1,jt.current),address_line_2:(0,p.isAVSFieldVisible)(_.address_line_2,jt.current),city:(0,p.isAVSFieldVisible)(_.city,jt.current),state:(0,p.isAVSFieldVisible)(_.state,jt.current)}:void 0});if(St.ok){let ut=St.status===204?null:await St.json().catch(()=>null),Nn=(0,p.isAuthorizationOnlySession)(te)||ut?.status==="authorized";oo(G),rt("success"),se(null),await new Promise(xr=>setTimeout(xr,1200));let fn;typeof ut?.paymentId=="string"?fn=ut.paymentId:te?.paymentId&&(fn=te.paymentId);let At;typeof ut?.authorizationExpiresAt=="string"?At=ut.authorizationExpiresAt:te?.authorizationExpiresAt&&(At=te.authorizationExpiresAt),a?.(Nn?{status:"authorized",...fn===void 0?{}:{paymentId:fn},sessionId:typeof ut?.sessionId=="string"?ut.sessionId:G,...At===void 0?{}:{authorizationExpiresAt:At},paymentIntentId:i.threeDSecureActionResultTokenId,paymentMethodId:Pe,checkoutMethod:i.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:i.threeDSecureActionResultTokenId,paymentMethodId:Pe,checkoutMethod:i.isPaypal?"paypal":"card"});return}let wt=await St.json().catch(()=>null);if(wt?.type==="paypal_redirect_required"){let ut=wt.threeDSecureToken,Nn=wt.paymentMethodId||i.id||"";if(!Q||!ut){rt("error"),ge("PayPal authorization required but no token provided.");return}try{let fn=ze?.getRawProvider();if(!fn){ge("PayPal is not available.");return}let At={return_url:window.location.href};Nn&&(At.payment_method=Nn);let{error:xr}=await fn.confirmPayment({clientSecret:ut,confirmParams:At,redirect:"if_required"});if(xr){rt("error");let Co=xr.message??"PayPal payment failed.";ge(Co),Jn("paypal",Co,{code:xr.code})}}catch(fn){rt("error"),ge(fn instanceof Error?fn.message:"PayPal authorization failed.")}return}if(wt?.type==="paypal_direct_required"){let ut=wt.orderId;if(!ut){rt("error"),ge("PayPal retry required but no order id provided.");return}let Nn=Me.current?.attempts??0;if(Nn>=2){rt("error"),ge("PayPal payment could not be completed after multiple attempts."),Jn("paypal","paypal_direct_required retry limit exceeded");return}xa(!1),Ma("loading"),se({orderId:ut,attempts:Nn+1}),rt(null);return}(0,p.classifyPaymentRejection)(St.status,wt)||Mt(),rt("error");let yr=wt?.message??"Payment failed. Please try again.";ge(yr),Jn(i.isPaypal?"paypal":"card",yr,{code:wt?.code??wt?.gatewayErrorCode,declineCode:wt?.declineCode??wt?.gatewayDeclineReason}),await new Promise(ut=>setTimeout(ut,1500))}catch(ft){Ws(ft)||Mt(),rt("error"),ge(ft instanceof Error?ft.message:"An unexpected error occurred"),await new Promise(St=>setTimeout(St,1500))}finally{X(!1),rt(null),Cn.current=!1}},[Ce,e,t,F,_,Ye,ee,J,v,Q,ze,te,a,ge,Jn,lt]),Pn=(0,s.useCallback)((i,S)=>{g?g(i):zi(i,S)},[g,zi]),fo=`${Hs}:${e}`;(0,s.useEffect)(()=>{if(typeof window>"u")return;let i=localStorage.getItem(fo);if(!i)return;let S;try{S=JSON.parse(i)}catch{localStorage.removeItem(fo);return}if(!S||typeof S.createdAt!="number"||Date.now()-S.createdAt<0||Date.now()-S.createdAt>Tc||typeof S.paymentMethodId!="string"||typeof S.providerIntentId!="string"||typeof S.paymentMethodType!="string"||S.sessionId!==e||!t||S.nonce!==t||!qr.includes(S.paymentMethodType)){localStorage.removeItem(fo);return}localStorage.removeItem(fo),Pn({id:S.paymentMethodId,type:"card",threeDSecureActionResultTokenId:S.providerIntentId,gateway:"stripe",paymentMethodType:S.paymentMethodType},{...S.accountPatch?{accountPatch:S.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t})},[Pn,t,e,fo,qr]);let Ui=(0,s.useRef)(!1);(0,s.useEffect)(()=>{if(typeof window>"u"||Ui.current)return;let i=new URLSearchParams(window.location.search),S=i.get("payment_intent"),G=i.get("payment_intent_client_secret"),Be=i.get("redirect_status");if(!S||!G)return;let Z=St=>{let wt=localStorage.getItem(St);if(!wt)return null;try{return JSON.parse(wt)}catch{return localStorage.removeItem(St),null}},Pe=Z(ir)??Z(Ns),Ht;if(Pe?.clientSecret){if(Pe.clientSecret!==G)return;Ht={...Pe.accountPatch?{accountPatch:Pe.accountPatch}:{},...Pe.sessionId?{sessionId:Pe.sessionId}:{},...Pe.nonce?{nonce:Pe.nonce}:{}}}else if(Pe?.sessionId&&Pe.sessionId!==e)return;Ui.current=!0,localStorage.removeItem(ir),localStorage.removeItem(Ns);let We=new URL(window.location.href);We.searchParams.delete("payment_intent"),We.searchParams.delete("payment_intent_client_secret"),We.searchParams.delete("redirect_status"),window.history.replaceState({},"",We.toString());let Mt=Pe?.paymentMethodType??Pe?.tokenType??"card",ft="card";(async()=>{let St=Q?.getRawProvider();if(!St){let At="Payment is not available \u2014 please refresh and try again.";ge(At),Jn(ft,At);return}if(Be==="failed"){let At="Payment was declined. Please try again.";ge(At),Jn(ft,At);return}let{paymentIntent:wt,error:yr}=await St.retrievePaymentIntent(G);if(yr){let At=yr.message??"Failed to retrieve payment status.";ge(At),Jn(ft,At,{code:yr.code});return}let ut=wt?.status,Nn=So(ut);if(!wt||!Nn){let At=ut==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";ge(At),Jn(ft,At,{code:ut??"missing_payment_intent"});return}let fn=typeof wt.payment_method=="string"?wt.payment_method:wt.payment_method?.id;Pn({id:fn??Pe?.paymentMethodId??Pe?.tokenId??wt.id,type:"card",threeDSecureActionResultTokenId:wt.id,gateway:Pe?.gateway??"stripe",paymentMethodType:Mt},Ht)})()},[e,Pn,Q,ge,Jn]);let Aa=(0,s.useCallback)(i=>{i.preventDefault()},[]);if(!(Q!==null))return(0,d.jsx)("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let go=re==="buttons",Sn=E?.variables,Sl=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),Ba=Sn?.colorBackground,wl=Ba&&!Sl.has(Ba)?Ba:void 0,ho=f.cardInputBorder??(go?"#e5e7eb":"#A4A4FF"),qi=Sn?.colorDanger??"#dc2626",xt=i=>Vn[i]&&(pn[i]||dr),Ko=Xe&&(Kn||dr),Dn=i=>i?qi:ho,Ho=(yt.malformed||yt.empty)&&(jn||dr),kl=Dn(Ho),Fa=f.cardFormContainer?.backgroundColor??wl??(go?"white":"#EDEDFF"),Vr=f.cardInputBackground??Sn?.colorBackground??"white",Da=Hr(Te),$i=Hr(xe),jr=f.nameInput,Vi=f.cardInputFontSize??Gc(jr?.fontSize)??Sn?.fontSizeBase??"16px",ji=typeof jr?.fontFamily=="string"?jr.fontFamily:Sn?.fontFamily??"Poppins, sans-serif",Ki=ti(jr?.fontWeight)??400,Il=f.cardInputColor??(typeof jr?.color=="string"?jr.color:void 0)??Sn?.colorText??"#262833",Rl=f.cardInputPlaceholderColor??"#9ca3af",Lt=Sn?.borderRadius??"8px",_r=Sn?.borderRadius??f.cardButton?.borderRadius??Lt,Tr=Sn?.colorPrimary??"#4A49FF",El=Sn?.colorPrimaryHover??lo(Tr,.12),Na=Sn?.colorText??"#262833",La={fontSize:Vi,fontFamily:ji,fontWeight:Ki,color:Il,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},bo={marginTop:"0.375rem",...La,fontSize:"0.75rem",lineHeight:1.4,color:qi},_l={"--flopay-input-placeholder-color":Rl,"--flopay-input-font-size":Vi,"--flopay-input-font-family":ji,"--flopay-input-font-weight":String(Ki)},vo=f.cardFormContainer??{},Oa=vo.padding??(go?"0":"1rem"),za=vo.borderRadius??Lt,Tl=dt&&sn?(0,d.jsx)(so,{capture:dt,html:sn.html,messageToken:sn.messageToken,expectedOrigin:sn.expectedOrigin,theme:Ae,onReady:()=>{if(!fe&&!_||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){_n.current=!0;try{G.focus()}finally{_n.current=!1}}};_t.current||i()},onError:i=>ge(i),onValidation:i=>{let S=M.current;(S==="idle"||S==="validation-window")&&(ge(i),i&&M.current==="validation-window"&&(x.current&&(clearTimeout(x.current),x.current=null),M.current="idle",rt(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"}),Hi=(0,d.jsxs)("div",{onFocusCapture:i=>{["INPUT","SELECT","TEXTAREA","IFRAME"].includes(i.target.tagName)&&Hn()},style:{backgroundColor:Fa,borderRadius:za,...vo,padding:Oa,..._l,display:"flex",flexDirection:"column"},children:[(0,d.jsx)("style",{children:`
30
+ `,Sa=44,qo=280,Us=`flopay-card-enter ${qo}ms cubic-bezier(0, 0, 0.2, 1) both`,qs=`flopay-card-exit ${qo}ms cubic-bezier(0.4, 0, 0.2, 1) both`,Kc=`flopay-buttons-enter ${qo}ms cubic-bezier(0, 0, 0.2, 1) both`,Hc=`flopay-buttons-exit ${qo}ms cubic-bezier(0.4, 0, 0.2, 1) both`;function Wc(e){return e.gateway==="stripe"?"stripe":e.gateway==="paypal"||e.isPaypal?"paypal":void 0}function hi(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 Gc={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"};function Yc(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 Xs={width:"100%",minHeight:Sa,margin:"0 0 0.5rem",padding:"0.75rem 0.875rem",border:"1px solid #2563eb",borderRadius:8,background:"#eff6ff",color:"#1d4ed8",fontSize:"0.95rem",fontWeight:700,cursor:"pointer"};function Jc(e){switch(e){case"paypal":return"PayPal";case"apple_pay":return"Apple Pay";case"google_pay":return"Google Pay";default:return"Card"}}function $s(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function yi(e){return e==="paypal"?"PayPal":(0,u.getStripeMethodDisplayName)(e)}function Xc(e,t){let n=`We couldn't open ${yi(e)}. Try again or choose another payment method.`;return t?`${n} Allow pop-ups for this site, then try again.`:n}function Zc(e){let t=(0,u.getPostalCodeExample)(e);return`Enter a valid ${(0,u.getPostalCodeLabel)(e)}${t?` (e.g. ${t})`:""}`}function Qc(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 ed(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 js(e,t){return t instanceof u.FloPayError?t:new u.FloPayError(t instanceof Error?t.message:`${Jc(e)} before-click hook failed.`,"validation_error")}function mi(){return(0,d.jsx)("style",{children:Vc})}function td(e){return typeof e=="number"?`${e}px`:e}function Zs(e,t){let n=e.availablePaymentMethods;return n&&t.some(r=>n[r])?"ready":"unavailable"}function Qs({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 Vs(e){return e!=="unavailable"&&e!=="load_error"}function Ia(e){return(0,d.jsx)(rd,{...e})}function Ks({sessionId:e,nonce:t,email:n,billingApiUrl:r,onTokenizedBody:o,onErrorChange:a,isProcessing:l=!1,onButtonClick:c,onDecline:f,onTechnicalFailure:y,runBeforeButtonClick:p,billingName:b,onBuyerIdentityReady:h,onLoadStateChange:w,placeholderBorderRadius:B}){let N=wr(),{emitInstrument:de}=(0,s.useContext)(Yn),K=(0,Ht.useStripe)(),I=(0,Ht.useElements)(),[re,q]=(0,s.useState)("loading");(0,s.useEffect)(()=>{w?.(re)},[re,w]);let[ie,se]=(0,s.useState)(!1),ee=!(0,u.isValidEmail)(n?.trim())||!b?.trim(),{request:Oe,collect:ue,finish:Ct}=no(),st=(0,s.useRef)(!1),Se=(0,s.useRef)(null),Re=(0,s.useRef)(null),[he,te]=(0,s.useState)(0),[Te,fe]=(0,s.useState)(!1),we=(0,s.useRef)(!1),xe=(0,s.useRef)(new Map),{startAttempt:Le,finishAttempt:_e,invalidateAttempt:_,isAttemptInvalidated:oe,isAttemptCurrent:me}=Ao((Z,X,$)=>{y?.(Z,X,{...$,popupBlocked:$?.popupBlocked??Sr(X)}),fe(!0),te(ze=>ze+1)});(0,s.useEffect)(()=>{Te&&Re.current?.focus()},[Te,he]);let J=(0,s.useCallback)(()=>{te(Z=>Z+1)},[]),O=(0,s.useCallback)((Z,X,$)=>{_($),y?.("paypal",Z,{code:X,popupBlocked:Sr(Z)}),fe(!0),J()},[_,y,J]),Ce=(0,s.useCallback)(()=>{window.setTimeout(()=>{(Se.current?.querySelector("iframe")??Se.current)?.focus()},0)},[]);(0,s.useEffect)(()=>{we.current&&(we.current=!1,Ce())},[Ce,he]);let Ke=(0,s.useCallback)(()=>{fe(!1),a?.(null),Ce()},[Ce,a]);(0,s.useEffect)(()=>{if(!K||st.current)return;let Z=new URLSearchParams(window.location.search),X=Z.get("payment_intent"),$=Z.get("payment_intent_client_secret"),ze=Z.get("redirect_status");if(!X||!$)return;st.current=!0;let Je;try{let Xe=localStorage.getItem(Uo);if(Xe){let H=JSON.parse(Xe);H.clientSecret===$&&(Je={...H.accountPatch?{accountPatch:H.accountPatch}:{},...H.sessionId?{sessionId:H.sessionId}:{},...H.nonce?{nonce:H.nonce}:{}})}}catch{}try{localStorage.removeItem(Uo)}catch{}let be=new URL(window.location.href);be.searchParams.delete("payment_intent"),be.searchParams.delete("payment_intent_client_secret"),be.searchParams.delete("redirect_status"),window.history.replaceState({},"",be.toString()),(async()=>{try{if(se(!0),ze==="failed"){let z="PayPal payment was declined. Please try again.";a?.(z),f?.(cn("paypal",z));return}let{paymentIntent:Xe,error:H}=await K.retrievePaymentIntent($);if(H){a?.(H.message??"Failed to retrieve PayPal payment status.");return}if(Xe&&(Xe.status==="requires_capture"||Xe.status==="succeeded")){let z=typeof Xe.payment_method=="string"?Xe.payment_method:Xe.payment_method?.id;o({id:z??Xe.id,type:"card",threeDSecureActionResultTokenId:Xe.id,isPaypal:!0},Je)}else{let z="PayPal payment was not completed. Please try again.";a?.(z),f?.(cn("paypal",z))}}catch(Xe){a?.(Xe instanceof Error?Xe.message:"Failed to complete PayPal payment.")}finally{se(!1)}})()},[K,o,a,f]);let _t=(0,s.useCallback)(async Z=>{if(l||ie){Z.reject();return}let X=p?await p("paypal"):{proceed:!0};if(!X.proceed){xe.current.delete(he),Z.reject();return}let $=Le("paypal");xe.current.set(he,{generation:$,accountPatch:X.accountPatch,sessionId:X.sessionId,nonce:X.nonce}),fe(!1),c?.("paypal"),Z.resolve()},[l,c,p,Le,ie,he]),Qe=(0,s.useCallback)(async Z=>{if(!K||!I)return;let X=xe.current.get(he);if(X&&!me(X.generation)){xe.current.delete(he);return}if(!X&&oe()||X&&!_e(X.generation))return;X||_e();let $=X??null;if(xe.current.delete(he),!$&&p){let z=await p("paypal");if(!z.proceed){Z.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}$={accountPatch:z.accountPatch,sessionId:z.sessionId,nonce:z.nonce}}let ze=$?.sessionId??e,Je=$?.nonce??t,be=await jc({event:Z,prepared:$,email:n,billingName:b,methodLabel:"PayPal",collect:ue});if(!be){Z.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let Xe=be.email,H={...$?.accountPatch,...Dn(be,!0)};try{if(se(!0),a?.(null),!ze||!(0,u.isValidEmail)(Xe))throw new Error("Missing sessionId or email for PayPal payment");await h?.(be);let z=K.createPaymentMethod,{error:rt,paymentMethod:D}=await z({type:"paypal"});if(rt){O(rt,"stripe_paypal_create_payment_method_failed",X?.generation),Z.paymentFailed({reason:"fail"});return}let j=await wa(r,de,ze,Je??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:D?.id??null,intentKind:"payment"});if(j.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let qe=j.clientSecret,ve={return_url:window.location.href};if(D?.id&&(ve.payment_method=D.id),typeof window<"u")try{localStorage.setItem(Uo,JSON.stringify({clientSecret:qe,sessionId:ze,nonce:Je,accountPatch:H}))}catch{}let{error:Bt,paymentIntent:St}=await K.confirmPayment({clientSecret:qe,confirmParams:ve,redirect:"if_required"});if(Bt){if(typeof window<"u")try{localStorage.removeItem(Uo)}catch{}if(To(Bt)){let F=Bt.message??"Your payment was declined.";a?.(F),f?.(cn("paypal",F,{code:Cr(Bt),declineCode:oo(Bt)})),await ka({billingApiUrl:r,sessionId:ze,nonce:Je,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:Cr(Bt)??"provider_declined"}})}else O(Bt,"stripe_paypal_confirm_failed",X?.generation);return}if(typeof window<"u")try{localStorage.removeItem(Uo)}catch{}let P=typeof St?.payment_method=="string"?St.payment_method:St?.payment_method?.id;o({id:P??St?.id,type:"card",threeDSecureActionResultTokenId:St?.id,isPaypal:!0},{accountPatch:H,paymentMethodCategory:"paypal",sessionId:ze,nonce:Je});return}catch(z){O(z,"stripe_paypal_failed",X?.generation)}finally{se(!1)}},[K,I,e,t,n,b,ue,h,r,de,o,a,f,p,O,_e,me,oe,he]);return(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)(Qs,{state:re,placeholderTestId:"flopay-paypal-placeholder",borderRadius:B,children:(0,d.jsxs)("div",{ref:Se,tabIndex:-1,"data-testid":"flopay-paypal-focus-target",role:"group","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[Te&&(0,d.jsx)("button",{ref:Re,type:"button","data-testid":"flopay-paypal-retry-button",onClick:Ke,style:Xs,children:"Try PayPal again"}),Oe&&(0,d.jsx)(ro,{identity:Oe.identity,methodLabel:Oe.methodLabel,onComplete:Ct,onCancel:()=>Ct(null)},Oe.id),(0,d.jsx)("div",{style:{display:Oe?"none":void 0},children:(0,d.jsx)(Ht.ExpressCheckoutElement,{onReady:Z=>q(Zs(Z,["paypal"])),onLoadError:()=>{q("load_error"),gi(sn(N),"paypal","paypal")},onClick:_t,onConfirm:Qe,onCancel:()=>{let Z=xe.current.get(he);xe.current.delete(he),sn(N)?.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),_(Z?.generation),fe(!1),we.current=!0,J()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:ee,emailRequired:ee,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},he)})]})}),ie&&(0,d.jsx)(Xn,{status:"processing"})]})}function Hs({sessionId:e,nonce:t,email:n,billingApiUrl:r,intentKind:o,expressMethods:a,onTokenizedBody:l,onErrorChange:c,onButtonClick:f,onDecline:y,onTechnicalFailure:p,runBeforeButtonClick:b,billingName:h,onBuyerIdentityReady:w,onLoadStateChange:B,placeholderBorderRadius:N}){let de=wr(),{emitInstrument:K}=(0,s.useContext)(Yn),I=(0,Ht.useStripe)(),re=(0,Ht.useElements)(),[q,ie]=(0,s.useState)("loading");(0,s.useEffect)(()=>{B?.(q)},[q,B]);let[se,ee]=(0,s.useState)(!1),Oe=(0,s.useRef)(!(0,u.isValidEmail)(n?.trim())||!h?.trim()).current,{request:ue,collect:Ct,finish:st}=no(),Se=(0,s.useRef)(null),Re=(0,s.useRef)(null),[he,te]=(0,s.useState)(0),[Te,fe]=(0,s.useState)(!1),[we,xe]=(0,s.useState)("google_pay"),Le=(0,s.useRef)(!1),_e=(0,s.useRef)("google_pay"),_=(0,s.useRef)("google_pay"),oe=(0,s.useRef)(null),me=(0,s.useRef)(new Set);(0,s.useEffect)(()=>()=>{for(let z of me.current)window.clearTimeout(z);me.current.clear()},[]);let J=(0,s.useRef)(new Map),{startAttempt:O,finishAttempt:Ce,invalidateAttempt:Ke,isAttemptInvalidated:_t,isAttemptCurrent:Qe,generationRef:Z}=Ao((z,rt,D)=>{p?.(z,rt,{...D,popupBlocked:D?.popupBlocked??Sr(rt)}),xe(z),fe(!0),te(j=>j+1)});(0,s.useEffect)(()=>{Te&&Re.current?.focus()},[Te,he]);let X=(0,s.useCallback)(()=>{te(z=>z+1)},[]),$=(0,s.useCallback)((z,rt,D,j)=>{Ke(j),p?.(z,rt,{code:D,popupBlocked:Sr(rt)}),xe(z),fe(!0),X()},[Ke,p,X]),ze=(0,s.useCallback)(()=>{window.setTimeout(()=>{(Se.current?.querySelector("iframe")??Se.current)?.focus()},0)},[]);(0,s.useEffect)(()=>{Le.current&&(Le.current=!1,ze())},[ze,he]);let Je=(0,s.useCallback)(()=>{fe(!1),c?.(null),ze()},[ze,c]),be=(0,s.useCallback)(async z=>{let rt=!1,D=$e=>{rt||(rt=!0,z.paymentFailed({reason:"fail",...$e?{message:$e}:{}}))};if(!I||!re){D();return}let j=J.current.get(he);if(j&&!Qe(j.generation)){J.current.delete(he),D();return}if(!j&&_t()){D();return}if(j&&!Ce(j.generation)){D();return}j||Ce();let qe=z.expressPaymentType??j?.method??_e.current,ve=j??null,Bt=$s(qe),St;qe==="apple_pay"?St="apple_pay":qe==="google_pay"&&(St="google_pay");let P=j?.generation??Z.current,F=sn(de),qt=F?.now()??globalThis.performance?.now()??Date.now(),Ae=new AbortController,Et=!1,tn=!1,et=null,nn=e,lt="processing",Wt="other",dn="provider_runtime",rn,ke=new Promise(($e,ct)=>{rn=ct}),hn=window.setTimeout(()=>{Et=!0,Ae.abort(),rn(di)},Oc),bn=async($e,ct,un)=>{lt=$e,Wt=ct,dn=ct==="intent_create"||ct==="session_claim"?"transport_error":"provider_runtime";let Gt=F?.now()??globalThis.performance?.now()??Date.now();try{return await Promise.race([un,ke])}finally{let pn=F?.now()??globalThis.performance?.now()??Date.now();F?.performance({stage:$e,durationMs:Math.max(0,pn-Gt),durationMode:"machine",requestCategory:ct,paymentMethodCategory:"wallet",provider:"stripe",...Et?{statusClass:"timeout"}:{}})}};try{if(ee(!0),c?.(null),!ve&&b){let E=await bn("processing","other",b(Bt));if(!E.proceed){D();return}ve={accountPatch:E.accountPatch,sessionId:E.sessionId,nonce:E.nonce}}let $e=ve?.sessionId??e;nn=$e;let ct=ve?.nonce??t,un=oe.current??ve?.accountPatch,Gt=Js({event:z,fallbackEmail:un?.email??n,fallbackName:[un?.firstName,un?.lastName].join(" ").trim()||h});if(!(0,u.isValidEmail)(Gt.email)){D("Buyer details are required."),Ct(yi(qe),Gt).then(E=>{E&&(oe.current=E)});return}oe.current=null;let pn={...ve?.accountPatch,...Dn(Gt,!0)};await bn("processing","session_claim",Promise.resolve(w?.(Gt)));let{error:$t}=await bn("tokenization","provider_sdk",re.submit());if($t){D(),$(qe,$t,"stripe_wallet_submit_failed",j?.generation);return}if(!$e)throw new Error("Missing sessionId or email for payment.");let wt=await bn("processing","intent_create",wa(r,K,$e,ct??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:qe,paymentMethodId:null,intentKind:o},{signal:Ae.signal}));if(wt.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Qn=wt.clientSecret;window.clearTimeout(hn),tn=!0,F?.performance({stage:"callback",durationMs:Math.max(0,(F?.now()??globalThis.performance?.now()??Date.now())-qt),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe"});let kt=F?.now()??globalThis.performance?.now()??Date.now(),vn={stage:"provider_confirmation",provider:"stripe",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",...St?{walletType:St}:{},attempt:P},ht=!1;F?.log({name:"payment.provider_confirmation.started",...vn}),et=window.setTimeout(()=>{et!==null&&me.current.delete(et),ht=!0;let E=F?.now()??globalThis.performance?.now()??Date.now();F?.error({errorCode:"PROVIDER_RUNTIME_FAILED",...vn,operationOutcome:"watchdog_expired",checkoutSessionId:$e,durationMs:Math.max(0,E-kt),statusClass:"timeout",failureCategory:"provider_runtime"}),F?.flush?.().catch(()=>{})},zc),me.current.add(et);let Yt=E=>{et!==null&&(window.clearTimeout(et),me.current.delete(et),et=null);let xt=F?.now()??globalThis.performance?.now()??Date.now(),ot=Math.max(0,xt-kt),Xt=E;return ht&&(E==="resolved"?Xt="resolved_late":E==="returned_error"?Xt="returned_error_late":Xt="rejected_late"),F?.log({name:"payment.provider_confirmation.returned",...vn,operationOutcome:Xt}),F?.performance({...vn,durationMs:ot,durationMode:"buyer",operationOutcome:Xt}),{durationMs:ot,operationOutcome:Xt}},dt=!1,Tt=E=>{if(!E||typeof E!="object")return null;let xt=E;if(xt.error)return null;let ot=xt.setupIntent??xt.paymentIntent,Xt=ot?.id,on=ot?.status,Ln=xt.setupIntent?on==="succeeded":_o(typeof on=="string"?on:void 0),Tn=ot?.payment_method,Zt=null;return typeof Tn=="string"?Zt=Tn:typeof Tn?.id=="string"&&(Zt=Tn.id),!Ln||typeof Xt!="string"||!Zt?null:{intentId:Xt,paymentMethodId:Zt}},Pn=E=>{if(dt||j&&Z.current!==j.generation)return;let xt=Tt(E);if(!xt)return;let{intentId:ot,paymentMethodId:Xt}=xt;dt=!0;let on=`${Gs}:${$e}`;if(typeof window<"u")try{localStorage.setItem(on,JSON.stringify({createdAt:Date.now(),sessionId:$e,nonce:ct,accountPatch:pn,paymentMethodId:Xt,providerIntentId:ot,paymentMethodType:qe}))}catch{}try{l({id:Xt,type:"card",threeDSecureActionResultTokenId:ot},{accountPatch:pn,paymentMethodCategory:"wallet",sessionId:$e,nonce:ct})}finally{if(typeof window<"u")try{localStorage.removeItem(on)}catch{}}},Jt,Cn;try{let E=await((0,u.isSetupIntentClientSecret)(Qn)?I.confirmSetup({elements:re,clientSecret:Qn,redirect:"if_required"}):I.confirmPayment({elements:re,clientSecret:Qn,redirect:"if_required"}));if(!E||typeof E!="object"||(Jt=E,!Jt.error&&!Tt(Jt)))throw ui;Cn=Yt(Jt.error?"returned_error":"resolved")}catch(E){let xt=E===ui,ot=Yt(xt?"returned_error":"rejected");throw F?.error({...xt?{errorCode:"CONFIGURATION_INVALID",failureCategory:"invalid_response"}:Ja(E),...vn,operationOutcome:ot.operationOutcome,checkoutSessionId:$e,durationMs:ot.durationMs,statusClass:"unknown"}),E}let ut=Jt.error;if(ut){if(To(ut)){let E=ut.message??"Your payment was declined.";D(E),c?.(E),y?.(cn(Bt,E,{code:Cr(ut),declineCode:oo(ut)})),ka({billingApiUrl:r,sessionId:$e,nonce:ct,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:qe,providerDeclineReason:Cr(ut)??"provider_declined",...wt.intentKind==="payment"&&wt.providerObjectId.startsWith("pi_")?{providerIntentId:wt.providerObjectId}:{}}})}else F?.error({...Ja(ut),...vn,operationOutcome:Cn.operationOutcome,checkoutSessionId:$e,durationMs:Cn.durationMs,statusClass:"unknown"}),D(),$(qe,ut,"stripe_wallet_confirm_failed",j?.generation);return}if(Pn(Jt),!dt)throw new Error("Invalid provider returned for APM intent")}catch($e){if($e===di){let ct=F?.now()??globalThis.performance?.now()??Date.now();F?.error({errorCode:Uc(Wt),stage:lt,requestCategory:Wt,paymentMethodCategory:"wallet",provider:"stripe",...St?{walletType:St}:{},operationOutcome:"watchdog_expired",checkoutSessionId:nn,durationMs:Math.max(0,ct-qt),statusClass:"timeout",failureCategory:dn,attempt:P}),F?.flush?.().catch(()=>{})}D(),$(qe,$e,$e===di?"stripe_wallet_authorization_timeout":"stripe_wallet_failed",j?.generation)}finally{if(window.clearTimeout(hn),et!==null&&(window.clearTimeout(et),me.current.delete(et)),!tn){let $e=F?.now()??globalThis.performance?.now()??Date.now();F?.performance({stage:"callback",durationMs:Math.max(0,$e-qt),durationMode:"machine",requestCategory:"provider_sdk",paymentMethodCategory:"wallet",provider:"stripe",...Et?{statusClass:"timeout"}:{}})}ee(!1)}},[I,re,e,t,n,h,Ct,w,r,K,o,l,c,y,b,$,Ce,Qe,_t,Z,de,he]),Xe=(0,s.useMemo)(()=>{let z=["applePay","googlePay","paypal","link","amazonPay","klarna"],rt=new Set(["applePay","googlePay"]),D=new Set(a.map(u.stripeExpressMethodToOptionKey)),j={};for(let qe of z)D.has(qe)?j[qe]=rt.has(qe)?"always":"auto":j[qe]="never";return j},[a]),H=(0,s.useMemo)(()=>a.map(u.stripeExpressMethodToOptionKey),[a]);return(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)(Qs,{state:q,placeholderTestId:"flopay-wallet-placeholder",borderRadius:N,children:(0,d.jsxs)("div",{ref:Se,tabIndex:-1,"data-testid":"flopay-wallet-focus-target",role:"group","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[Te&&(0,d.jsxs)("button",{ref:Re,type:"button","data-testid":"flopay-wallet-retry-button",onClick:Je,style:Xs,children:["Try ",yi(we)," again"]}),ue&&(0,d.jsx)(ro,{identity:ue.identity,methodLabel:ue.methodLabel,onComplete:st,onCancel:()=>st(null)},ue.id),(0,d.jsx)("div",{style:{display:ue?"none":void 0},children:(0,d.jsx)(Ht.ExpressCheckoutElement,{onReady:z=>{ie(Zs(z,H))},onLoadError:z=>{ie("load_error"),gi(sn(de),"stripe","wallet")},onClick:async z=>{_e.current=z.expressPaymentType,_.current=$s(z.expressPaymentType);let rt=!0,D=window.setTimeout(()=>{rt=!1,z.reject()},Nc),j=b?await b(_.current):{proceed:!0};if(window.clearTimeout(D),!rt)return;if(!j.proceed){J.current.delete(he),z.reject();return}let qe=O(z.expressPaymentType);J.current.set(he,{generation:qe,method:z.expressPaymentType,accountPatch:j.accountPatch,sessionId:j.sessionId,nonce:j.nonce}),fe(!1),f?.(_.current),z.resolve()},onConfirm:be,onCancel:()=>{let z=J.current.get(he);J.current.delete(he),sn(de)?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet"}),Ke(z?.generation),fe(!1),Le.current=!0,X()},options:{buttonType:{applePay:"plain",googlePay:"plain"},paymentMethods:Xe,emailRequired:Oe,billingAddressRequired:Oe,layout:{maxColumns:1,overflow:"never"}}},he)})]})}),se&&(0,d.jsx)(Xn,{status:"processing"})]})}function el(e,t){return{...e,paymentMethodTypes:[t],...t==="revolut_pay"||t==="sepa_debit"||t==="us_bank_account"?{setupFutureUsage:"off_session"}:null}}function nd({method:e,themeId:t,submitting:n=!1,disabled:r=!1,highlighted:o=!1,hasNextStep:a=!1,onClick:l,backgroundColor:c,borderColor:f,textColor:y,borderRadius:p,fontFamily:b}){let h=(0,u.resolveStripeMethodBrandVariant)(e,t),w=_s[e],[B,N]=(0,s.useState)(!1),de=!!w&&!B,K=h?.backgroundColor??c??"#ffffff",I=h?.borderColor??f??"#d1d5db",re=h?.textColor??y??"#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:Sa,padding:"0 1rem",backgroundColor:K,color:re,border:`1px solid ${I}`,borderRadius:p??8,fontSize:"0.95rem",fontWeight:600,fontFamily:b,cursor:n||r?"not-allowed":"pointer",opacity:r&&!n?.55:1,animation:n?"flopay-pulse 1.5s ease-in-out infinite":void 0,display:"flex",alignItems:"center",justifyContent:"center",gap:8,transition:"transform 0.1s, opacity 140ms ease-out, border-color 140ms ease-out",boxShadow:o?"0 0 0 2px rgba(74, 73, 255, 0.15)":void 0},children:n?(0,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:[de?(0,d.jsx)("img",{src:w,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,!de&&h?.logoSvg?(0,d.jsx)("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:h.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:re,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 fi({method:e,sessionId:t,nonce:n,email:r,billingName:o,onBuyerIdentityReady:a,billingApiUrl:l,onTokenizedBody:c,onErrorChange:f,onDecline:y,onCancel:p,runBeforeButtonClick:b,onButtonClick:h,isProcessing:w,submitButtonColor:B,submitButtonBorderRadius:N,submitButtonStyle:de,errorText:K}){let I=wr(),{emitInstrument:re}=(0,s.useContext)(Yn),q=(0,Ht.useStripe)(),ie=(0,Ht.useElements)(),[se,ee]=(0,s.useState)(!1),Oe=(0,s.useRef)(!1),[ue,Ct]=(0,s.useState)(!1),[st,Se]=(0,s.useState)("loading"),[Re,he]=(0,s.useState)(""),te=!(0,u.isValidEmail)(r?.trim()),Te=!te||(0,u.isValidEmail)(Re.trim()),fe=(0,s.useCallback)(async()=>{if(!q||!ie||w||Oe.current||!ue)return;Oe.current=!0,ee(!0);let we=b?await b("card"):{proceed:!0};if(!we.proceed){Oe.current=!1,ee(!1);return}h?.("card");let xe=we.sessionId??t,Le=we.nonce??n,_e=Nr(o?.trim()),_=Dn({email:we.accountPatch?.email?.trim()||r?.trim()||Re.trim(),firstName:we.accountPatch?.firstName?.trim()||_e.firstName,lastName:we.accountPatch?.lastName?.trim()||_e.lastName}),oe=_.email,me=Dn({...we.accountPatch,..._});try{if(f?.(null),!(0,u.isValidEmail)(oe))throw new Error("A valid email address is required for payment.");await a?.(_);let J=await ie.submit();if(J.error){f?.(J.error.message??"Payment failed.");return}let O=[_.firstName,_.lastName].filter(Boolean).join(" "),Ce=await q.createPaymentMethod({elements:ie,params:{billing_details:{email:oe,...O?{name:O}:{}}}});if(Ce.error||!Ce.paymentMethod){f?.(Ce.error?.message??"Failed to create payment method.");return}let Ke=Ce.paymentMethod;if(!xe||!oe)throw new Error("Missing sessionId or email for payment.");let _t=Ke.type||e,Qe=await wa(l,re,xe,Le??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:_t,paymentMethodId:null,intentKind:"payment"});if(Qe.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Z=Qe.clientSecret;if(typeof window<"u")try{localStorage.setItem(yr,JSON.stringify({clientSecret:Z,sessionId:xe,nonce:Le,accountPatch:me,paymentMethodId:Ke.id,paymentMethodType:Ke.type??e,gateway:"stripe"}))}catch{}let{error:X,paymentIntent:$}=await q.confirmPayment({clientSecret:Z,confirmParams:{return_url:window.location.href,payment_method:Ke.id},redirect:"if_required"});if(X){if(typeof window<"u")try{localStorage.removeItem(yr)}catch{}let be=X.message??"Payment failed.";f?.(be),y?.(cn("card",be,{code:X.code})),await ka({billingApiUrl:l,sessionId:xe,nonce:Le,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:X.code??"provider_declined"}});return}let ze=$?.status;if(!_o(ze)){if(typeof window<"u")try{localStorage.removeItem(yr)}catch{}let be=ze==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";f?.(be),y?.(cn("card",be,{code:ze??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(yr)}catch{}let Je=typeof $?.payment_method=="string"?$.payment_method:$?.payment_method?.id;c({id:Je??Ke.id,type:"card",threeDSecureActionResultTokenId:$?.id,gateway:"stripe",paymentMethodType:Ke.type??e},{accountPatch:me,paymentMethodCategory:"apm",sessionId:xe,nonce:Le})}catch(J){f?.(J instanceof Error?J.message:"Payment failed. Please try again.")}finally{Oe.current=!1,ee(!1)}},[q,ie,w,ue,b,h,t,n,r,o,Re,a,l,re,e,c,f,y]);return(0,d.jsxs)("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[te&&(0,d.jsx)("div",{"data-testid":"flopay-apm-identity-fields",style:{display:"flex",flexDirection:"column",gap:"0.75rem",marginBottom:"0.75rem"},children:te&&(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:Re,onChange:we=>he(we.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]})}),(0,d.jsx)(Ht.PaymentElement,{onReady:()=>Se("ready"),onLoadError:()=>{Se("load_error"),gi(sn(I),"stripe","apm")},onChange:we=>{Ct(!!we.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:()=>{fe()},disabled:!ue||!Te||se||w||st!=="ready",style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:B,color:"white",border:"none",borderRadius:N,fontSize:"1rem",fontWeight:600,cursor:!ue||!Te||se||w||st!=="ready"?"not-allowed":"pointer",opacity:!ue||!Te||se||w||st!=="ready"?.5:1,transition:"opacity 120ms ease-out",...de??{}},children:se?"Processing\u2026":`Pay with ${(0,u.getStripeMethodDisplayName)(e)}`}),K&&(0,d.jsx)(io,{margin:"0.75rem 0 0",children:K})]})}function Ws({sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:a,paymentElementMethods:l,stripeInstance:c,paymentElementBaseOptions:f,onTokenizedBody:y,onErrorChange:p,onButtonClick:b,onDecline:h,runBeforeButtonClick:w,onLoadStateChange:B,isProcessing:N=!1,submitButtonColor:de="#4A49FF",submitButtonBorderRadius:K=8,submitButtonStyle:I,buttonAppearance:re,themeId:q,onExpandApm:ie,expandedApmMethod:se}){let{emitInstrument:ee}=(0,s.useContext)(Yn),[Oe,ue]=(0,s.useState)(null),[Ct,st]=(0,s.useState)(null),Se=(0,s.useRef)(!1),{request:Re,collect:he,finish:te}=no();(0,s.useEffect)(()=>{l.length>0&&c?B?.("ready"):c||B?.("loading")},[l.length,c,B]);let Te=(0,s.useCallback)(async _=>{if(!c||Se.current||N)return;Se.current=!0,st(_);let oe=w?await w("card"):{proceed:!0};if(!oe.proceed){Se.current=!1,st(null);return}b?.("card");let me=oe.sessionId??e,J=oe.nonce??t,O=Nr([oe.accountPatch?.firstName,oe.accountPatch?.lastName].filter(Boolean).join(" ")||r),Ce=Dn({email:oe.accountPatch?.email?.trim()||n?.trim(),firstName:oe.accountPatch?.firstName?.trim()||O.firstName,lastName:oe.accountPatch?.lastName?.trim()||O.lastName});if(!(0,u.isValidEmail)(Ce.email)){st(null);let Qe=await he((0,u.getStripeMethodDisplayName)(_),Ce);if(!Qe){Se.current=!1;return}Ce=Qe,st(_)}let Ke=Ce.email,_t=Dn({...oe.accountPatch,...Ce});try{if(p?.(null),!me||!(0,u.isValidEmail)(Ke))throw new Error("Missing sessionId or email for payment.");await o?.(Ce);let Qe=await wa(a,ee,me,J??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:_,paymentMethodId:null,intentKind:"payment"});if(Qe.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Z=Qe.clientSecret;if(typeof window<"u")try{localStorage.setItem(yr,JSON.stringify({clientSecret:Z,sessionId:me,nonce:J,accountPatch:_t,paymentMethodType:_,gateway:"stripe"}))}catch{}let{error:X,paymentIntent:$}=await c.confirmPayment({clientSecret:Z,confirmParams:{return_url:window.location.href,payment_method_data:{type:_,billing_details:{name:[Ce.firstName,Ce.lastName].filter(Boolean).join(" "),...Ke?{email:Ke}:{}}}},redirect:"if_required"});if(X){if(typeof window<"u")try{localStorage.removeItem(yr)}catch{}let be=X.message??"Payment failed.";p?.(be),h?.(cn("card",be,{code:X.code})),await ka({billingApiUrl:a,sessionId:me,nonce:J,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:_,providerDeclineReason:X.code??"provider_declined"}});return}let ze=$?.status;if(!_o(ze)){if(typeof window<"u")try{localStorage.removeItem(yr)}catch{}let be=ze==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";p?.(be),h?.(cn("card",be,{code:ze??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(yr)}catch{}let Je=typeof $?.payment_method=="string"?$.payment_method:$?.payment_method?.id;y({id:Je??$?.id,type:"card",threeDSecureActionResultTokenId:$?.id,gateway:"stripe",paymentMethodType:_},{accountPatch:_t,paymentMethodCategory:"apm",sessionId:me,nonce:J})}catch(Qe){p?.(Qe instanceof Error?Qe.message:"Payment failed. Please try again.")}finally{Se.current=!1,st(null)}},[c,N,w,b,e,t,n,he,a,ee,r,o,y,p,h]),[fe,we]=(0,s.useState)(null),xe=ie?se??null:fe,Le=(0,s.useCallback)(_=>{Se.current||N||xe&&xe!==_||((0,u.needsStripeMethodExplicitConfirm)(_)?ie?ie(_):we(_):Te(_))},[xe,N,Te,ie]),_e=(0,s.useMemo)(()=>fe?el(f,fe):null,[fe,f]);return(0,d.jsx)("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:Re?(0,d.jsx)(ro,{identity:Re.identity,methodLabel:Re.methodLabel,onComplete:te,onCancel:()=>te(null)},Re.id):l.map(_=>{let oe=se===_,me=Ct===_,J=Ct!==null&&Ct!==_||se!=null&&se!==_;return(0,d.jsxs)(s.default.Fragment,{children:[(0,d.jsx)(nd,{method:_,themeId:q,submitting:me,disabled:J,highlighted:oe,hasNextStep:(0,u.needsStripeMethodExplicitConfirm)(_),onClick:()=>Le(_),backgroundColor:re?.backgroundColor,borderColor:re?.borderColor,textColor:re?.textColor,borderRadius:re?.borderRadius,fontFamily:re?.fontFamily}),!ie&&fe===_&&_e&&c&&(0,d.jsx)(Ht.Elements,{stripe:c,options:_e,children:(0,d.jsx)(fi,{method:_,sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:a,onTokenizedBody:y,onErrorChange:p,onDecline:h,onCancel:()=>we(null),runBeforeButtonClick:w,onButtonClick:b,isProcessing:N,submitButtonColor:de,submitButtonBorderRadius:K,submitButtonStyle:I})},_)]},_)})})}function rd({sessionId:e,nonce:t,billingApiUrl:n,email:r,userId:o,onComplete:a,onError:l,onDecline:c,onTokenizedBody:f,firstName:y,lastName:p,chv:b,className:h,isProcessing:w,error:B,onErrorChange:N,showPayPal:de=!0,showStripe:K=!0,enabledPaymentMethods:I,enabledPaymentMethodCountries:re,showApplePay:q=!0,showGooglePay:ie=!0,layout:se="default",theme:ee,buttonsTheme:Oe,buttonsStyles:ue,appearance:Ct,cardButtonContent:st,cardBackButtonContent:Se,cardTitleContent:Re,showSecurityFooter:he,onButtonClick:te,onBeforeButtonClick:Te,onBuyerIdentityReady:fe,enableAVS:we,cardFieldOrder:xe,cardPreFormSlot:Le,avsLayout:_e="row",country:_,zip:oe,addressLine1:me,addressLine2:J,city:O,state:Ce,onCountryChange:Ke,onZipChange:_t,avsCheck:Qe,checkoutType:Z,checkoutLayout:X,totalAmount:$=0,currency:ze="usd",initialCardOpen:Je=!1,directPaypal:be,isSubscription:Xe=!1,session:H,dataAttachmentPending:z=!1,dataAttachmentRequiresIdentity:rt=!1,debug:D=!1}){let j=wr(),qe=aa(),ve=(0,s.useContext)(rr),{emitInstrument:Bt}=(0,s.useContext)(Yn),St=H??ve.session,P=St?.gateways?.paypal?.providerObjectType??be?.providerObjectType,F=z||ve.claimPending===!0,qt=rt||ve.claimRequiresIdentity===!0,Ae=F&&!qt,Et=ys(),[tn,et]=(0,s.useState)(!1),[nn,lt]=(0,s.useState)(null),[Wt,dn]=(0,s.useState)(_??"US"),[rn,ke]=(0,s.useState)(oe??""),[hn,bn]=(0,s.useState)(me??""),[$e,ct]=(0,s.useState)(J??""),[un,Gt]=(0,s.useState)(O??""),[pn,$t]=(0,s.useState)(Ce??""),[wt,Qn]=(0,s.useState)(""),[kt,vn]=(0,s.useState)({}),ht=(0,s.useRef)(oe??""),Yt=(0,s.useRef)(_??"US"),dt=(0,s.useRef)(me??""),Tt=(0,s.useRef)(J??""),Pn=(0,s.useRef)(O??""),Jt=(0,s.useRef)(Ce??""),Cn=(0,s.useRef)(""),ut=(0,s.useRef)({});(0,s.useEffect)(()=>{let i=(S,V,Fe,Y,Pe)=>{if(ut.current[S])return;let Qt=V?.trim();!Qt||Qt===Fe.current||(Fe.current=Qt,Y(Qt),Pe?.(Qt))};i("country",_,Yt,dn,Ke),i("zip",oe,ht,ke,_t),i("addressLine1",me,dt,bn),i("addressLine2",J,Tt,ct),i("city",O,Pn,Gt),i("state",Ce,Jt,$t)},[_,oe,me,J,O,Ce,Ke,_t]);let E=(0,s.useMemo)(()=>(0,u.resolveAVSConfig)(we),[we]),xt=E!==null,ot=(0,s.useMemo)(()=>(0,u.isAuthorizationOnlySession)(H),[H]),Xt=!!H?.vault?.html,on=!!H?.gateways?.pcivault,Tn=!!(H?.gateways?.stripe?.enabledPaymentMethods??I)?.includes("card"),Zt=Xt||Tn||on,tt=!!(K&&Zt&&j&&e),[Tr,xr]=(0,s.useState)(()=>se!=="buttons"||Je?e??null:null),[Un,Ar]=(0,s.useState)(0),qn=se!=="buttons"||Je||!!e&&Tr===e,pt=(0,s.useMemo)(()=>!j||!tt||!e||!qn?null:j.cardCapture({sessionId:e,captureMethod:H?.captureMethod}),[j,tt,e,qn,H?.captureMethod]),L=(0,s.useMemo)(()=>{let i=Wt,S=E?(0,u.isAVSFieldVisible)(E.postal_code,i):!1;return Qc(i,rn,S)},[E,Wt,rn]),{avsInvalid:mt,invalidAvsFields:pe}=(0,s.useMemo)(()=>{let i={line1:!1,city:!1,state:!1,zip:!1};if(!tt||!E)return{avsInvalid:!1,invalidAvsFields:i};let S=Wt,V=(Pe,Qt)=>(0,u.isAVSFieldVisible)(Pe,S)&&!Qt.trim(),Fe={line1:V(E.address_line_1,hn),city:V(E.city,un),state:V(E.state,pn),zip:L.empty||L.malformed};return{avsInvalid:Fe.line1||Fe.city||Fe.state||Fe.zip,invalidAvsFields:Fe}},[tt,E,Wt,hn,un,pn,L]),[xn,Sn]=(0,s.useState)(!1),[wn,hr]=(0,s.useState)(!1),[at,Mr]=(0,s.useState)(!1),[er,Br]=(0,s.useState)({line1:!1,city:!1,state:!1}),$n=(0,s.useRef)(!1),jn=(0,s.useRef)({email:!1,line1:!1,city:!1,state:!1,zip:!1}),jt=(0,s.useRef)(!1),bt=(0,s.useCallback)(i=>{jn.current[i]=!0,jt.current=!0},[]),Nn=(0,s.useCallback)(i=>!$n.current&&jn.current[i],[]),mn=(0,s.useCallback)(i=>{Nn(i)&&Br(S=>S[i]?S:{...S,[i]:!0})},[Nn]),[On,fn]=(0,s.useState)(()=>pi(H?.vault)),[Ue,ln]=(0,s.useState)(Je&&Zt?"card":"buttons"),[Ft,Vn]=(0,s.useState)(null),sr=Ue==="expanding"||Ue==="card",br=H?.gateways?.stripe?"stripe":void 0,Kn=(0,s.useCallback)(()=>{Bt?.({class:"card_surface",provider:br})},[br,Bt]),An=(0,s.useRef)(null),Mn=(0,s.useCallback)(i=>{An.current&&clearTimeout(An.current),An.current=setTimeout(()=>{An.current=null,i()},qo)},[]);(0,s.useEffect)(()=>()=>{An.current&&clearTimeout(An.current)},[]);let lr=(0,s.useCallback)(()=>{Kn(),xr(e??null),Ar(i=>i+1),ln("expanding"),Mn(()=>ln("card"))},[Mn,Kn,e]),Vr=(0,s.useCallback)(()=>{ln("collapsing"),Mn(()=>ln("buttons"))},[Mn]),Hn=(0,s.useCallback)(i=>{Vn(i),ln("apm-expanding"),Mn(()=>ln("apm-form"))},[Mn]),cr=(0,s.useCallback)(()=>{ln("apm-collapsing"),Mn(()=>{ln("buttons"),Vn(null)})},[Mn]);(0,s.useEffect)(()=>{se==="buttons"&&Je&&Zt&&(xr(e??null),ln("card"))},[se,Je,Zt,e]);let[gn,yt]=(0,s.useState)(null),kn=(0,s.useRef)(!1),A=(0,s.useRef)(null),x=(0,s.useRef)("idle"),[U,ne]=(0,s.useState)(null),He=(0,s.useRef)(U);(0,s.useEffect)(()=>{He.current=U},[U]);let Ie=n||Et,ye=(0,s.useRef)(null),le=(0,s.useMemo)(()=>{if(fe||ve.claimBuyerIdentity||H?.buyerIdentified!==!1||!e||!t)return;let i=`${Ie}|${e}|${t}`;ye.current?.key!==i&&(ye.current={key:i,claim:eo(new Ir.PaymentAPI(Ie,{telemetry:!1}),e,t,{...o?{userId:o}:{},...y?{firstName:y}:{},...p?{lastName:p}:{}})});let S=ye.current.claim;return async V=>{await S(V)}},[fe,ve.claimBuyerIdentity,H?.buyerIdentified,e,t,Ie,o,y,p]),W=fe??ve.claimBuyerIdentity??le,M=B??nn,ge=(0,s.useMemo)(()=>(0,u.resolveTheme)(ee),[ee]),k=(0,s.useMemo)(()=>{let i=ge?.buttonsLayout??(0,u.resolveButtonsLayoutTheme)(Oe);return ue?{...i,...ue,cardButton:{...i.cardButton,...ue.cardButton},cardFormContainer:{...i.cardFormContainer,...ue.cardFormContainer},backButton:{...i.backButton,...ue.backButton},backButtonIcon:{...i.backButtonIcon,...ue.backButtonIcon},submitButton:{...i.submitButton,...ue.submitButton},title:{...i.title,...ue.title}}:i},[ge,Oe,ue]),G=Ct??ge?.appearance,Ze=(0,s.useMemo)(()=>Ca({appearance:G,buttonsStyles:k,layout:se}),[G,k,se]),Vt=ve.inlineSessionPatchProcessing??!1,v=(w??tn)||Vt,m=Ie.replace(/\/+$/,""),g=(0,s.useMemo)(()=>Ya({userId:o,email:r,firstName:y,lastName:p,country:_,zip:oe},kt),[o,r,y,p,_,oe,kt]),ae=[g.firstName,g.lastName].filter(i=>!!i?.trim()).join(" "),Me=!(0,u.isValidEmail)(g.email?.trim()),ce=(0,s.useRef)(null);tt&&ce.current===null&&(ce.current=Me);let At=tt&&(ce.current??Me),In=(0,s.useMemo)(()=>ed(wt,At),[wt,At]),vt=In.empty||In.malformed,Dt=(0,s.useMemo)(()=>j?j.getRawProvider():null,[j]),an=(0,s.useMemo)(()=>qe?qe.getRawProvider():null,[qe]),Ee=$||100,je=ze.toLowerCase(),Be=(0,s.useMemo)(()=>G?(0,Ir.toStripeAppearance)(G):null,[G]),Ne=Be,it=(0,s.useMemo)(()=>{let i=Be??{},S=i.rules??{};return{...i,rules:{...S,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...S[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...S[".AccordionItemContents"]??{}}}}},[Be]),Rn=(0,s.useMemo)(()=>({...ds($,H?.captureMethod),currency:je,...Ne?{appearance:Ne}:null}),[$,je,H?.captureMethod,Ne]),Ge=(0,s.useMemo)(()=>({mode:"payment",amount:Ee,currency:je,captureMethod:"manual",setupFutureUsage:"off_session",...Ne?{appearance:Ne}:null}),[Ee,je,Ne]),Q=(0,s.useCallback)(i=>{lt(i),N?.(i)},[N]),dr=(0,s.useRef)(""),[Ri,yl]=(0,s.useState)(!1),Ma=(0,s.useCallback)(()=>{yl(!0)},[]);(0,s.useEffect)(()=>{if(!tt||!At||!W||!Ri||vt||dr.current)return;let i=Dn({email:(0,u.isValidEmail)(g.email?.trim())?g.email?.trim():Cn.current.trim(),firstName:g.firstName?.trim(),lastName:g.lastName?.trim()});dr.current=JSON.stringify(i),vn(S=>({...S,...i})),Promise.resolve(W(i)).catch(S=>{dr.current="",Q(S instanceof Error?S.message:"Failed to attach buyer details.")})},[tt,At,W,Ri,vt,g.email,g.firstName,g.lastName,Q]),(0,s.useEffect)(()=>{!tt||!pt||pt.setCardFieldOrder?.(xe??null,E==null&&!At)},[tt,pt,xe,E,At]),(0,s.useEffect)(()=>{(Ue==="expanding"||Ue==="collapsing"||Ue==="apm-expanding"||Ue==="apm-collapsing")&&Q(null)},[Ue,Q]);let tr=(0,s.useCallback)((i,S,V)=>{c?.(cn(i,S,V))},[c]),Kr=(0,s.useCallback)((i,S,V)=>{let Fe=V?.popupBlocked??Sr(S),Y=Xc(i,Fe),Pe=zr(V?.code)??Cr(S)??"external_payment_method_failed",Qt=new u.FloPayError(Y,"api_error",{code:"external_payment_method_failed",param:i});yt(null),se==="buttons"&&(ln("buttons"),Vn(null)),Q(Y),l?.(Qt),console.error("[FloPay] External payment method failed:",{method:i,code:Pe,popupBlocked:Fe})},[se,l,Q]);(0,s.useEffect)(()=>{if(!tt||!e){fn(null);return}let i=pi(H?.vault);if(i){fn(i);return}if(!qn){fn(null);return}fn(null);let S=!0;return new Ir.PaymentAPI(m).getVaultCapture(e,t).then(V=>{if(!S)return;let Fe=pi(V);Fe?fn(Fe):Q("Failed to load the secure card form.")}).catch(V=>{S&&Q(V instanceof Error?V.message:"Failed to load the secure card form.")}),()=>{S=!1}},[tt,qn,Un,e,H?.vault,m,t,Q]);let ur=(0,s.useRef)({onComplete:a,onError:l,updateError:Q,emitDecline:tr,resolvedAccount:g,avsConfig:E,avsCheckProp:Qe,sessionId:e,nonce:t,baseUrl:m,captureMethod:H?.captureMethod,paymentId:H?.paymentId,authorizationExpiresAt:H?.authorizationExpiresAt});ur.current={onComplete:a,onError:l,updateError:Q,emitDecline:tr,resolvedAccount:g,avsConfig:E,avsCheckProp:Qe,sessionId:e,nonce:t,baseUrl:m,captureMethod:H?.captureMethod,paymentId:H?.paymentId,authorizationExpiresAt:H?.authorizationExpiresAt};let Ba=(0,s.useRef)(!1),_i=(0,s.useCallback)(()=>{let i=ur.current,S=i.resolvedAccount.email?.trim(),V=(0,u.isValidEmail)(S)?S:Cn.current.trim();if(!(0,u.isValidEmail)(V))return null;let Fe=i.resolvedAccount.firstName?.trim(),Y=i.resolvedAccount.lastName?.trim(),Pe=Yt.current||i.resolvedAccount.country||"US",Qt=i.avsConfig?(0,u.isAVSFieldVisible)(i.avsConfig.state,Pe):!1,Ye=i.avsConfig?(0,u.isAVSFieldVisible)(i.avsConfig.address_line_1,Pe):!1,Nt=i.avsConfig?(0,u.isAVSFieldVisible)(i.avsConfig.postal_code,Pe):!1,Pt=i.avsConfig?(0,u.isAVSFieldVisible)(i.avsConfig.city,Pe):!1,It=i.avsConfig?(0,u.isAVSFieldVisible)(i.avsConfig.address_line_2,Pe):!1,Rt=Ye&&!Qt&&Nt?(0,u.getStateFromPostalCode)(Pe,(ht.current??"").trim()):null,vr=Qt?Jt.current:Rt;return{accountData:{userId:i.resolvedAccount.userId??"",email:V,...Fe?{firstName:Fe}:{},...Y?{lastName:Y}:{},...Nt&&ht.current?{zip:ht.current}:{},...Pt&&Pn.current?{city:Pn.current}:{},...vr?{state:vr}:{},...Ye&&dt.current?{addressLine1:dt.current}:{},...It&&Tt.current?{addressLine2:Tt.current}:{},country:Pe},...i.avsCheckProp===void 0?{}:{avsCheck:i.avsCheckProp},...i.avsConfig?{avsConfig:{country:(0,u.isAVSFieldVisible)(i.avsConfig.country,Pe),postal_code:Nt,address_line_1:Ye,address_line_2:It,city:Pt,state:Qt}}:{}}},[]),Ei=(0,s.useRef)(F);Ei.current=F,(0,s.useEffect)(()=>{F||M!==zs||ur.current.updateError(null)},[F,M]),(0,s.useEffect)(()=>{!tt||!pt||pt.setSubmitGate?.(mt||F||vt)},[tt,pt,mt,F,vt]),(0,s.useEffect)(()=>{if(!tt||!pt)return;Ba.current=!1;let i=null,S=()=>{i&&clearTimeout(i),i=setTimeout(()=>{i=null,x.current="idle",yt(null)},1500)},V=pt.on("submitting",()=>{Sn(!0),A.current&&clearTimeout(A.current),x.current="validation-window",A.current=setTimeout(()=>{A.current=null,x.current==="validation-window"&&(x.current="processing")},qc),yt("processing");let Ye=ur.current;if(!Ye.sessionId||!Ye.nonce)return;let Nt=_i();if(!Nt){Ye.updateError("Enter a valid email address."),x.current="idle",yt(null);return}new Ir.PaymentAPI(Ye.baseUrl).patchAccountSnapshot(Ye.sessionId,Ye.nonce,Nt,{telemetryMode:"best_effort"}).catch(Pt=>{if(!$c(Pt))return;let It=Pt instanceof Error?Pt.message:"Please check your billing address and try again.";Ye.updateError(It),x.current="idle",yt(null),Ye.onError?.(Pt instanceof u.FloPayError?Pt:new u.FloPayError(It,"api_error"))})}),Fe=pt.on("complete",async Ye=>{if(co(Ye.sessionId??ur.current.sessionId),x.current="terminal",yt("success"),await new Promise(It=>setTimeout(It,1200)),Ba.current)return;Ba.current=!0;let Nt=ur.current,Pt=(0,u.isAuthorizationOnlySession)(Nt)||Ye.outcome==="authorized";ur.current.onComplete?.(Pt?{status:"authorized",paymentIntentId:Ye.intentId,paymentId:Ye.paymentId??Nt.paymentId,sessionId:Ye.sessionId??Nt.sessionId,authorizationExpiresAt:Ye.authorizationExpiresAt??Nt.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",paymentIntentId:Ye.intentId,checkoutMethod:"card"})}),Y=pt.on("decline",Ye=>{let Nt=ur.current,Pt=Ye.message??"Your payment was declined. Please try another card or contact your bank.";x.current="terminal",Nt.updateError(Pt),yt("error");let It=Ye.failureOutcome??(0,u.normalizeCheckoutFailureOutcome)(Ye.declineReason)??"authorization_declined";Nt.emitDecline("card",Pt,{code:It,declineCode:It}),S()}),Pe=pt.on("error",Ye=>{let Nt=ur.current,Pt=Ye.message??"There was a problem processing your payment. Please try again.";x.current="terminal",Nt.updateError(Pt),yt("error"),Nt.onError?.(new u.FloPayError(Pt,"api_error",{code:Ye.failureOutcome??"capture_failed"})),S()}),Qt=pt.on("blocked",()=>{if(!Ei.current){Sn(!0);return}Ma(),ur.current.updateError(zs)});return()=>{i&&(clearTimeout(i),i=null),A.current&&(clearTimeout(A.current),A.current=null),x.current="idle",yt(null),V(),Fe(),Y(),Pe(),Qt()}},[tt,pt,Ma,_i]);let pr=!!be?.clientId,fo=Array.isArray(I),Ko=fo&&I.length>0,fl=fo&&I.includes("paypal"),{expressMethods:Ho,paymentElementMethods:go}=(0,s.useMemo)(()=>(0,u.partitionStripeMethods)(I,{excludePaypal:pr}),[I,pr]),Ti=pr||!!qe,gl=(0,s.useMemo)(()=>Ti?Ho.filter(i=>i!=="paypal"):Ho,[Ho,Ti]),hl=(0,s.useMemo)(()=>{let i=[];return q&&i.push("apple_pay"),ie&&i.push("google_pay"),i},[q,ie]),Hr=fo?gl:hl,bl=K&&Hr.length>0,Fa=xt?Wt:_,Wo=(0,s.useMemo)(()=>{let i=Fa?.trim().toUpperCase();return i?re?go.filter(S=>{let V=re[S];return!V||V.length===0||V.includes(i)}):(0,u.filterStripeMethodsByCountry)(go,Fa):go},[go,Fa,re]),Da=(0,s.useMemo)(()=>({mode:"payment",amount:Ee,currency:je,paymentMethodCreation:"manual",appearance:it}),[Ee,je,it]),[xi,Ai]=(0,s.useState)("loading"),[Mi,Bi]=(0,s.useState)("loading"),[Fi,Di]=(0,s.useState)("loading"),[vl,La]=(0,s.useState)(!1),[Li,Na]=(0,s.useState)("loading"),[Oa,Pl]=(0,s.useState)();(0,s.useEffect)(()=>{Pl(ia())},[]);let Go=Oa?.inAppBrowser,Yo=Oa?sa(Oa,be?.approvalPresentation,P??(Xe?"subscription":"order")):"popup",Ni=de&&(pr||(fo?fl:Go===!1)),Oi=K&&bl,ho=!Ae&&Ni&&pr,zi=Li==="retrying"||Li==="exhausted",bo=!Ae&&Ni&&!!an&&(!pr||zi),Wr=!Ae&&Oi&&!!Dt,vo=!Ae&&K&&Ko&&Wo.length>0&&!!Dt,Cl=ho&&!zi?vl:bo&&Vs(xi),Sl=Wr&&Vs(Mi),wl=vo&&Fi!=="load_error",Ui=i=>i==="loading"||i==="ready",qi=ho||bo&&Ui(xi)||Wr&&Ui(Mi)||vo&&Fi!=="load_error",Jo=(0,s.useRef)(!1);(0,s.useEffect)(()=>{if(!Jo.current){if(!K&&!de){Jo.current=!0;let i=new u.FloPayError("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");l?.(i),Q(i.message)}else if(!K&&de&&!pr&&!an){Jo.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),Q(i.message)}else if(Go!==void 0&&!Ae&&!Zt&&!qi){Jo.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),Q(i.message)}}},[K,de,pr,an,Go,Ae,Zt,qi,l,Q]);let $i=(0,s.useRef)(!1);(0,s.useEffect)(()=>{if($i.current||!Ko)return;let i=[];q!==!0&&i.push("showApplePay"),ie!==!0&&i.push("showGooglePay"),i.length!==0&&($i.current=!0,console.warn(`[FloPay] ${i.join(" / ")} ${i.length===1?"is":"are"} deprecated: the Apple Pay / Google Pay surface is now driven by \`gateways.stripe.enabledPaymentMethods\` on the session response. Remove the legacy prop(s) to silence this warning.`))},[Ko,q,ie]);let ji=(0,s.useCallback)((i,S)=>ve.applyInlineSessionPatch?ve.applyInlineSessionPatch(i).then(V=>({error:null,sessionId:V.sessionId||e,nonce:V.session?.clientSecret||t})).catch(V=>{let Fe=js(S,V);return Q(Fe.message),l?.(Fe),{error:Fe,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[ve.applyInlineSessionPatch,t,l,e,Q]),nr=(0,s.useCallback)(async i=>{if(!Te)return{proceed:!0};try{let S=await Te({method:i,sessionId:e||void 0,createSession:ve.inlineSessionDraft});if(S===!1)return{proceed:!1};if(S&&typeof S=="object"){S.account&&vn(Fe=>({...Fe??{},...S.account}));let V=await ji(S,i);return V.error?{proceed:!1,accountPatch:S.account}:{proceed:!0,accountPatch:S.account,sessionId:V.sessionId,nonce:V.nonce}}return{proceed:!0}}catch(S){let V=js(i,S);return Q(V.message),l?.(V),{proceed:!1}}},[ji,ve.inlineSessionDraft,Te,l,e,Q]),Vi=(0,s.useCallback)(async(i,S)=>{if(kn.current)return;kn.current=!0,et(!0),yt("processing"),Q(null);let V=S?.sessionId??e,Fe=S?.nonce??t,Y=Ya(g,S?.accountPatch),Pe=S?.completionPaymentMethodId??Eo(i),Qt=i.originalPaymentMethodId?{...i,originalPaymentMethodId:void 0}:i,Ye=Wc(i),Nt=()=>{Bt?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"process_payment",provider:Ye})};try{let It=await new Ir.PaymentAPI(m).processPayment(Y.userId??"",{sessionId:V,nonce:Fe,paymentMethodCategory:S?.paymentMethodCategory??Yc(i),tokenizedData:Qt,accountData:{...S?.accountPatch,userId:Y.userId??"",email:Y.email??"",firstName:Y.firstName||void 0,lastName:Y.lastName||void 0,...E?(()=>{let ft=Yt.current,Gn=(0,u.isAVSFieldVisible)(E.state,ft),_n=(0,u.isAVSFieldVisible)(E.address_line_1,ft),Ot=(0,u.isAVSFieldVisible)(E.postal_code,ft),Lr=_n&&!Gn&&Ot?(0,u.getStateFromPostalCode)(ft,(ht.current??"").trim()):null,Io=Gn?Jt.current:Lr;return{country:ft,...Ot&&ht.current?{zip:ht.current}:{},...(0,u.isAVSFieldVisible)(E.city,ft)&&Pn.current?{city:Pn.current}:{},...Io?{state:Io}:{},..._n&&dt.current?{addressLine1:dt.current}:{},...(0,u.isAVSFieldVisible)(E.address_line_2,ft)&&Tt.current?{addressLine2:Tt.current}:{}}})():{}},chv:b,avsCheck:Qe??!1,checkoutType:Z,checkoutLayout:X,avsConfig:E?{country:(0,u.isAVSFieldVisible)(E.country,Yt.current),postal_code:(0,u.isAVSFieldVisible)(E.postal_code,Yt.current),address_line_1:(0,u.isAVSFieldVisible)(E.address_line_1,Yt.current),address_line_2:(0,u.isAVSFieldVisible)(E.address_line_2,Yt.current),city:(0,u.isAVSFieldVisible)(E.city,Yt.current),state:(0,u.isAVSFieldVisible)(E.state,Yt.current)}:void 0});if(It.ok){let ft=It.status===204?null:await It.json().catch(()=>null),Gn=(0,u.isAuthorizationOnlySession)(H)||ft?.status==="authorized";co(V),yt("success"),ne(null),await new Promise(Lr=>setTimeout(Lr,1200));let _n;typeof ft?.paymentId=="string"?_n=ft.paymentId:H?.paymentId&&(_n=H.paymentId);let Ot;typeof ft?.authorizationExpiresAt=="string"?Ot=ft.authorizationExpiresAt:H?.authorizationExpiresAt&&(Ot=H.authorizationExpiresAt),a?.(Gn?{status:"authorized",..._n===void 0?{}:{paymentId:_n},sessionId:typeof ft?.sessionId=="string"?ft.sessionId:V,...Ot===void 0?{}:{authorizationExpiresAt:Ot},paymentIntentId:i.threeDSecureActionResultTokenId,paymentMethodId:Pe,checkoutMethod:i.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:i.threeDSecureActionResultTokenId,paymentMethodId:Pe,checkoutMethod:i.isPaypal?"paypal":"card"});return}let Rt=await It.json().catch(()=>null);if(Rt?.type==="paypal_redirect_required"){let ft=Rt.threeDSecureToken,Gn=Rt.paymentMethodId||i.id||"";if(!j||!ft){yt("error"),Q("PayPal authorization required but no token provided.");return}try{let _n=qe?.getRawProvider();if(!_n){Q("PayPal is not available.");return}let Ot={return_url:window.location.href};Gn&&(Ot.payment_method=Gn);let{error:Lr}=await _n.confirmPayment({clientSecret:ft,confirmParams:Ot,redirect:"if_required"});if(Lr){yt("error");let Io=Lr.message??"PayPal payment failed.";Q(Io),tr("paypal",Io,{code:Lr.code})}}catch(_n){yt("error"),Q(_n instanceof Error?_n.message:"PayPal authorization failed.")}return}if(Rt?.type==="paypal_direct_required"){let ft=Rt.orderId;if(!ft){yt("error"),Q("PayPal retry required but no order id provided.");return}let Gn=He.current?.attempts??0;if(Gn>=2){yt("error"),Q("PayPal payment could not be completed after multiple attempts."),tr("paypal","paypal_direct_required retry limit exceeded");return}La(!1),Na("loading"),ne({orderId:ft,attempts:Gn+1}),yt(null);return}(0,u.classifyPaymentRejection)(It.status,Rt)||Nt(),yt("error");let vr=Rt?.message??"Payment failed. Please try again.";Q(vr),tr(i.isPaypal?"paypal":"card",vr,{code:Rt?.code??Rt?.gatewayErrorCode,declineCode:Rt?.declineCode??Rt?.gatewayDeclineReason}),await new Promise(ft=>setTimeout(ft,1500))}catch(Pt){Ys(Pt)||Nt(),yt("error"),Q(Pt instanceof Error?Pt.message:"An unexpected error occurred"),await new Promise(It=>setTimeout(It,1500))}finally{et(!1),yt(null),kn.current=!1}},[m,e,t,g,E,Qe,Z,X,b,j,qe,H,a,Q,tr,Bt]),Bn=(0,s.useCallback)((i,S)=>{f?f(i):Vi(i,S)},[f,Vi]),Po=`${Gs}:${e}`;(0,s.useEffect)(()=>{if(typeof window>"u")return;let i=localStorage.getItem(Po);if(!i)return;let S;try{S=JSON.parse(i)}catch{localStorage.removeItem(Po);return}if(!S||typeof S.createdAt!="number"||Date.now()-S.createdAt<0||Date.now()-S.createdAt>Lc||typeof S.paymentMethodId!="string"||typeof S.providerIntentId!="string"||typeof S.paymentMethodType!="string"||S.sessionId!==e||!t||S.nonce!==t||!Hr.includes(S.paymentMethodType)){localStorage.removeItem(Po);return}localStorage.removeItem(Po),Bn({id:S.paymentMethodId,type:"card",threeDSecureActionResultTokenId:S.providerIntentId,gateway:"stripe",paymentMethodType:S.paymentMethodType},{...S.accountPatch?{accountPatch:S.accountPatch}:{},paymentMethodCategory:"wallet",sessionId:e,nonce:t})},[Bn,t,e,Po,Hr]);let Ki=(0,s.useRef)(!1);(0,s.useEffect)(()=>{if(typeof window>"u"||Ki.current)return;let i=new URLSearchParams(window.location.search),S=i.get("payment_intent"),V=i.get("payment_intent_client_secret"),Fe=i.get("redirect_status");if(!S||!V)return;let Y=It=>{let Rt=localStorage.getItem(It);if(!Rt)return null;try{return JSON.parse(Rt)}catch{return localStorage.removeItem(It),null}},Pe=Y(yr)??Y(Os),Qt;if(Pe?.clientSecret){if(Pe.clientSecret!==V)return;Qt={...Pe.accountPatch?{accountPatch:Pe.accountPatch}:{},...Pe.sessionId?{sessionId:Pe.sessionId}:{},...Pe.nonce?{nonce:Pe.nonce}:{}}}else if(Pe?.sessionId&&Pe.sessionId!==e)return;Ki.current=!0,localStorage.removeItem(yr),localStorage.removeItem(Os);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());let Nt=Pe?.paymentMethodType??Pe?.tokenType??"card",Pt="card";(async()=>{let It=j?.getRawProvider();if(!It){let Ot="Payment is not available \u2014 please refresh and try again.";Q(Ot),tr(Pt,Ot);return}if(Fe==="failed"){let Ot="Payment was declined. Please try again.";Q(Ot),tr(Pt,Ot);return}let{paymentIntent:Rt,error:vr}=await It.retrievePaymentIntent(V);if(vr){let Ot=vr.message??"Failed to retrieve payment status.";Q(Ot),tr(Pt,Ot,{code:vr.code});return}let ft=Rt?.status,Gn=_o(ft);if(!Rt||!Gn){let Ot=ft==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";Q(Ot),tr(Pt,Ot,{code:ft??"missing_payment_intent"});return}let _n=typeof Rt.payment_method=="string"?Rt.payment_method:Rt.payment_method?.id;Bn({id:_n??Pe?.paymentMethodId??Pe?.tokenId??Rt.id,type:"card",threeDSecureActionResultTokenId:Rt.id,gateway:Pe?.gateway??"stripe",paymentMethodType:Nt},Qt)})()},[e,Bn,j,Q,tr]);let za=(0,s.useCallback)(i=>{i.preventDefault()},[]);if(!(j!==null))return(0,d.jsx)("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let Co=se==="buttons",Fn=G?.variables,kl=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),Ua=Fn?.colorBackground,Il=Ua&&!kl.has(Ua)?Ua:void 0,So=k.cardInputBorder??(Co?"#e5e7eb":"#A4A4FF"),Hi=Fn?.colorDanger??"#dc2626",Lt=i=>pe[i]&&(er[i]||xn),Xo=vt&&(at||xn),Wn=i=>i?Hi:So,Zo=(L.malformed||L.empty)&&(wn||xn),Rl=Wn(Zo),qa=k.cardFormContainer?.backgroundColor??Il??(Co?"white":"#EDEDFF"),Gr=k.cardInputBackground??Fn?.colorBackground??"white",$a=Xr(Se),Wi=Xr(Re),Yr=k.nameInput,Gi=k.cardInputFontSize??td(Yr?.fontSize)??Fn?.fontSizeBase??"16px",Yi=typeof Yr?.fontFamily=="string"?Yr.fontFamily:Fn?.fontFamily??"Poppins, sans-serif",Ji=ci(Yr?.fontWeight)??400,_l=k.cardInputColor??(typeof Yr?.color=="string"?Yr.color:void 0)??Fn?.colorText??"#262833",El=k.cardInputPlaceholderColor??"#9ca3af",Kt=Fn?.borderRadius??"8px",Fr=Fn?.borderRadius??k.cardButton?.borderRadius??Kt,Dr=Fn?.colorPrimary??"#4A49FF",Tl=Fn?.colorPrimaryHover??yo(Dr,.12),ja=Fn?.colorText??"#262833",Va={fontSize:Gi,fontFamily:Yi,fontWeight:Ji,color:_l,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},wo={marginTop:"0.375rem",...Va,fontSize:"0.75rem",lineHeight:1.4,color:Hi},xl={"--flopay-input-placeholder-color":El,"--flopay-input-font-size":Gi,"--flopay-input-font-family":Yi,"--flopay-input-font-weight":String(Ji)},ko=k.cardFormContainer??{},Ka=ko.padding??(Co?"0":"1rem"),Ha=ko.borderRadius??Kt,Al=pt&&On?(0,d.jsx)(mo,{capture:pt,html:On.html,messageToken:On.messageToken,expectedOrigin:On.expectedOrigin,theme:Ze,onReady:()=>{if(!At&&!E||typeof document>"u")return;let i=()=>{let V=(document.querySelector('[data-testid="flopay-vault-identity-fields"]')??document.querySelector('[data-testid="flopay-avs-fields"]'))?.querySelector("input:not([disabled]), select:not([disabled])");if(V){$n.current=!0;try{V.focus()}finally{$n.current=!1}}};jt.current||i()},onError:i=>Q(i),onValidation:i=>{let S=x.current;(S==="idle"||S==="validation-window")&&(Q(i),i&&x.current==="validation-window"&&(A.current&&(clearTimeout(A.current),A.current=null),x.current="idle",yt(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"}),Xi=(0,d.jsxs)("div",{onFocusCapture:i=>{["INPUT","SELECT","TEXTAREA","IFRAME"].includes(i.target.tagName)&&Kn()},style:{backgroundColor:qa,borderRadius:Ha,...ko,padding:Ka,...xl,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 @@ ${Ut.join(`
35
35
  font-family: var(--flopay-input-font-family);
36
36
  font-weight: var(--flopay-input-font-weight);
37
37
  }
38
- `}),go&&Rr&&(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:Se?-2:0},children:[(0,d.jsxs)("button",{type:"button",onClick:Er,style:{display:"inline-flex",alignItems:"center",gap:Da?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:f.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...f.backButton},"aria-label":"Back to payment methods",children:[(0,d.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...f.backButtonIcon},children:(0,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:Te})]}),$i?(0,d.jsx)("div",{style:{flex:1}}):(0,d.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:f.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...f.title},children:(0,d.jsx)(Po,{content:xe})})]}),!go&&!$i&&(0,d.jsx)("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:Na,order:Se?-3:0,...f.title},children:(0,d.jsx)(Po,{content:xe})}),Se&&Oe&&(0,d.jsx)("div",{style:{order:-2,width:"100%"},children:Oe}),Se&&fe&&(0,d.jsxs)("div",{"data-testid":"flopay-vault-identity-fields",style:{order:-1,marginTop:"0.5rem"},children:[(0,d.jsx)("div",{style:{backgroundColor:Vr,border:`1px solid ${Dn(Ko)}`,borderRadius:Lt,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:Ze,onChange:i=>{ot("email"),Rn.current=i.target.value,Yt(i.target.value)},onPointerDown:()=>ot("email"),onKeyDown:()=>ot("email"),onBlur:()=>{Tn("email")&&Ir(!0),Xe||Ra()},disabled:we,required:!0,"aria-invalid":Ko||void 0,"aria-describedby":Ko?"flopay-buyer-email-error":void 0,"data-testid":"flopay-email",style:{width:"100%",border:"none",outline:"none",background:"transparent",...La}})}),Ko&&(0,d.jsx)("div",{id:"flopay-buyer-email-error",role:"alert","data-testid":"flopay-email-error",style:bo,children:st.empty?"Email address is required":"Enter a valid email address"})]}),_&&(0,d.jsx)("div",{style:{order:Se?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let i=qt,S=(Z=!1)=>({backgroundColor:Vr,border:`1px solid ${Dn(Z)}`,borderRadius:Lt,marginTop:"0.5rem",padding:"10px"}),G=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...La}),Be=(0,p.getStateOptions)(i);return(0,d.jsxs)(d.Fragment,{children:[(0,p.isAVSFieldVisible)(_.address_line_1,i)&&(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("div",{style:S(xt("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:Z=>{ot("line1"),bt.current.addressLine1=!0,Jt.current=Z.target.value,Zt(Z.target.value)},onPointerDown:()=>ot("line1"),onKeyDown:()=>ot("line1"),onBlur:()=>xn("line1"),disabled:we,required:!0,"aria-invalid":xt("line1")||void 0,"aria-describedby":xt("line1")?"flopay-billing-address-line1-error":void 0,"data-testid":"flopay-address-line1",style:G()})}),xt("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,p.isAVSFieldVisible)(_.address_line_2,i)&&(0,d.jsx)("div",{style:S(),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:$e,onChange:Z=>{bt.current.addressLine2=!0,on.current=Z.target.value,ht(Z.target.value)},disabled:we,"data-testid":"flopay-address-line2",style:G()})}),((0,p.isAVSFieldVisible)(_.city,i)||(0,p.isAVSFieldVisible)(_.state,i))&&(0,d.jsxs)("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[(0,p.isAVSFieldVisible)(_.city,i)&&(0,d.jsx)("div",{style:{flex:1,backgroundColor:Vr,borderTop:`1px solid ${Dn(xt("city"))}`,borderRight:`1px solid ${Dn(xt("city"))}`,borderBottom:`1px solid ${Dn(xt("city"))}`,borderLeft:`1px solid ${Dn(xt("city"))}`,padding:"10px",borderTopLeftRadius:Lt,borderBottomLeftRadius:Lt,...(0,p.isAVSFieldVisible)(_.state,i)?{borderRight:"none",borderTopRightRadius:0,borderBottomRightRadius:0}:{borderRadius:Lt}},children:(0,d.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-city",name:"billing-city",placeholder:"City",autoComplete:"billing address-level2",value:Qt,onChange:Z=>{ot("city"),bt.current.city=!0,In.current=Z.target.value,Dt(Z.target.value)},onPointerDown:()=>ot("city"),onKeyDown:()=>ot("city"),onBlur:()=>xn("city"),disabled:we,required:!0,"aria-invalid":xt("city")||void 0,"aria-describedby":xt("city")?"flopay-billing-city-error":void 0,"data-testid":"flopay-city",style:G()})}),(0,p.isAVSFieldVisible)(_.state,i)&&(0,d.jsx)("div",{style:{flex:1,backgroundColor:Vr,borderTop:`1px solid ${Dn(xt("state"))}`,borderRight:`1px solid ${Dn(xt("state"))}`,borderBottom:`1px solid ${Dn(xt("state"))}`,borderLeft:`1px solid ${Dn(xt("state"))}`,padding:"10px",borderTopRightRadius:Lt,borderBottomRightRadius:Lt,...(0,p.isAVSFieldVisible)(_.city,i)?{borderTopLeftRadius:0,borderBottomLeftRadius:0,borderLeft:`1px solid ${Dn(xt("state")||xt("city"))}`}:{borderRadius:Lt}},children:Be?(0,d.jsxs)("select",{id:"flopay-billing-state",name:"billing-state",value:nn,onChange:Z=>{ot("state"),bt.current.state=!0,Kt.current=Z.target.value,Vt(Z.target.value)},onPointerDown:()=>ot("state"),onKeyDown:()=>ot("state"),onBlur:()=>xn("state"),disabled:we,autoComplete:"billing address-level1",required:!0,"aria-invalid":xt("state")||void 0,"aria-describedby":xt("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:{...G(),cursor:"pointer"},children:[(0,d.jsx)("option",{value:"",children:(0,p.getStateLabel)(i)}),Be.map(Z=>(0,d.jsx)("option",{value:Z.code,children:Z.name},Z.code))]}):(0,d.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-state",name:"billing-state",placeholder:(0,p.getStateLabel)(i),autoComplete:"billing address-level1",value:nn,onChange:Z=>{ot("state"),bt.current.state=!0,Kt.current=Z.target.value,Vt(Z.target.value)},onPointerDown:()=>ot("state"),onKeyDown:()=>ot("state"),onBlur:()=>xn("state"),disabled:we,required:!0,"aria-invalid":xt("state")||void 0,"aria-describedby":xt("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:G()})})]}),xt("city")&&(0,d.jsx)("div",{id:"flopay-billing-city-error",role:"alert","data-testid":"flopay-city-error",style:bo,children:"City is required"}),xt("state")&&(0,d.jsxs)("div",{id:"flopay-billing-state-error",role:"alert","data-testid":"flopay-state-error",style:bo,children:[(0,p.getStateLabel)(i)," is required"]}),((0,p.isAVSFieldVisible)(_.country,i)||(0,p.isAVSFieldVisible)(_.postal_code,i))&&(0,d.jsxs)("div",{style:{display:"flex",flexDirection:ke==="column"?"column":"row",gap:ke==="column"?"0.5rem":"0",marginTop:"0.5rem"},children:[(0,p.isAVSFieldVisible)(_.country,i)&&(0,d.jsx)("div",{style:{flex:ke==="row"?1:void 0,backgroundColor:Vr,borderTop:`1px solid ${ho}`,borderRight:`1px solid ${ho}`,borderBottom:`1px solid ${ho}`,borderLeft:`1px solid ${ho}`,padding:"10px",...ke==="row"&&(0,p.isAVSFieldVisible)(_.postal_code,i)?{borderRadius:"0",borderTopLeftRadius:Lt,borderBottomLeftRadius:Lt,borderRight:"none"}:{borderRadius:Lt}},children:(0,d.jsx)("select",{id:"flopay-billing-country",name:"billing-country",value:qt,onChange:Z=>{bt.current.country=!0,jt.current=Z.target.value,Gt(Z.target.value),tt?.(Z.target.value),Kt.current="",Vt("")},disabled:we,autoComplete:"billing country","data-testid":"flopay-country",style:{...G(),cursor:"pointer"},children:p.COUNTRY_OPTIONS.map(Z=>(0,d.jsxs)("option",{value:Z.code,children:[Z.flag," ",Z.name]},Z.code))})}),(0,p.isAVSFieldVisible)(_.postal_code,i)&&(0,d.jsx)("div",{style:{flex:ke==="row"?1:void 0,backgroundColor:Vr,border:`1px solid ${kl}`,padding:"10px",...ke==="row"&&(0,p.isAVSFieldVisible)(_.country,i)?{borderRadius:"0",borderTopRightRadius:Lt,borderBottomRightRadius:Lt}:{borderRadius:Lt}},children:(0,d.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-postal-code",name:"billing-postal-code",placeholder:(0,p.getPostalCodeLabel)(qt),autoComplete:"billing postal-code",value:$t,onChange:Z=>{ot("zip"),bt.current.zip=!0,at.current=Z.target.value,kn(Z.target.value),gt?.(Z.target.value)},onPointerDown:()=>ot("zip"),onKeyDown:()=>ot("zip"),onBlur:()=>{Tn("zip")&&ur(!0)},disabled:we,required:yt.required,"aria-invalid":Ho||void 0,"aria-describedby":Ho?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:G()})})]}),Ho&&(0,d.jsx)("div",{id:"flopay-billing-postal-code-error",role:"alert","data-testid":"flopay-zip-error",style:bo,children:yt.empty?`${(0,p.getPostalCodeLabel)(i)} is required`:Kc(i)})]})})()}),Se&&Tl,C&&(0,d.jsx)(to,{margin:"0.75rem 0",styleOverride:f.errorBanner,children:C})]}),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"},Wi=i=>B?!ye||!or?(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=${ye}`,` directPaypalConfigured=${or}`,` inAppBrowserDetected=${String(Vo)}`,` shouldRenderDirectPayPal=${po}`,` shouldRenderStripePayPal=${mo}`,` hasPaypalStripeInstance=${!!Pt}`].join(`
39
- `)}):null,Gi=i=>B?!W||!be?(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=${W}`,` currency=${qe}`,` amountInCents=${yn}`,` enabledPaymentMethods: ${JSON.stringify(I??[])}`,` enabledPaymentMethodsProvided=${co}`,` hasEnabledMethods=${Uo}`,` expressMethods: ${JSON.stringify(qo)}`,` walletExpressMethods: ${JSON.stringify(qr)}`,` paymentElementMethods: ${JSON.stringify(uo)}`,` paymentElementMethodsForCurrency: ${JSON.stringify($o)}`,` hasStripeInstance=${!!be}`,` shouldRenderWallets=${$r}`,` shouldRenderPaymentElement=${yo}`].join(`
40
- `)}):null,Yi=je==="apm-expanding"||je==="apm-form"||je==="apm-collapsing",Kr;je==="apm-expanding"?Kr=Os:je==="apm-collapsing"&&(Kr=zs);let Go=Tt?Zs(Ta,Tt):null;if(re==="buttons"){let i=je==="buttons"||je==="expanding"||je==="apm-expanding",S=je==="expanding"||je==="card"||je==="collapsing",G=Ge===void 0?{boxSizing:"border-box",height:ya,padding:"0 1rem"}:{padding:"0.9rem 1rem"},Be;je==="expanding"||je==="apm-expanding"?Be=zc:(je==="collapsing"||je==="apm-collapsing")&&(Be=Oc);let Z;return je==="expanding"?Z=Os:je==="collapsing"&&(Z=zs),(0,d.jsxs)("form",{onSubmit:Aa,className:h,noValidate:!0,style:{position:"relative"},children:[(0,d.jsx)(ai,{}),ln&&(0,d.jsx)(zn,{status:ln,errorMessage:C,authorized:Ct}),(0,d.jsxs)("div",{style:{display:"grid"},children:[(0,d.jsxs)("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!i&&!Be?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!i&&!Be?qc:{},...Be?{animation:Be,pointerEvents:"none"}:{}},children:[Wi("flopay-direct-paypal-gate-debug"),Gi("flopay-stripe-gate-debug"),po&&ve&&(0,d.jsxs)(d.Fragment,{children:[K&&(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:_e,email:F.email,billingName:H||void 0,onBuyerIdentityReady:u,clientId:ve.clientId,environment:ve.environment,currency:qe.toUpperCase(),isSubscription:Je,providerObjectType:T,onTokenizedBody:Pn,onComplete:a,onErrorChange:ge,onDecline:c,onTechnicalFailure:Ur,onButtonClick:ae,runBeforeButtonClick:Xn,isProcessing:we,onLoadStateChange:xa,onInitializationStateChange:Ma,session:ct,existingOrderId:K?.orderId,debug:B},K?.orderId??"fresh")]}),mo&&(0,d.jsx)(zt.Elements,{stripe:Pt,options:Ci,children:(0,d.jsx)(Vs,{sessionId:e,nonce:t,email:F.email,billingName:H||void 0,onBuyerIdentityReady:u,billingApiUrl:_e,onTokenizedBody:Pn,onErrorChange:ge,isProcessing:we,onButtonClick:ae,onDecline:c,onTechnicalFailure:Ur,runBeforeButtonClick:Xn,onLoadStateChange:Ri,placeholderBorderRadius:_r})}),$r?(0,d.jsx)(zt.Elements,{stripe:be,options:vi,children:(0,d.jsx)(js,{sessionId:e,nonce:t,email:F.email,billingName:H||void 0,onBuyerIdentityReady:u,billingApiUrl:_e,intentKind:$>0?"payment":"setup",expressMethods:qr,onTokenizedBody:Pn,onErrorChange:ge,onButtonClick:ae,onDecline:c,onTechnicalFailure:Ur,runBeforeButtonClick:Xn,onLoadStateChange:_i,placeholderBorderRadius:_r})}):null,!$r&&Bi?(0,d.jsx)("div",{style:{height:ya,borderRadius:_r,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,yo&&(0,d.jsx)(Ks,{sessionId:e,nonce:t,email:F.email,billingName:[F.firstName,F.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:u,billingApiUrl:_e,paymentElementMethods:$o,stripeInstance:be,paymentElementBaseOptions:Ta,onTokenizedBody:Pn,onErrorChange:ge,onButtonClick:ae,onDecline:c,runBeforeButtonClick:Xn,onLoadStateChange:xi,isProcessing:we,submitButtonColor:Tr,submitButtonBorderRadius:Lt,submitButtonStyle:f.submitButton,onExpandApm:An,expandedApmMethod:Tt,themeId:le,buttonAppearance:{backgroundColor:f.cardButton?.backgroundColor,borderColor:f.cardInputBorder,textColor:f.cardButton?.color,borderRadius:_r}}),Se&&(0,d.jsx)("button",{type:"button",onClick:async()=>{we||!(await Xn("card")).proceed||(ae?.("card"),Gn())},disabled:we,style:{width:"100%",...G,...f.cardButton,...ci({themeBundle:U,resolvedPrimaryColor:Tr,resolvedBorderRadius:Lt,submitButtonStyle:f.submitButton,explicitPrimaryColor:Sn?.colorPrimary}),fontSize:f.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:we?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",transition:"background-color 0.15s, border-color 0.2s, box-shadow 0.2s, transform 0.1s",position:"relative",opacity:we?.6:1},onMouseEnter:Pe=>{!we&&(U||Sn?.colorPrimary)&&(Pe.currentTarget.style.backgroundColor=El)},onMouseLeave:Pe=>{(U||Sn?.colorPrimary)&&(Pe.currentTarget.style.backgroundColor=Tr)},onMouseDown:Pe=>{Pe.currentTarget.style.transform="scale(0.985)"},onMouseUp:Pe=>{Pe.currentTarget.style.transform="scale(1)"},children:(0,d.jsx)(Wr,{content:Ge})}),C&&je==="buttons"&&(0,d.jsx)(to,{margin:"0.25rem 0",styleOverride:f.errorBanner,children:C})]}),Se&&S&&(0,d.jsx)("div",{style:{gridArea:"1 / 1",...Z?{animation:Z}:{},...je==="collapsing"?{pointerEvents:"none"}:{}},children:Hi}),W&&Yi&&Tt&&Go&&be&&(0,d.jsx)("div",{style:{gridArea:"1 / 1",...Kr?{animation:Kr}:{},...je==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,d.jsxs)("div",{style:{backgroundColor:Fa,borderRadius:za,...vo,padding:Oa},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:Yn,style:{display:"inline-flex",alignItems:"center",gap:Da?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:f.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...f.backButton},"aria-label":"Back to payment methods",children:[(0,d.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...f.backButtonIcon},children:(0,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:Te})]}),(0,d.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:f.titleFontSize??"1.05rem",color:Na,paddingRight:80,...f.title},children:`Pay with ${(0,p.getStripeMethodDisplayName)(Tt)}`})]}),(0,d.jsx)(zt.Elements,{stripe:be,options:Go,children:(0,d.jsx)(si,{method:Tt,sessionId:e,nonce:t,email:F.email,billingName:[F.firstName,F.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:u,billingApiUrl:_e,onTokenizedBody:Pn,onErrorChange:ge,onDecline:c,onCancel:Yn,runBeforeButtonClick:Xn,onButtonClick:ae,isProcessing:we,submitButtonColor:Tr,submitButtonBorderRadius:Lt,submitButtonStyle:f.submitButton,errorText:C})},Tt)]})})]})]})}return Yi&&Tt&&Go&&be&&W?(0,d.jsxs)("form",{onSubmit:Aa,className:h,noValidate:!0,style:{position:"relative"},children:[(0,d.jsx)(ai,{}),ln&&(0,d.jsx)(zn,{status:ln,errorMessage:C,authorized:Ct}),(0,d.jsx)("div",{style:{...Kr?{animation:Kr}:{},...je==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,d.jsxs)("div",{style:{backgroundColor:Fa,borderRadius:za,...vo,padding:Oa},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:Yn,style:{display:"inline-flex",alignItems:"center",gap:Da?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:f.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...f.backButton},"aria-label":"Back to payment methods",children:[(0,d.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...f.backButtonIcon},children:(0,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:Te})]}),(0,d.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:f.titleFontSize??"1.05rem",color:Na,paddingRight:80,...f.title},children:`Pay with ${(0,p.getStripeMethodDisplayName)(Tt)}`})]}),(0,d.jsx)(zt.Elements,{stripe:be,options:Go,children:(0,d.jsx)(si,{method:Tt,sessionId:e,nonce:t,email:F.email,billingName:[F.firstName,F.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:u,billingApiUrl:_e,onTokenizedBody:Pn,onErrorChange:ge,onDecline:c,onCancel:Yn,runBeforeButtonClick:Xn,onButtonClick:ae,isProcessing:we,submitButtonColor:Tr,submitButtonBorderRadius:Lt,submitButtonStyle:f.submitButton,errorText:C})},Tt)]})})]}):(0,d.jsxs)("form",{onSubmit:Aa,className:h,noValidate:!0,style:{position:"relative"},children:[(0,d.jsx)(ai,{}),ln&&(0,d.jsx)(zn,{status:ln,errorMessage:C,authorized:Ct}),(0,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Wi("flopay-direct-paypal-gate-debug-default"),Gi("flopay-stripe-gate-debug-default"),po&&ve&&(0,d.jsxs)(d.Fragment,{children:[K&&(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:_e,email:F.email,billingName:H||void 0,onBuyerIdentityReady:u,clientId:ve.clientId,environment:ve.environment,currency:qe.toUpperCase(),isSubscription:Je,providerObjectType:T,onTokenizedBody:Pn,onComplete:a,onErrorChange:ge,onDecline:c,onTechnicalFailure:Ur,onButtonClick:ae,runBeforeButtonClick:Xn,isProcessing:we,onLoadStateChange:xa,onInitializationStateChange:Ma,session:ct,existingOrderId:K?.orderId,debug:B},K?.orderId??"fresh")]}),mo&&(0,d.jsx)(zt.Elements,{stripe:Pt,options:Ci,children:(0,d.jsx)(Vs,{sessionId:e,nonce:t,email:F.email,billingName:H||void 0,onBuyerIdentityReady:u,billingApiUrl:_e,onTokenizedBody:Pn,onErrorChange:ge,isProcessing:we,onButtonClick:ae,onDecline:c,onTechnicalFailure:Ur,runBeforeButtonClick:Xn,onLoadStateChange:Ri,placeholderBorderRadius:_r})}),$r&&(0,d.jsx)(zt.Elements,{stripe:be,options:vi,children:(0,d.jsx)(js,{sessionId:e,nonce:t,email:F.email,billingName:H||void 0,onBuyerIdentityReady:u,billingApiUrl:_e,intentKind:$>0?"payment":"setup",expressMethods:qr,onTokenizedBody:Pn,onErrorChange:ge,onButtonClick:ae,onDecline:c,onTechnicalFailure:Ur,runBeforeButtonClick:Xn,onLoadStateChange:_i,placeholderBorderRadius:_r})}),yo&&(0,d.jsx)(Ks,{sessionId:e,nonce:t,email:F.email,billingName:[F.firstName,F.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:_e,paymentElementMethods:$o,stripeInstance:be,paymentElementBaseOptions:Ta,onTokenizedBody:Pn,onErrorChange:ge,onButtonClick:ae,onDecline:c,runBeforeButtonClick:Xn,onLoadStateChange:xi,isProcessing:we,submitButtonColor:Tr,submitButtonBorderRadius:Lt,submitButtonStyle:f.submitButton,themeId:le,onExpandApm:An,expandedApmMethod:Tt,buttonAppearance:{backgroundColor:f.cardButton?.backgroundColor,borderColor:f.cardInputBorder,textColor:f.cardButton?.color,borderRadius:_r}})]}),Se&&(Cl||vl||Pl)&&(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"}})]}),Se&&Hi]})}var R=require("react/jsx-runtime"),Lr=44,gi="flopay_checkout_saved_payment_resume",Ca=new Map,ba=new Map;function Qs(e,t){t.settled&&t.consumers===0&&Ca.get(e)===t&&Ca.delete(e)}function Xc(e,t,n){let r=ba.get(e);if(r&&(!r.sdkGeneratedIdempotencyKey||!t||r.sdkGeneratedIdempotencyKey===t))return r.attempt;let o=n(),a={attempt:o,sdkGeneratedIdempotencyKey:t};ba.set(e,a);let l=()=>{ba.get(e)===a&&ba.delete(e)};return o.then(l,l),o}function Lo(e){return new Promise(t=>setTimeout(t,e))}function va(e,t,n){let r=ta({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:Fe.SDK_VERSION,enabled:t!==!1});return r.beginCheckout(n),r}function Oo(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function di(e,t,n,r,o,a){let l=va(e,t,n);l.error({errorCode:r,stage:o,paymentMethodCategory:"unknown",...a,...o==="session_read"?{requestCategory:"session_read"}:{}}),Oo(l)}function el(e,t,n,r){e.log({name:t==="session_claim"?"session.claim.completed":"session.request.completed",stage:t,requestCategory:t,statusClass:"2xx"}),e.performance({stage:t,durationMs:Math.max(0,e.now()-n),durationMode:"machine",requestCategory:t,...r===void 0?{}:{attempt:r},statusClass:"2xx"})}function tl(e,t,n,r,o){let a=(0,Fe.classifyTelemetryFailure)(t,"CHECKOUT_SESSION_CREATE_FAILED","unknown");return e.performance({stage:n,durationMs:Math.max(0,e.now()-r),durationMode:"machine",requestCategory:n,attempt:o,statusClass:a.statusClass}),t instanceof Fe.FloPayError&&t.code==="session_auto_completed"?!1:t instanceof Fe.FloPayError&&t.type==="validation_error"?(e.terminal({outcome:"validation_rejected",stage:n,paymentMethodCategory:"unknown"}),!1):a.statusClass==="4xx"?(e.terminal({outcome:"validation_rejected",stage:n,paymentMethodCategory:"unknown",requestCategory:n,statusClass:"4xx"}),!1):(e.error({...a,stage:n,paymentMethodCategory:"unknown",requestCategory:n}),!0)}function fi(e){let t=e?.data.paypal?.publishableKey;if(t)return{clientId:t,environment:e?.data.paypal?.environment,providerObjectType:e?.data.paypal?.providerObjectType}}function ui(e){return!e||e.data.stripe?.publishableKey?!1:!!fi(e)?.clientId}var Zc={name:"provider_unavailable",initialize:()=>Promise.resolve(),getRawProvider:()=>null,destroy:()=>{}};function Qc(e){return new Cr.FloPay(Zc,{publishableKey:"provider_unavailable",...e})}async function pi(e,t){let{publishableKey:n,paypalPublishableKey:r}=Qa(e);return{...await ei({publishableKey:n,paypalPublishableKey:r,...t}),publishableKey:n,paypalPublishableKey:r}}function hi(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function ed(){if(!hi())return null;try{let e=window.sessionStorage.getItem(gi);return e?JSON.parse(e):null}catch{return null}}function nl(e){if(hi())try{window.sessionStorage.setItem(gi,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function mi(){if(hi())try{window.sessionStorage.removeItem(gi)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}function td(){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 rl(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 yi(e,t){return e?"custom_layout":t==="buttons"?"buttons_layout":"default_layout"}function nd(e,t){return e?"unknown":t==="buttons"?"buttons":"embedded"}function ol(e){return e?.gateways?.stripe?"stripe":e?.gateways?.paypal?"paypal":void 0}function rd(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 Pa({sessionId:e,nonce:t,createSession:n,billingApiUrl:r,telemetry:o,appearance:a,locale:l,loading:c,error:g,onComplete:y,onError:m,onInstrument:v,onDecline:h,onCountryChange:w,onZipChange:D,showPayPal:N=!0,showStripe:ye=!0,enabledPaymentMethods:W,showApplePay:I=!0,showGooglePay:ie=!0,debug:q=!1,layout:ue,theme:re,buttonsTheme:le,buttonsStyles:He,cardButtonContent:ce,cardBackButtonContent:Rt,cardTitleContent:Ge,showSecurityFooter:Te,onButtonClick:xe,onBeforeButtonClick:oe,enableAVS:ae,cardFieldOrder:z,cardPreFormSlot:De,avsLayout:Ne,className:Ee,initialErrorMessage:Oe=null,children:ke,checkoutMode:k,confirmLabel:de,renderConfirmButton:he,onSessionCompleted:Y}){let L=(0,Fe.resolveBillingApiUrl)(r),Ie=(0,P.useMemo)(()=>(0,Fe.resolveTheme)(re),[re]),tt=a??Ie?.appearance,gt=n?"embedded_checkout":"standard_checkout",Ye=yi(ke,ue),[ee,J]=(0,P.useState)(null),[$,qe]=(0,P.useState)(null),et=(0,P.useRef)(null),ve=(0,P.useRef)(null),Je=(0,P.useRef)(0),[te,V]=(0,P.useState)(null),nt=(0,P.useRef)(null),[B,Q]=(0,P.useState)(null),ze=(0,P.useMemo)(()=>n?ro(n):"",[n]),pe=n?`create:${ze}`:`session:${e??""}`,lt=ol(B),ct=(0,P.useRef)(new Set),T=(0,P.useRef)(pe),O=(0,P.useRef)(pe);Fr(()=>{O.current=pe,T.current!==pe&&(T.current=pe,ct.current.clear())},[pe]);let kt=(0,P.useCallback)(x=>{if(O.current===pe){if(Ka.has(x.name)){if(ct.current.has(x.name))return;ct.current.add(x.name)}Qe(()=>v?.(x))}},[pe,v]),Le=eo(kt,pe),Ut=(0,P.useRef)(!1),cn=(0,P.useCallback)(x=>{if(Ut.current)return;let M=x.gateway||!lt?x:{...x,gateway:lt};kt(M)},[kt,lt]);(0,P.useEffect)(()=>{Le({class:"lifecycle",name:"checkout.mount"})},[Le]);let[X,Ft]=(0,P.useState)(e??""),mt=e??X,qt=n?"":mt,[Gt,$t]=(0,P.useState)(!0),[kn,hn]=(0,P.useState)(null),[Zt,$e]=(0,P.useState)(0),[ht,Qt]=(0,P.useState)("full"),[Dt,nn]=(0,P.useState)(!1),[Vt,Ze]=(0,P.useState)(Oe),[Yt,vt]=(0,P.useState)(null),[dn,at]=(0,P.useState)(null),[jt,Jt]=(0,P.useState)(!1),[on,In]=(0,P.useState)(void 0),[Kt,Rn]=(0,P.useState)(""),[bt,_]=(0,P.useState)(!1),[Et,Ct]=(0,P.useState)(!1),[Nt,en]=(0,P.useState)(!1),un=(0,P.useRef)(0),bn=(0,P.useRef)(void 0),[j,Se]=(0,P.useState)("loading"),[an,cr]=(0,P.useState)(0),Ve=(0,P.useRef)(!1),Pr=(0,P.useRef)(!1),qn=(0,P.useRef)(!1),dt=(0,P.useRef)(null),yt=(0,P.useMemo)(()=>({checkoutMode:k??ht,layout:nd(ke,ue)}),[k,ke,ht,ue]),$n=(0,P.useRef)(y);$n.current=y;let Vn=(0,P.useRef)(m);Vn.current=m;let dr=(0,P.useRef)(h);dr.current=h;let En=(0,P.useCallback)((x,M)=>{et.current=x,qe(x),nt.current=M,V(M)},[]),jn=(0,P.useCallback)(()=>{let x=ve.current;x&&(ve.current=null,x.destroy())},[]);(0,P.useEffect)(()=>{Xt($)?.setCheckoutContext(yt),te&&te!==$&&Xt(te)?.setCheckoutContext(yt)},[$,te,yt]);let ur=(0,P.useRef)(Y);ur.current=Y;let Kn=(0,P.useCallback)(x=>{Se(x),!(x!=="exhausted"||qn.current)&&(qn.current=!0,Vn.current?.(new Fe.FloPayError("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),Ir=(0,P.useCallback)(()=>{Se("retrying"),cr(x=>x+1)},[]);(0,P.useEffect)(()=>{Se("loading"),cr(0),qn.current=!1},[mt]),(0,P.useEffect)(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:Fe.SDK_VERSION,checkout_type:gt,checkout_layout:Ye,billing_api_url:L})},[Ye,gt,L]);let pn=(0,P.useMemo)(()=>n?ro(n,!0):"",[n]),pr=(0,P.useMemo)(()=>Kt===pn?on:void 0,[on,Kt,pn]),_n=(0,P.useMemo)(()=>n?qa(n,pr):void 0,[n,pr]),vn=k??_n?.checkoutMode??"full",_t=(0,P.useMemo)(()=>_n?{..._n,checkoutMode:vn}:void 0,[_n,vn]);(0,P.useEffect)(()=>{In(void 0),Rn(pn),bn.current=void 0,en(!1)},[pn]),(0,P.useEffect)(()=>{Ze(Oe)},[Oe]);let ot=(0,P.useCallback)((x,M,K)=>{Qe(()=>{dr.current?.(tn(x,M,K))})},[]),Tn=(0,P.useCallback)(async(x,M)=>{Ze(null),at(null),Jt(!1),vt("processing");let K=M?.sessionId??x.id,se=ol(x),Me=et.current??nt.current,_e=Xt(Me),Re=Me?null:va(L,o,yt),b={log:Ce=>{_e?_e.log(Ce):Re?.log(Ce)},error:Ce=>{_e?_e.error(Ce):Re?.error(Ce)},terminal:Ce=>{_e?_e.terminal(Ce):Re?.terminal(Ce)},performance:Ce=>{_e?_e.performance(Ce):Re?.performance(Ce)},now:()=>_e?.now()??Re?.now()??0,elapsed:Ce=>_e?.elapsed(Ce)??Math.max(0,(Re?.now()??Ce)-Ce)},u=b.now(),C=!!(M?.initialAutoProcessingError||M?.initialAutoProcessingPending),U=!1,f,E=()=>{U||(U=!0,C=!0,f=b.now(),b.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),b.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},Ae=!1,it=()=>{Ae||(Ae=!0,b.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),b.performance({stage:"processing",durationMs:b.elapsed(u),durationMode:"machine",paymentMethodCategory:"saved"}),f!==void 0&&b.performance({stage:"recovery",durationMs:b.elapsed(f),durationMode:"machine",paymentMethodCategory:"saved"}))};b.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),Ut.current=!0;try{b.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"})}finally{Ut.current=!1}Le({class:"lifecycle",name:"payment.processing.started",provider:se}),C&&E();let we;try{let Ce=Ps(M?.initialAutoProcessingError),F;if(Ce)E(),Ce.type==="paypal_redirect_required"&&dt.current?.publishableKey&&nl({sessionId:K,publishableKey:dt.current.publishableKey,paypalPublishableKey:dt.current.paypalPublishableKey}),F=await ua(Ce,{flopay:et.current,paypalFlopay:nt.current,attempt3DS:M?.attempt3DS,billingApiUrl:L,sessionId:K,session:x,telemetry:!1}),Ce.type==="paypal_redirect_required"&&mi();else if(M?.initialAutoProcessingPending){let ne=(await new Cr.PaymentAPI(L,{telemetry:!1}).waitForCheckoutSessionCompletion(M.initialAutoProcessingPending.sessionId,{initialDelayMs:M.initialAutoProcessingPending.retryAfterMs})).data.session;if(!Jr(ne))throw Zo(ne);F=Ar(ne,K)}else{if(M?.initialAutoProcessingError)throw kr(M.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:M.initialAutoProcessingError.checkoutMethod});if(M?.fromCreateSession)return M?.fallbackToFull&&(Qt("full"),rl("full")),!1;{let H=await io({billingApiUrl:L,sessionId:K,session:x,telemetry:!1});H.type==="success"?F=H.result:(E(),H.type==="paypal_redirect_required"&&dt.current?.publishableKey&&nl({sessionId:K,publishableKey:dt.current.publishableKey,paypalPublishableKey:dt.current.paypalPublishableKey}),F=await ua(H,{flopay:et.current,paypalFlopay:nt.current,attempt3DS:M?.attempt3DS,billingApiUrl:L,sessionId:K,session:x,telemetry:!1}),H.type==="paypal_redirect_required"&&mi())}}K&&oo(K),it(),C&&(b.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),b.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),b.terminal({outcome:F.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),Jt(F.status==="authorized"),vt("success"),await Lo(1200),we=()=>$n.current?.(F)}catch(Ce){let F=Ao(Ce),H=F.checkoutMethod??Mo;Ze(F.message),at(F.message),Jt(!1),M?.fallbackToFull&&(b.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),Qt("full"),rl("full")),it();let me=F.statusCode===void 0?void 0:(0,Fe.telemetryStatusClass)(F.statusCode,"unknown"),ne=me==="4xx"?{requestCategory:"process_payment",statusClass:me}:{},fe=me===void 0||me==="4xx";if(fe&&(F.telemetryOutcome==="payment_declined"||!!(F.declineCode||F.code?.toLowerCase().includes("declin"))))b.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...ne});else if(fe&&(F.telemetryOutcome==="validation_rejected"||F.type==="validation_error"))b.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...ne});else{let be=(0,Fe.classifyTelemetryFailure)(Ce,C?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown"),Pt=F.telemetryRequestCategory??"process_payment";Ut.current=!0;try{b.error({...be,...F.telemetryFailureCategory?{failureCategory:F.telemetryFailureCategory}:{},stage:C?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:Pt})}finally{Ut.current=!1}Le({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:Pt,provider:se})}return Qe(()=>Vn.current?.(F)),ot(H,F,{code:F.code,declineCode:F.declineCode}),vt("error"),await Promise.allSettled([Lo(1500),M?.ensureProvidersReady?M.ensureProvidersReady():Promise.resolve()]),C&&(b.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),b.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{it(),Re&&Oo(Re),vt(null),at(null)}return Qe(we),!0},[ot,Le,L,o,yt]);(0,P.useEffect)(()=>{if(typeof window>"u"||Pr.current)return;let x=new URLSearchParams(window.location.search),M=x.get("payment_intent_client_secret");if(!M)return;let K=ed();K&&(Pr.current=!0,(async()=>{let se,Me=0;Ze(null),at(null),vt("processing"),nn(!0);try{if(x.get("redirect_status")==="failed")throw Object.assign(new Fe.FloPayError("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:_e,paypalFlopay:Re}=await ei({publishableKey:K.publishableKey,paypalPublishableKey:K.paypalPublishableKey,billingApiUrl:L,locale:l,telemetry:o});se=Xt(Re??_e),se?.setCheckoutContext(yt),Me=se?.now()??0,se?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),se?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let b=(Re??_e)?.getRawProvider();if(!b)throw Object.assign(new Fe.FloPayError("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:u,error:C}=await b.retrievePaymentIntent(M);if(C)throw Object.assign(new Fe.FloPayError(C.message??"Failed to retrieve PayPal payment status.","api_error",{code:C.code}),{checkoutMethod:"paypal"});let U=os(u?.status);if(!u||U==="failed")throw Object.assign(new Fe.FloPayError("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let f=typeof u.payment_method=="string"?u.payment_method:u.payment_method?.id,E=U;if(K.sessionId){let we=(await new Cr.PaymentAPI(L,{telemetry:!1}).getUnifiedCheckoutSession(K.sessionId)).data.session;if(we&&we.status!=="complete"){let Ce=await io({billingApiUrl:L,sessionId:K.sessionId,session:we,telemetry:!1,tokenizedData:{id:f??u.id,type:"card",threeDSecureActionResultTokenId:u.id,isPaypal:!0}});if(Ce.type!=="success")throw Object.assign(new Fe.FloPayError("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});E=Ce.result.status}}K.sessionId&&oo(K.sessionId),se?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),se?.performance({stage:"redirect_resume",durationMs:se.elapsed(Me),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),se?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),vt("success"),await Lo(1200),Qe(()=>$n.current?.({status:E,paymentIntentId:u.id,paymentMethodId:f,checkoutMethod:"paypal"}))}catch(_e){let Re=Ao(_e),b=Re.checkoutMethod??"paypal",u=!!(Re.declineCode||Re.code?.toLowerCase().includes("declin"));if(se)se.performance({stage:"redirect_resume",durationMs:se.elapsed(Me),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),u?se.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):se.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(u){let C=va(L,o,yt);C.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),Oo(C)}else di(L,o,yt,"REDIRECT_RESUME_FAILED","redirect_resume");Ze(Re.message),at(Re.message),Qe(()=>Vn.current?.(Re)),ot(b,Re,{code:Re.code,declineCode:Re.declineCode}),vt("error"),await Lo(1500)}finally{mi(),td(),vt(null),at(null),nn(!1)}})())},[ot,l,L,o,yt]);let xn=(0,P.useRef)(null),sn=(0,P.useMemo)(()=>_t?ro(_t):"",[_t]),Fn=(0,P.useRef)(_t);Fn.current=_t,(0,P.useEffect)(()=>{Ft(e??"")},[e]),(0,P.useEffect)(()=>{Ve.current=!1,Ze(Oe),at(null),Jt(!1),vt(null)},[sn,Oe,e]);async function je(x,M,K){let se=va(L,o,yt),Me=new Cr.PaymentAPI(L,{telemetry:!1}),_e=!1;try{let Re=x.idempotencyKey===void 0?void 0:(0,Fe.resolveIdempotencyKey)(x.idempotencyKey),b=Ga(M,K),u=Ya(M,K);b?.canonicalIdentity===K&&u&&u.canonicalIdentity===void 0&&(la(M,K,u.idempotencyKey),u={...u,canonicalIdentity:K});let C=Re??(u?.canonicalIdentity===K?u.idempotencyKey:void 0),U,f=!1;se.log({name:b?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let E=b?.sid??null,Ae=null,it,we,Ce=!1;if(E)try{Ae=await Me.getUnifiedCheckoutSession(E,b?.nonce),b&&b.canonicalIdentity===void 0&&(hs(Ae.data.session,x)?(sa(M,K,E,b.nonce??Ae.data.session?.clientSecret),u&&u.canonicalIdentity===void 0&&(la(M,K,u.idempotencyKey),C??(C=u.idempotencyKey))):(ia(M,K),u=null,C=Re,E=null,Ae=null));let H=Ae?.data.session?.status,me=Ae?.data.session,ne=me?.clientSecret||b?.nonce;if(E&&me?.buyerIdentified===!1&&ne&&(we=Yr(Me,E,ne,x.account)),E&&Ae&&H==="complete"){if(Ja(E))return{sid:E,result:Ae};ia(M,K),E=null,Ae=null,f=!0}}catch{se.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),b?.canonicalIdentity===void 0?(ia(M,K),C=Re):aa(M,K),E=null}if(!E){!Re&&(f||!C)&&(C=(0,Fe.resolveIdempotencyKey)(),U=C),C&&la(M,K,C);let H=se.now(),me=0;se.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let ne={...x,idempotencyKey:C,avsCheck:!!ae,avsConfig:typeof ae=="object"?ae:void 0,checkoutType:"embedded_checkout",checkoutLayout:yi(ke,ue)};Object.defineProperty(ne,Cr.SESSION_CREATE_TELEMETRY,{configurable:!1,enumerable:!1,value:{onAttempt:Xe=>{me=Math.max(me,Xe)}}});let fe=()=>{el(se,"session_create",H,me)},st=Xe=>{tl(se,Xe,"session_create",H,me)&&Le({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_create"})};try{if((0,Fe.isDetachedSessionEligible)(ne)){let Xe=await Me.createDetachedSession(ne);Xe.claimed.catch(()=>{}),Ae=Xe.shell,E=Xe.sessionId,we=Xe.claim;let be=se.now();se.log({name:"session.claim.started",stage:"session_claim",requestCategory:"session_claim"}),it=Xe.claimed.then(Pt=>{let yn=Pt.data.session?.id??Xe.sessionId;return yn&&sa(M,K,yn,Pt.data.session?.clientSecret??Xe.nonce),el(se,"session_claim",be),fe(),Pt},Pt=>{throw aa(M,K),tl(se,Pt,"session_claim",be,0)&&Le({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_claim"}),Pt}).finally(()=>Oo(se)),it.catch(()=>{}),_e=!0,se.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),se.performance({stage:"session_shell",durationMs:se.now()-H,durationMode:"machine",requestCategory:"session_create",attempt:me,statusClass:"2xx",paymentMethodCategory:"card"})}else Ae=await Me.createAndFetchSession(ne),fe()}catch(Xe){throw st(Xe),Xe}E=Ae.data.session?.id??E??"",E&&!it&&sa(M,K,E,Ae.data.session?.clientSecret)}let F=Ae?.data.session;return!we&&E&&F?.buyerIdentified===!1&&F.clientSecret&&(we=Yr(Me,E,F.clientSecret,x.account)),{sid:E??"",result:Ae,sdkGeneratedIdempotencyKey:U,...it?{claimed:it}:{},...we?{claim:we}:{},...Ce?{claimRequiresIdentity:!0}:{}}}finally{_e||Oo(se)}}let mn=(0,P.useRef)(je);Fr(()=>{mn.current=je},[je]);let Tt=(0,P.useCallback)(async(x,M)=>{let K=Fn.current;if(!K)throw new Fe.FloPayError("createSession is required to bootstrap checkout.","validation_error");let se=qa(K,x),Me=ro(se),_e=gs(se),Re=Ca.get(Me);if(!Re){let C={canonicalIdentity:Me,promise:mn.current(se,_e,Me),consumers:0,settled:!1};Re=C,Ca.set(Me,C);let U=()=>{C.settled=!0,Qs(Me,C)};C.promise.then(U,U)}Re.consumers+=1;let b=!1,u=()=>{b||(b=!0,Re.consumers-=1,Qs(Me,Re))};M?.(u);try{let C=await Re.promise;xn.current=Me,x&&(Rn(pn),In(F=>ts(F,x)));let{sid:U,result:f,claimed:E,claim:Ae,claimRequiresIdentity:it}=C;if(bn.current=Ae,en(it===!0),J(f),f.data.session&&Q(f.data.session),U&&Ft(U),E){un.current+=1;let F=un.current;Ct(!0),E.then(H=>{un.current===F&&(J(H),H.data.session&&Q(H.data.session),Ct(!1),en(!1))},H=>{un.current===F&&(Ct(!1),en(!1),hn(H instanceof Fe.FloPayError?H:new Fe.FloPayError(H instanceof Error?H.message:"Failed to create session","api_error")))})}else un.current+=1,Ct(!1),en(!1);let{flopay:we,paypalFlopay:Ce}=await pi(f,{billingApiUrl:L,locale:l,telemetry:o});return En(we,Ce),$t(!1),C}catch(C){throw xn.current===Me&&(xn.current=null),C}finally{M||u()}},[pn,En,l,L,o]),nr=(0,P.useRef)(Tn);nr.current=Tn;let Rr=(0,P.useRef)(Tt);Rr.current=Tt;let mr=(0,P.useCallback)(async x=>{if(!rd(x)||bt)return{sessionId:X,session:B};_(!0);try{let M=await Tt(x);return{sessionId:M.sid,session:M.result.data.session??null}}finally{_(!1)}},[Tt,bt,X,B]),Hn=(0,P.useCallback)(async x=>{let M=bn.current;if(!M)return;let K=un.current,se=await M(x);un.current===K&&(J(se),se.data.session&&Q(se.data.session))},[]);(0,P.useEffect)(()=>{let x=!1,M,K=++Je.current;jn(),hn(null),$e(0);let se=()=>{x=!0,Je.current===K&&(Je.current+=1,jn())},Me=Fn.current;if(sn&&Me)return Qt(vn),$t(!1),xn.current===sn?se:(Q(ns(Me,k)),(async()=>{let b=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),u=vn==="auto"&&!Ve.current&&!b;u&&(Ze(null),at(null),vt("processing"));try{let C=await Rr.current(void 0,Ae=>{M=Ae}),U=C.result.data.session??null;dt.current=Qa(C.result);let f=ui(C.result),E=Ja(C.sid||U?.id);if(!x&&u&&U&&!f&&!E){Ve.current=!0,await Xc(sn,C.sdkGeneratedIdempotencyKey,()=>nr.current(U,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:C.result.autoProcessingError,initialAutoProcessingPending:C.result.autoProcessingPending,autoProcessingAttempted:C.result.autoProcessingAttempted,sessionId:C.sid||U.id}));return}!x&&u&&((f||E)&&(Ve.current=!0),vt(null),at(null))}catch(C){if(x)return;let U=Xo(C);if(u&&U==="session_auto_completed"){Ve.current=!0,vt("success"),await Lo(1200),x||(Qe(()=>{$n.current?.({status:"succeeded"})}),vt(null),at(null));return}u&&(vt(null),at(null));let f=C instanceof Fe.FloPayError?C:new Fe.FloPayError(C instanceof Error?C.message:"Failed to create session","api_error");hn(f)}finally{M?.(),M=void 0}})(),()=>{se(),M?.()});$t(!0);async function _e(){let b=!1,u=null;try{let C=new Cr.PaymentAPI(L,{telemetry:!1}),U=await C.getUnifiedCheckoutSession(mt,t);if(u=U,x)return;J(U);let f=U.data.session??null;if(Q(f),!f)throw new Fe.FloPayError("No session data returned","api_error");let E=f.checkoutMode;if(E==="setup")throw new Fe.FloPayError("This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.","validation_error",{code:"InvalidCardSetupSurface",param:"sessionId"});if(f.status==="authorized"){$t(!1),Qe(()=>{$n.current?.(Ar(f,mt)),ur.current?.(f.successUrl??"")});return}if(f.status==="complete"){$t(!1),Qe(()=>{ur.current?.(f.successUrl??"")});return}if(f.status==="expired")throw Jo(f);b=!0;let Ae=k??E??"full";Qt(Ae),un.current+=1;let it=f.clientSecret||t;bn.current=f.buyerIdentified===!1&&it?Yr(C,mt,it,{...f.customer?.id?{userId:f.customer.id}:{}}):void 0,Ct(!1),en(!1);let we=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),Ce=ui(U);if(Ae==="auto"&&!Ve.current&&!we&&!Ce){Ve.current=!0;let F=Re(U);try{if(await nr.current(f,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>F,sessionId:mt||f.id}),x)return;await F,x||$t(!1);return}catch{if(x)return;await F,x||$t(!1);return}}await Re(U),x||$t(!1)}catch(C){if(x)return;let U=es(C,b);if(b&&Le({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"}),U){let{errorCode:E,stage:Ae,...it}=U;di(L,o,yt,E,Ae,it)}if(U?.stage==="provider_load"&&(k??u?.data.session?.checkoutMode??"full")==="full"&&Qi(u,N,ye)){let E=Qc({billingApiUrl:L,locale:l,telemetry:o});ve.current=E,En(E,null),$e(1),$t(!1);return}let f=C instanceof Fe.FloPayError&&U?.stage!=="provider_load"?C:Zi();f!==C&&Qe(()=>Vn.current?.(f)),hn(f),$t(!1)}}async function Re(b){let{flopay:u,paypalFlopay:C,...U}=await pi(b,{billingApiUrl:L,locale:l,telemetry:o});dt.current={publishableKey:U.publishableKey,paypalPublishableKey:U.paypalPublishableKey},En(u,C),$e(0)}return _e(),se},[k,sn,vn,qt,t,N,ye]);let Wn=(0,P.useCallback)(async()=>{if(!ee||Zt!==1)return;let x=Je.current;$e(2);try{let{flopay:M,paypalFlopay:K}=await pi(ee,{billingApiUrl:L,locale:l,telemetry:o});if(Je.current!==x)return;jn(),En(M,K),$e(0)}catch(M){if(Je.current!==x)return;let{errorCode:K,stage:se,...Me}=Ua(M);di(L,o,yt,K,se,Me)}},[jn,En,l,Zt,L,o,yt,ee]),Mn=(0,P.useCallback)(async()=>{if(!(Dt||!B)){nn(!0),Ze(null);try{await Tn(B,{attempt3DS:!0,fallbackToFull:!0,sessionId:mt||B.id})}finally{nn(!1)}}},[mt,Dt,Tn,B]),Gn=fi(ee),Er=ui(ee),An=(0,P.useMemo)(()=>{if(!(!ee||!B||!ee.data.stripe?.publishableKey))return{billingApiUrl:L}},[ee,B,L]),Yn=!!(n&&!ke&&ue==="buttons"&&oe&&vn==="full"),ln=(0,P.useMemo)(()=>({session:B,loading:Gt,error:kn,checkoutMode:ht,inlineSessionDraft:_t,applyInlineSessionPatch:Yn?mr:void 0,inlineSessionPatchProcessing:bt,claimPending:Et,claimRequiresIdentity:Nt,claimBuyerIdentity:Hn}),[B,Gt,kn,ht,_t,Yn,mr,bt,Et,Nt,Hn]),rt=!!n&&ue==="buttons"&&!Er&&(!$||!An),Cn=Yt?(0,R.jsx)(zn,{status:Yt,errorMessage:dn,authorized:jt}):null;if(Gt){if(c)return(0,R.jsxs)(R.Fragment,{children:[c,Cn]});if(ue==="buttons"){let x=Ie?.buttonsLayout?.cardButton?.borderRadius??Ie?.appearance.variables?.borderRadius??8,M=K=>(0,R.jsx)("div",{style:{height:K,borderRadius:x,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:[N&&M(Lr),ye&&(I||ie)&&M(Lr),ye&&M(Lr),(0,R.jsx)("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),Cn]})}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); } }"})]}),Cn]})}return kn?g?(0,R.jsx)(Zn.Provider,{value:ln,children:g(kn)}):(0,R.jsx)(Zn.Provider,{value:ln,children:(0,R.jsx)("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:kn.message})}):rt?(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(Zn.Provider,{value:ln,children:(0,R.jsx)(ad,{onButtonClick:xe,showPayPal:N,showStripe:ye,showApplePay:I,showGooglePay:ie,theme:re,buttonsTheme:le,buttonsStyles:He,cardButtonContent:ce,cardBackButtonContent:Rt,cardTitleContent:Ge})}),Cn]}):Er&&B&&Gn?(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(Zn.Provider,{value:ln,children:(0,R.jsxs)("div",{className:Ee,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Vt&&(0,R.jsx)(to,{icon:!1,children:Vt}),j==="retrying"&&(0,R.jsx)("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),j==="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:Ir,children:"Retry PayPal"})]}),Et?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; } }"})}):j!=="exhausted"&&(0,R.jsx)("div",{"aria-hidden":j==="retrying"?!0:void 0,style:j==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:(0,R.jsx)(fs,{sessionId:mt,nonce:B.clientSecret||void 0,billingApiUrl:L,email:B.customer?.email||_t?.account?.email,billingName:[B.customer?.firstName,B.customer?.lastName].filter(Boolean).join(" ")||[_t?.account?.firstName,_t?.account?.lastName].filter(Boolean).join(" ")||void 0,onBuyerIdentityReady:Hn,clientId:Gn.clientId,environment:Gn.environment,currency:(B.currency??"usd").toUpperCase(),isSubscription:B.mode==="subscription",providerObjectType:Gn.providerObjectType,onComplete:y,onErrorChange:Ze,onDecline:h,onButtonClick:xe,onInitializationStateChange:Kn,allowAutomaticRetry:an===0,session:B,telemetry:o,telemetryContext:yt,onInstrument:cn,debug:q},`${pe}:paypal-init-${an}`)})]})}),Cn]}):!$||!An?(0,R.jsx)(R.Fragment,{children:Cn}):ht==="confirm"?(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(Zn.Provider,{value:ln,children:(0,R.jsx)(To,{flopay:$,paypalFlopay:te,options:An,onInstrument:cn,children:(0,R.jsxs)("div",{className:Ee,children:[Vt&&(0,R.jsx)("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:Vt}),he?he({onConfirm:Mn,isProcessing:Dt}):(0,R.jsx)("button",{type:"button",onClick:Mn,disabled:Dt,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:Dt?"not-allowed":"pointer",opacity:Dt?.6:1},children:Dt?"Processing...":de??"Confirm Purchase"})]})},pe)}),Cn]}):(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(Zn.Provider,{value:ln,children:(0,R.jsxs)(To,{flopay:$,paypalFlopay:te,options:An,onInstrument:cn,children:[Zt===1&&(0,R.jsx)("button",{type:"button",onClick:Wn,children:"Retry payment methods"}),ke?(0,R.jsxs)(R.Fragment,{children:[Vt&&(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:Vt}),(0,R.jsx)(od,{sessionId:mt,nonce:B?.clientSecret||void 0,billingApiUrl:L,session:B,children:ke})]}):(0,R.jsx)(ha,{sessionId:mt,nonce:B?.clientSecret||void 0,email:B?.customer?.email||_t?.account?.email,userId:B?.customer?.id||_t?.account?.userId,firstName:B?.customer?.firstName||_t?.account?.firstName,lastName:B?.customer?.lastName||_t?.account?.lastName,totalAmount:B?Math.round((0,Fe.buildCheckoutDisplayData)(B).total*100):0,currency:B?.currency?.toLowerCase()??"usd",onComplete:y,onError:m,onDecline:h,error:Vt,onErrorChange:Ze,showPayPal:N,showStripe:ye,enabledPaymentMethods:Zt?[]:W??ee?.data.stripe?.enabledPaymentMethods??B?.gateways?.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:ee?.data.stripe?.enabledPaymentMethodCountries,showApplePay:I,showGooglePay:ie,layout:ue,theme:re,buttonsTheme:le,buttonsStyles:He,appearance:tt,cardButtonContent:ce,cardBackButtonContent:Rt,cardTitleContent:Ge,onButtonClick:xe,onBeforeButtonClick:oe,onBuyerIdentityReady:Hn,enableAVS:ae,...z?{cardFieldOrder:z}:{},...De?{cardPreFormSlot:De}:{},avsLayout:Ne,country:B?.customer?.country,city:B?.customer?.city,state:B?.customer?.state,onCountryChange:w,onZipChange:D,avsCheck:!!ae,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:yi(ke,ue),className:Ee,directPaypal:fi(ee),isSubscription:B?.mode==="subscription",session:B,dataAttachmentPending:Et,dataAttachmentRequiresIdentity:Nt,debug:q})]},pe)}),Cn]})}function od({sessionId:e,nonce:t,billingApiUrl:n,session:r,children:o}){return(0,R.jsx)(R.Fragment,{children:P.default.Children.map(o,a=>{if(!P.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:P.default.cloneElement(a,c)})})}function ad({onButtonClick:e,showPayPal:t,showStripe:n=!0,showApplePay:r,showGooglePay:o,theme:a,buttonsTheme:l,buttonsStyles:c,cardButtonContent:g,cardBackButtonContent:y,cardTitleContent:m}){let[v,h]=(0,P.useState)(!1),w=(0,P.useMemo)(()=>(0,Fe.resolveTheme)(a),[a]),D=(0,P.useMemo)(()=>{let I=w?.buttonsLayout??(0,Fe.resolveButtonsLayoutTheme)(l);return c?{...I,...c,cardButton:{...I.cardButton,...c.cardButton},cardFormContainer:{...I.cardFormContainer,...c.cardFormContainer},backButton:{...I.backButton,...c.backButton},backButtonIcon:{...I.backButtonIcon,...c.backButtonIcon},submitButton:{...I.submitButton,...c.submitButton},title:{...I.title,...c.title}}:I},[w,l,c]),N=w?.buttonsLayout?.cardButton?.borderRadius??w?.appearance.variables?.borderRadius??8,ye=I=>(0,R.jsx)("div",{style:{height:I,borderRadius:N,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),W=g===void 0?{boxSizing:"border-box",height:Lr,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(v){let I=D.cardInputBorder??"#e5e7eb",ie=D.cardInputBackground??"white",q=Hr(y),ue=Hr(m);return(0,R.jsxs)("div",{style:{backgroundColor:D.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",...D.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:()=>h(!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",...D.backButton},children:[(0,R.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...D.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:y})]}),ue?(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,...D.title},children:(0,R.jsx)(Po,{content:m})})]}),(0,R.jsx)("div",{style:{backgroundColor:ie,border:`1px solid ${I}`,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:ie,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${I}`,borderLeft:`1px solid ${I}`,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:ie,borderTop:"none",borderRight:`1px solid ${I}`,borderBottom:`1px solid ${I}`,borderLeft:`1px solid ${I}`,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:ie,border:`1px solid ${I}`,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",...D.submitButton,opacity:.5}}),(0,R.jsx)("style",{children:`
38
+ `}),Co&&sr&&(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:tt?-2:0},children:[(0,d.jsxs)("button",{type:"button",onClick:Vr,style:{display:"inline-flex",alignItems:"center",gap:$a?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:k.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...k.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",...k.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)(Qr,{content:Se})]}),Wi?(0,d.jsx)("div",{style:{flex:1}}):(0,d.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:k.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...k.title},children:(0,d.jsx)(Ro,{content:Re})})]}),!Co&&!Wi&&(0,d.jsx)("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:ja,order:tt?-3:0,...k.title},children:(0,d.jsx)(Ro,{content:Re})}),tt&&Le&&(0,d.jsx)("div",{style:{order:-2,width:"100%"},children:Le}),tt&&At&&(0,d.jsxs)("div",{"data-testid":"flopay-vault-identity-fields",style:{order:-1,marginTop:"0.5rem"},children:[(0,d.jsx)("div",{style:{backgroundColor:Gr,border:`1px solid ${Wn(Xo)}`,borderRadius:Kt,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:wt,onChange:i=>{bt("email"),Cn.current=i.target.value,Qn(i.target.value)},onPointerDown:()=>bt("email"),onKeyDown:()=>bt("email"),onBlur:()=>{Nn("email")&&Mr(!0),vt||Ma()},disabled:v,required:!0,"aria-invalid":Xo||void 0,"aria-describedby":Xo?"flopay-buyer-email-error":void 0,"data-testid":"flopay-email",style:{width:"100%",border:"none",outline:"none",background:"transparent",...Va}})}),Xo&&(0,d.jsx)("div",{id:"flopay-buyer-email-error",role:"alert","data-testid":"flopay-email-error",style:wo,children:In.empty?"Email address is required":"Enter a valid email address"})]}),E&&(0,d.jsx)("div",{style:{order:tt?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let i=Wt,S=(Y=!1)=>({backgroundColor:Gr,border:`1px solid ${Wn(Y)}`,borderRadius:Kt,marginTop:"0.5rem",padding:"10px"}),V=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...Va}),Fe=(0,u.getStateOptions)(i);return(0,d.jsxs)(d.Fragment,{children:[(0,u.isAVSFieldVisible)(E.address_line_1,i)&&(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("div",{style:S(Lt("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:Y=>{bt("line1"),ut.current.addressLine1=!0,dt.current=Y.target.value,bn(Y.target.value)},onPointerDown:()=>bt("line1"),onKeyDown:()=>bt("line1"),onBlur:()=>mn("line1"),disabled:v,required:!0,"aria-invalid":Lt("line1")||void 0,"aria-describedby":Lt("line1")?"flopay-billing-address-line1-error":void 0,"data-testid":"flopay-address-line1",style:V()})}),Lt("line1")&&(0,d.jsx)("div",{id:"flopay-billing-address-line1-error",role:"alert","data-testid":"flopay-address-line1-error",style:wo,children:"Street address is required"})]}),(0,u.isAVSFieldVisible)(E.address_line_2,i)&&(0,d.jsx)("div",{style:S(),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:$e,onChange:Y=>{ut.current.addressLine2=!0,Tt.current=Y.target.value,ct(Y.target.value)},disabled:v,"data-testid":"flopay-address-line2",style:V()})}),((0,u.isAVSFieldVisible)(E.city,i)||(0,u.isAVSFieldVisible)(E.state,i))&&(0,d.jsxs)("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[(0,u.isAVSFieldVisible)(E.city,i)&&(0,d.jsx)("div",{style:{flex:1,backgroundColor:Gr,borderTop:`1px solid ${Wn(Lt("city"))}`,borderRight:`1px solid ${Wn(Lt("city"))}`,borderBottom:`1px solid ${Wn(Lt("city"))}`,borderLeft:`1px solid ${Wn(Lt("city"))}`,padding:"10px",borderTopLeftRadius:Kt,borderBottomLeftRadius:Kt,...(0,u.isAVSFieldVisible)(E.state,i)?{borderRight:"none",borderTopRightRadius:0,borderBottomRightRadius:0}:{borderRadius:Kt}},children:(0,d.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-city",name:"billing-city",placeholder:"City",autoComplete:"billing address-level2",value:un,onChange:Y=>{bt("city"),ut.current.city=!0,Pn.current=Y.target.value,Gt(Y.target.value)},onPointerDown:()=>bt("city"),onKeyDown:()=>bt("city"),onBlur:()=>mn("city"),disabled:v,required:!0,"aria-invalid":Lt("city")||void 0,"aria-describedby":Lt("city")?"flopay-billing-city-error":void 0,"data-testid":"flopay-city",style:V()})}),(0,u.isAVSFieldVisible)(E.state,i)&&(0,d.jsx)("div",{style:{flex:1,backgroundColor:Gr,borderTop:`1px solid ${Wn(Lt("state"))}`,borderRight:`1px solid ${Wn(Lt("state"))}`,borderBottom:`1px solid ${Wn(Lt("state"))}`,borderLeft:`1px solid ${Wn(Lt("state"))}`,padding:"10px",borderTopRightRadius:Kt,borderBottomRightRadius:Kt,...(0,u.isAVSFieldVisible)(E.city,i)?{borderTopLeftRadius:0,borderBottomLeftRadius:0,borderLeft:`1px solid ${Wn(Lt("state")||Lt("city"))}`}:{borderRadius:Kt}},children:Fe?(0,d.jsxs)("select",{id:"flopay-billing-state",name:"billing-state",value:pn,onChange:Y=>{bt("state"),ut.current.state=!0,Jt.current=Y.target.value,$t(Y.target.value)},onPointerDown:()=>bt("state"),onKeyDown:()=>bt("state"),onBlur:()=>mn("state"),disabled:v,autoComplete:"billing address-level1",required:!0,"aria-invalid":Lt("state")||void 0,"aria-describedby":Lt("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:{...V(),cursor:"pointer"},children:[(0,d.jsx)("option",{value:"",children:(0,u.getStateLabel)(i)}),Fe.map(Y=>(0,d.jsx)("option",{value:Y.code,children:Y.name},Y.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:pn,onChange:Y=>{bt("state"),ut.current.state=!0,Jt.current=Y.target.value,$t(Y.target.value)},onPointerDown:()=>bt("state"),onKeyDown:()=>bt("state"),onBlur:()=>mn("state"),disabled:v,required:!0,"aria-invalid":Lt("state")||void 0,"aria-describedby":Lt("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:V()})})]}),Lt("city")&&(0,d.jsx)("div",{id:"flopay-billing-city-error",role:"alert","data-testid":"flopay-city-error",style:wo,children:"City is required"}),Lt("state")&&(0,d.jsxs)("div",{id:"flopay-billing-state-error",role:"alert","data-testid":"flopay-state-error",style:wo,children:[(0,u.getStateLabel)(i)," is required"]}),((0,u.isAVSFieldVisible)(E.country,i)||(0,u.isAVSFieldVisible)(E.postal_code,i))&&(0,d.jsxs)("div",{style:{display:"flex",flexDirection:_e==="column"?"column":"row",gap:_e==="column"?"0.5rem":"0",marginTop:"0.5rem"},children:[(0,u.isAVSFieldVisible)(E.country,i)&&(0,d.jsx)("div",{style:{flex:_e==="row"?1:void 0,backgroundColor:Gr,borderTop:`1px solid ${So}`,borderRight:`1px solid ${So}`,borderBottom:`1px solid ${So}`,borderLeft:`1px solid ${So}`,padding:"10px",..._e==="row"&&(0,u.isAVSFieldVisible)(E.postal_code,i)?{borderRadius:"0",borderTopLeftRadius:Kt,borderBottomLeftRadius:Kt,borderRight:"none"}:{borderRadius:Kt}},children:(0,d.jsx)("select",{id:"flopay-billing-country",name:"billing-country",value:Wt,onChange:Y=>{ut.current.country=!0,Yt.current=Y.target.value,dn(Y.target.value),Ke?.(Y.target.value),Jt.current="",$t("")},disabled:v,autoComplete:"billing country","data-testid":"flopay-country",style:{...V(),cursor:"pointer"},children:u.COUNTRY_OPTIONS.map(Y=>(0,d.jsxs)("option",{value:Y.code,children:[Y.flag," ",Y.name]},Y.code))})}),(0,u.isAVSFieldVisible)(E.postal_code,i)&&(0,d.jsx)("div",{style:{flex:_e==="row"?1:void 0,backgroundColor:Gr,border:`1px solid ${Rl}`,padding:"10px",..._e==="row"&&(0,u.isAVSFieldVisible)(E.country,i)?{borderRadius:"0",borderTopRightRadius:Kt,borderBottomRightRadius:Kt}:{borderRadius:Kt}},children:(0,d.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-postal-code",name:"billing-postal-code",placeholder:(0,u.getPostalCodeLabel)(Wt),autoComplete:"billing postal-code",value:rn,onChange:Y=>{bt("zip"),ut.current.zip=!0,ht.current=Y.target.value,ke(Y.target.value),_t?.(Y.target.value)},onPointerDown:()=>bt("zip"),onKeyDown:()=>bt("zip"),onBlur:()=>{Nn("zip")&&hr(!0)},disabled:v,required:L.required,"aria-invalid":Zo||void 0,"aria-describedby":Zo?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:V()})})]}),Zo&&(0,d.jsx)("div",{id:"flopay-billing-postal-code-error",role:"alert","data-testid":"flopay-zip-error",style:wo,children:L.empty?`${(0,u.getPostalCodeLabel)(i)} is required`:Zc(i)})]})})()}),tt&&Al,M&&(0,d.jsx)(io,{margin:"0.75rem 0",styleOverride:k.errorBanner,children:M})]}),Qo={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"},Zi=i=>D?!de||!pr?(0,d.jsx)("pre",{"data-testid":i,style:Qo,children:"FloPay/DirectPayPal-debug - not enabled"}):(0,d.jsx)("pre",{"data-testid":i,style:Qo,children:["FloPay/DirectPayPal-debug (parent gate)",` showPayPal=${de}`,` directPaypalConfigured=${pr}`,` inAppBrowserDetected=${String(Go)}`,` shouldRenderDirectPayPal=${ho}`,` shouldRenderStripePayPal=${bo}`,` hasPaypalStripeInstance=${!!an}`].join(`
39
+ `)}):null,Qi=i=>D?!K||!Dt?(0,d.jsx)("pre",{"data-testid":i,style:Qo,children:"FloPay/Stripe-debug - not enabled"}):(0,d.jsx)("pre",{"data-testid":i,style:Qo,children:["FloPay/Stripe-debug (parent gate)",` showStripe=${K}`,` currency=${ze}`,` amountInCents=${Ee}`,` enabledPaymentMethods: ${JSON.stringify(I??[])}`,` enabledPaymentMethodsProvided=${fo}`,` hasEnabledMethods=${Ko}`,` expressMethods: ${JSON.stringify(Ho)}`,` walletExpressMethods: ${JSON.stringify(Hr)}`,` paymentElementMethods: ${JSON.stringify(go)}`,` paymentElementMethodsForCurrency: ${JSON.stringify(Wo)}`,` hasStripeInstance=${!!Dt}`,` shouldRenderWallets=${Wr}`,` shouldRenderPaymentElement=${vo}`].join(`
40
+ `)}):null,es=Ue==="apm-expanding"||Ue==="apm-form"||Ue==="apm-collapsing",Jr;Ue==="apm-expanding"?Jr=Us:Ue==="apm-collapsing"&&(Jr=qs);let ea=Ft?el(Da,Ft):null;if(se==="buttons"){let i=Ue==="buttons"||Ue==="expanding"||Ue==="apm-expanding",S=Ue==="expanding"||Ue==="card"||Ue==="collapsing",V=st===void 0?{boxSizing:"border-box",height:Sa,padding:"0 1rem"}:{padding:"0.9rem 1rem"},Fe;Ue==="expanding"||Ue==="apm-expanding"?Fe=Hc:(Ue==="collapsing"||Ue==="apm-collapsing")&&(Fe=Kc);let Y;return Ue==="expanding"?Y=Us:Ue==="collapsing"&&(Y=qs),(0,d.jsxs)("form",{onSubmit:za,className:h,noValidate:!0,style:{position:"relative"},children:[(0,d.jsx)(mi,{}),gn&&(0,d.jsx)(Xn,{status:gn,errorMessage:M,authorized:ot}),(0,d.jsxs)("div",{style:{display:"grid"},children:[(0,d.jsxs)("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!i&&!Fe?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!i&&!Fe?Gc:{},...Fe?{animation:Fe,pointerEvents:"none"}:{}},children:[Zi("flopay-direct-paypal-gate-debug"),Qi("flopay-stripe-gate-debug"),ho&&be&&(0,d.jsxs)(d.Fragment,{children:[U&&(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)(Mo,{sessionId:e,nonce:t,billingApiUrl:Ie,email:g.email,billingName:ae||void 0,onBuyerIdentityReady:W,clientId:be.clientId,environment:be.environment,currency:ze.toUpperCase(),isSubscription:Xe,providerObjectType:P,approvalPresentation:Yo==="popup"?void 0:Yo,onTokenizedBody:Bn,onComplete:a,onErrorChange:Q,onDecline:c,onTechnicalFailure:Kr,onButtonClick:te,runBeforeButtonClick:nr,isProcessing:v,onLoadStateChange:La,onInitializationStateChange:Na,session:St,existingOrderId:U?.orderId,debug:D},U?.orderId??"fresh")]}),bo&&(0,d.jsx)(Ht.Elements,{stripe:an,options:Ge,children:(0,d.jsx)(Ks,{sessionId:e,nonce:t,email:g.email,billingName:ae||void 0,onBuyerIdentityReady:W,billingApiUrl:Ie,onTokenizedBody:Bn,onErrorChange:Q,isProcessing:v,onButtonClick:te,onDecline:c,onTechnicalFailure:Kr,runBeforeButtonClick:nr,onLoadStateChange:Ai,placeholderBorderRadius:Fr})}),Wr?(0,d.jsx)(Ht.Elements,{stripe:Dt,options:Rn,children:(0,d.jsx)(Hs,{sessionId:e,nonce:t,email:g.email,billingName:ae||void 0,onBuyerIdentityReady:W,billingApiUrl:Ie,intentKind:$>0?"payment":"setup",expressMethods:Hr,onTokenizedBody:Bn,onErrorChange:Q,onButtonClick:te,onDecline:c,onTechnicalFailure:Kr,runBeforeButtonClick:nr,onLoadStateChange:Bi,placeholderBorderRadius:Fr})}):null,!Wr&&Oi?(0,d.jsx)("div",{style:{height:Sa,borderRadius:Fr,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,vo&&(0,d.jsx)(Ws,{sessionId:e,nonce:t,email:g.email,billingName:[g.firstName,g.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:W,billingApiUrl:Ie,paymentElementMethods:Wo,stripeInstance:Dt,paymentElementBaseOptions:Da,onTokenizedBody:Bn,onErrorChange:Q,onButtonClick:te,onDecline:c,runBeforeButtonClick:nr,onLoadStateChange:Di,isProcessing:v,submitButtonColor:Dr,submitButtonBorderRadius:Kt,submitButtonStyle:k.submitButton,onExpandApm:Hn,expandedApmMethod:Ft,themeId:ee,buttonAppearance:{backgroundColor:k.cardButton?.backgroundColor,borderColor:k.cardInputBorder,textColor:k.cardButton?.color,borderRadius:Fr}}),tt&&(0,d.jsx)("button",{type:"button",onClick:async()=>{v||!(await nr("card")).proceed||(te?.("card"),lr())},disabled:v,style:{width:"100%",...V,...k.cardButton,...hi({themeBundle:ge,resolvedPrimaryColor:Dr,resolvedBorderRadius:Kt,submitButtonStyle:k.submitButton,explicitPrimaryColor:Fn?.colorPrimary}),fontSize:k.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:v?"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:v?.6:1},onMouseEnter:Pe=>{!v&&(ge||Fn?.colorPrimary)&&(Pe.currentTarget.style.backgroundColor=Tl)},onMouseLeave:Pe=>{(ge||Fn?.colorPrimary)&&(Pe.currentTarget.style.backgroundColor=Dr)},onMouseDown:Pe=>{Pe.currentTarget.style.transform="scale(0.985)"},onMouseUp:Pe=>{Pe.currentTarget.style.transform="scale(1)"},children:(0,d.jsx)(Zr,{content:st})}),M&&Ue==="buttons"&&(0,d.jsx)(io,{margin:"0.25rem 0",styleOverride:k.errorBanner,children:M})]}),tt&&S&&(0,d.jsx)("div",{style:{gridArea:"1 / 1",...Y?{animation:Y}:{},...Ue==="collapsing"?{pointerEvents:"none"}:{}},children:Xi}),K&&es&&Ft&&ea&&Dt&&(0,d.jsx)("div",{style:{gridArea:"1 / 1",...Jr?{animation:Jr}:{},...Ue==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,d.jsxs)("div",{style:{backgroundColor:qa,borderRadius:Ha,...ko,padding:Ka},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:cr,style:{display:"inline-flex",alignItems:"center",gap:$a?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:k.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...k.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",...k.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)(Qr,{content:Se})]}),(0,d.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:k.titleFontSize??"1.05rem",color:ja,paddingRight:80,...k.title},children:`Pay with ${(0,u.getStripeMethodDisplayName)(Ft)}`})]}),(0,d.jsx)(Ht.Elements,{stripe:Dt,options:ea,children:(0,d.jsx)(fi,{method:Ft,sessionId:e,nonce:t,email:g.email,billingName:[g.firstName,g.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:W,billingApiUrl:Ie,onTokenizedBody:Bn,onErrorChange:Q,onDecline:c,onCancel:cr,runBeforeButtonClick:nr,onButtonClick:te,isProcessing:v,submitButtonColor:Dr,submitButtonBorderRadius:Kt,submitButtonStyle:k.submitButton,errorText:M})},Ft)]})})]})]})}return es&&Ft&&ea&&Dt&&K?(0,d.jsxs)("form",{onSubmit:za,className:h,noValidate:!0,style:{position:"relative"},children:[(0,d.jsx)(mi,{}),gn&&(0,d.jsx)(Xn,{status:gn,errorMessage:M,authorized:ot}),(0,d.jsx)("div",{style:{...Jr?{animation:Jr}:{},...Ue==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,d.jsxs)("div",{style:{backgroundColor:qa,borderRadius:Ha,...ko,padding:Ka},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:cr,style:{display:"inline-flex",alignItems:"center",gap:$a?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:k.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...k.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",...k.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)(Qr,{content:Se})]}),(0,d.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:k.titleFontSize??"1.05rem",color:ja,paddingRight:80,...k.title},children:`Pay with ${(0,u.getStripeMethodDisplayName)(Ft)}`})]}),(0,d.jsx)(Ht.Elements,{stripe:Dt,options:ea,children:(0,d.jsx)(fi,{method:Ft,sessionId:e,nonce:t,email:g.email,billingName:[g.firstName,g.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:W,billingApiUrl:Ie,onTokenizedBody:Bn,onErrorChange:Q,onDecline:c,onCancel:cr,runBeforeButtonClick:nr,onButtonClick:te,isProcessing:v,submitButtonColor:Dr,submitButtonBorderRadius:Kt,submitButtonStyle:k.submitButton,errorText:M})},Ft)]})})]}):(0,d.jsxs)("form",{onSubmit:za,className:h,noValidate:!0,style:{position:"relative"},children:[(0,d.jsx)(mi,{}),gn&&(0,d.jsx)(Xn,{status:gn,errorMessage:M,authorized:ot}),(0,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Zi("flopay-direct-paypal-gate-debug-default"),Qi("flopay-stripe-gate-debug-default"),ho&&be&&(0,d.jsxs)(d.Fragment,{children:[U&&(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)(Mo,{sessionId:e,nonce:t,billingApiUrl:Ie,email:g.email,billingName:ae||void 0,onBuyerIdentityReady:W,clientId:be.clientId,environment:be.environment,currency:ze.toUpperCase(),isSubscription:Xe,providerObjectType:P,approvalPresentation:Yo==="popup"?void 0:Yo,onTokenizedBody:Bn,onComplete:a,onErrorChange:Q,onDecline:c,onTechnicalFailure:Kr,onButtonClick:te,runBeforeButtonClick:nr,isProcessing:v,onLoadStateChange:La,onInitializationStateChange:Na,session:St,existingOrderId:U?.orderId,debug:D},U?.orderId??"fresh")]}),bo&&(0,d.jsx)(Ht.Elements,{stripe:an,options:Ge,children:(0,d.jsx)(Ks,{sessionId:e,nonce:t,email:g.email,billingName:ae||void 0,onBuyerIdentityReady:W,billingApiUrl:Ie,onTokenizedBody:Bn,onErrorChange:Q,isProcessing:v,onButtonClick:te,onDecline:c,onTechnicalFailure:Kr,runBeforeButtonClick:nr,onLoadStateChange:Ai,placeholderBorderRadius:Fr})}),Wr&&(0,d.jsx)(Ht.Elements,{stripe:Dt,options:Rn,children:(0,d.jsx)(Hs,{sessionId:e,nonce:t,email:g.email,billingName:ae||void 0,onBuyerIdentityReady:W,billingApiUrl:Ie,intentKind:$>0?"payment":"setup",expressMethods:Hr,onTokenizedBody:Bn,onErrorChange:Q,onButtonClick:te,onDecline:c,onTechnicalFailure:Kr,runBeforeButtonClick:nr,onLoadStateChange:Bi,placeholderBorderRadius:Fr})}),vo&&(0,d.jsx)(Ws,{sessionId:e,nonce:t,email:g.email,billingName:[g.firstName,g.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:Ie,paymentElementMethods:Wo,stripeInstance:Dt,paymentElementBaseOptions:Da,onTokenizedBody:Bn,onErrorChange:Q,onButtonClick:te,onDecline:c,runBeforeButtonClick:nr,onLoadStateChange:Di,isProcessing:v,submitButtonColor:Dr,submitButtonBorderRadius:Kt,submitButtonStyle:k.submitButton,themeId:ee,onExpandApm:Hn,expandedApmMethod:Ft,buttonAppearance:{backgroundColor:k.cardButton?.backgroundColor,borderColor:k.cardInputBorder,textColor:k.cardButton?.color,borderRadius:Fr}})]}),tt&&(Sl||Cl||wl)&&(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"}})]}),tt&&Xi]})}var R=require("react/jsx-runtime"),jr=44,ki="flopay_checkout_saved_payment_resume",Ea=new Map,Ra=new Map;function tl(e,t){t.settled&&t.consumers===0&&Ea.get(e)===t&&Ea.delete(e)}function od(e,t,n){let r=Ra.get(e);if(r&&(!r.sdkGeneratedIdempotencyKey||!t||r.sdkGeneratedIdempotencyKey===t))return r.attempt;let o=n(),a={attempt:o,sdkGeneratedIdempotencyKey:t};Ra.set(e,a);let l=()=>{Ra.get(e)===a&&Ra.delete(e)};return o.then(l,l),o}function $o(e){return new Promise(t=>setTimeout(t,e))}function _a(e,t,n){let r=ca({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:De.SDK_VERSION,enabled:t!==!1});return r.beginCheckout(n),r}function jo(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function bi(e,t,n,r,o,a){let l=_a(e,t,n);l.error({errorCode:r,stage:o,paymentMethodCategory:"unknown",...a,...o==="session_read"?{requestCategory:"session_read"}:{}}),jo(l)}function nl(e,t,n,r){e.log({name:t==="session_claim"?"session.claim.completed":"session.request.completed",stage:t,requestCategory:t,statusClass:"2xx"}),e.performance({stage:t,durationMs:Math.max(0,e.now()-n),durationMode:"machine",requestCategory:t,...r===void 0?{}:{attempt:r},statusClass:"2xx"})}function rl(e,t,n,r,o){let a=(0,De.classifyTelemetryFailure)(t,"CHECKOUT_SESSION_CREATE_FAILED","unknown");return e.performance({stage:n,durationMs:Math.max(0,e.now()-r),durationMode:"machine",requestCategory:n,attempt:o,statusClass:a.statusClass}),t instanceof De.FloPayError&&t.code==="session_auto_completed"?!1:t instanceof De.FloPayError&&t.type==="validation_error"?(e.terminal({outcome:"validation_rejected",stage:n,paymentMethodCategory:"unknown"}),!1):a.statusClass==="4xx"?(e.terminal({outcome:"validation_rejected",stage:n,paymentMethodCategory:"unknown",requestCategory:n,statusClass:"4xx"}),!1):(e.error({...a,stage:n,paymentMethodCategory:"unknown",requestCategory:n}),!0)}function wi(e){let t=e?.data.paypal?.publishableKey;if(t)return{clientId:t,environment:e?.data.paypal?.environment,providerObjectType:e?.data.paypal?.providerObjectType,approvalPresentation:e?.data.paypal?.approvalPresentation}}function vi(e){return!e||e.data.stripe?.publishableKey?!1:!!wi(e)?.clientId}var ad={name:"provider_unavailable",initialize:()=>Promise.resolve(),getRawProvider:()=>null,destroy:()=>{}};function id(e){return new Rr.FloPay(ad,{publishableKey:"provider_unavailable",...e})}async function Pi(e,t){let{publishableKey:n,paypalPublishableKey:r}=si(e);return{...await li({publishableKey:n,paypalPublishableKey:r,...t}),publishableKey:n,paypalPublishableKey:r}}function Ii(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function sd(){if(!Ii())return null;try{let e=window.sessionStorage.getItem(ki);return e?JSON.parse(e):null}catch{return null}}function ol(e){if(Ii())try{window.sessionStorage.setItem(ki,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function Ci(){if(Ii())try{window.sessionStorage.removeItem(ki)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}function ld(){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 al(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 Si(e,t){return e?"custom_layout":t==="buttons"?"buttons_layout":"default_layout"}function cd(e,t){return e?"unknown":t==="buttons"?"buttons":"embedded"}function il(e){return e?.gateways?.stripe?"stripe":e?.gateways?.paypal?"paypal":void 0}function dd(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 Ta({sessionId:e,nonce:t,createSession:n,billingApiUrl:r,telemetry:o,appearance:a,locale:l,loading:c,error:f,onComplete:y,onError:p,onInstrument:b,onDecline:h,onCountryChange:w,onZipChange:B,showPayPal:N=!0,showStripe:de=!0,enabledPaymentMethods:K,showApplePay:I=!0,showGooglePay:re=!0,debug:q=!1,layout:ie,theme:se,buttonsTheme:ee,buttonsStyles:Oe,cardButtonContent:ue,cardBackButtonContent:Ct,cardTitleContent:st,showSecurityFooter:Se,onButtonClick:Re,onBeforeButtonClick:he,enableAVS:te,cardFieldOrder:Te,cardPreFormSlot:fe,avsLayout:we,className:xe,initialErrorMessage:Le=null,children:_e,checkoutMode:_,confirmLabel:oe,renderConfirmButton:me,onSessionCompleted:J}){let O=(0,De.resolveBillingApiUrl)(r),Ce=(0,C.useMemo)(()=>(0,De.resolveTheme)(se),[se]),Ke=a??Ce?.appearance,_t=n?"embedded_checkout":"standard_checkout",Qe=Si(_e,ie),[Z,X]=(0,C.useState)(null),[$,ze]=(0,C.useState)(null),Je=(0,C.useRef)(null),be=(0,C.useRef)(null),Xe=(0,C.useRef)(0),[H,z]=(0,C.useState)(null),rt=(0,C.useRef)(null),[D,j]=(0,C.useState)(null),qe=(0,C.useMemo)(()=>n?lo(n):"",[n]),ve=n?`create:${qe}`:`session:${e??""}`,Bt=il(D),St=(0,C.useRef)(new Set),P=(0,C.useRef)(ve),F=(0,C.useRef)(ve);Ur(()=>{F.current=ve,P.current!==ve&&(P.current=ve,St.current.clear())},[ve]);let qt=(0,C.useCallback)(A=>{if(F.current===ve){if(Za.has(A.name)){if(St.current.has(A.name))return;St.current.add(A.name)}nt(()=>b?.(A))}},[ve,b]),Ae=ao(qt,ve),Et=(0,C.useRef)(!1),tn=(0,C.useCallback)(A=>{if(Et.current)return;let x=A.gateway||!Bt?A:{...A,gateway:Bt};qt(x)},[qt,Bt]);(0,C.useEffect)(()=>{Ae({class:"lifecycle",name:"checkout.mount"})},[Ae]);let[et,nn]=(0,C.useState)(e??""),lt=e??et,Wt=n?"":lt,[dn,rn]=(0,C.useState)(!0),[ke,hn]=(0,C.useState)(null),[bn,$e]=(0,C.useState)(0),[ct,un]=(0,C.useState)("full"),[Gt,pn]=(0,C.useState)(!1),[$t,wt]=(0,C.useState)(Le),[Qn,kt]=(0,C.useState)(null),[vn,ht]=(0,C.useState)(null),[Yt,dt]=(0,C.useState)(!1),[Tt,Pn]=(0,C.useState)(void 0),[Jt,Cn]=(0,C.useState)(""),[ut,E]=(0,C.useState)(!1),[xt,ot]=(0,C.useState)(!1),[Xt,on]=(0,C.useState)(!1),Ln=(0,C.useRef)(0),Tn=(0,C.useRef)(void 0),[Zt,tt]=(0,C.useState)("loading"),[Tr,xr]=(0,C.useState)(0),Un=(0,C.useRef)(!1),Ar=(0,C.useRef)(!1),qn=(0,C.useRef)(!1),pt=(0,C.useRef)(null),L=(0,C.useMemo)(()=>({checkoutMode:_??ct,layout:cd(_e,ie)}),[_,_e,ct,ie]),mt=(0,C.useRef)(y);mt.current=y;let pe=(0,C.useRef)(p);pe.current=p;let xn=(0,C.useRef)(h);xn.current=h;let Sn=(0,C.useCallback)((A,x)=>{Je.current=A,ze(A),rt.current=x,z(x)},[]),wn=(0,C.useCallback)(()=>{let A=be.current;A&&(be.current=null,A.destroy())},[]);(0,C.useEffect)(()=>{sn($)?.setCheckoutContext(L),H&&H!==$&&sn(H)?.setCheckoutContext(L)},[$,H,L]);let hr=(0,C.useRef)(J);hr.current=J;let at=(0,C.useCallback)(A=>{tt(A),!(A!=="exhausted"||qn.current)&&(qn.current=!0,pe.current?.(new De.FloPayError("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),Mr=(0,C.useCallback)(()=>{tt("retrying"),xr(A=>A+1)},[]);(0,C.useEffect)(()=>{tt("loading"),xr(0),qn.current=!1},[lt]),(0,C.useEffect)(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:De.SDK_VERSION,checkout_type:_t,checkout_layout:Qe,billing_api_url:O})},[Qe,_t,O]);let er=(0,C.useMemo)(()=>n?lo(n,!0):"",[n]),Br=(0,C.useMemo)(()=>Jt===er?Tt:void 0,[Tt,Jt,er]),$n=(0,C.useMemo)(()=>n?Ga(n,Br):void 0,[n,Br]),jn=_??$n?.checkoutMode??"full",jt=(0,C.useMemo)(()=>$n?{...$n,checkoutMode:jn}:void 0,[$n,jn]);(0,C.useEffect)(()=>{Pn(void 0),Cn(er),Tn.current=void 0,on(!1)},[er]),(0,C.useEffect)(()=>{wt(Le)},[Le]);let bt=(0,C.useCallback)((A,x,U)=>{nt(()=>{xn.current?.(cn(A,x,U))})},[]),Nn=(0,C.useCallback)(async(A,x)=>{wt(null),ht(null),dt(!1),kt("processing");let U=x?.sessionId??A.id,ne=il(A),He=Je.current??rt.current,Ie=sn(He),ye=He?null:_a(O,o,L),le={log:m=>{Ie?Ie.log(m):ye?.log(m)},error:m=>{Ie?Ie.error(m):ye?.error(m)},terminal:m=>{Ie?Ie.terminal(m):ye?.terminal(m)},performance:m=>{Ie?Ie.performance(m):ye?.performance(m)},now:()=>Ie?.now()??ye?.now()??0,elapsed:m=>Ie?.elapsed(m)??Math.max(0,(ye?.now()??m)-m)},W=le.now(),M=!!(x?.initialAutoProcessingError||x?.initialAutoProcessingPending),ge=!1,k,G=()=>{ge||(ge=!0,M=!0,k=le.now(),le.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),le.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},Ze=!1,Vt=()=>{Ze||(Ze=!0,le.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),le.performance({stage:"processing",durationMs:le.elapsed(W),durationMode:"machine",paymentMethodCategory:"saved"}),k!==void 0&&le.performance({stage:"recovery",durationMs:le.elapsed(k),durationMode:"machine",paymentMethodCategory:"saved"}))};le.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),Et.current=!0;try{le.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"})}finally{Et.current=!1}Ae({class:"lifecycle",name:"payment.processing.started",provider:ne}),M&&G();let v;try{let m=ks(x?.initialAutoProcessingError),g;if(m)G(),m.type==="paypal_redirect_required"&&pt.current?.publishableKey&&ol({sessionId:U,publishableKey:pt.current.publishableKey,paypalPublishableKey:pt.current.paypalPublishableKey}),g=await va(m,{flopay:Je.current,paypalFlopay:rt.current,attempt3DS:x?.attempt3DS,billingApiUrl:O,sessionId:U,session:A,telemetry:!1}),m.type==="paypal_redirect_required"&&Ci();else if(x?.initialAutoProcessingPending){let ce=(await new Rr.PaymentAPI(O,{telemetry:!1}).waitForCheckoutSessionCompletion(x.initialAutoProcessingPending.sessionId,{initialDelayMs:x.initialAutoProcessingPending.retryAfterMs})).data.session;if(!to(ce))throw oa(ce);g=Or(ce,U)}else{if(x?.initialAutoProcessingError)throw Er(x.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:x.initialAutoProcessingError.checkoutMethod});if(x?.fromCreateSession)return x?.fallbackToFull&&(un("full"),al("full")),!1;{let ae=await po({billingApiUrl:O,sessionId:U,session:A,telemetry:!1});ae.type==="success"?g=ae.result:(G(),ae.type==="paypal_redirect_required"&&pt.current?.publishableKey&&ol({sessionId:U,publishableKey:pt.current.publishableKey,paypalPublishableKey:pt.current.paypalPublishableKey}),g=await va(ae,{flopay:Je.current,paypalFlopay:rt.current,attempt3DS:x?.attempt3DS,billingApiUrl:O,sessionId:U,session:A,telemetry:!1}),ae.type==="paypal_redirect_required"&&Ci())}}U&&co(U),Vt(),M&&(le.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),le.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),le.terminal({outcome:g.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),dt(g.status==="authorized"),kt("success"),await $o(1200),v=()=>mt.current?.(g)}catch(m){let g=No(m),ae=g.checkoutMethod??Lo;wt(g.message),ht(g.message),dt(!1),x?.fallbackToFull&&(le.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),un("full"),al("full")),Vt();let Me=g.statusCode===void 0?void 0:(0,De.telemetryStatusClass)(g.statusCode,"unknown"),ce=Me==="4xx"?{requestCategory:"process_payment",statusClass:Me}:{},At=Me===void 0||Me==="4xx";if(At&&(g.telemetryOutcome==="payment_declined"||!!(g.declineCode||g.code?.toLowerCase().includes("declin"))))le.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...ce});else if(At&&(g.telemetryOutcome==="validation_rejected"||g.type==="validation_error"))le.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...ce});else{let Dt=(0,De.classifyTelemetryFailure)(m,M?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown"),an=g.telemetryRequestCategory??"process_payment";Et.current=!0;try{le.error({...Dt,...g.telemetryFailureCategory?{failureCategory:g.telemetryFailureCategory}:{},stage:M?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:an})}finally{Et.current=!1}Ae({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:an,provider:ne})}return nt(()=>pe.current?.(g)),bt(ae,g,{code:g.code,declineCode:g.declineCode}),kt("error"),await Promise.allSettled([$o(1500),x?.ensureProvidersReady?x.ensureProvidersReady():Promise.resolve()]),M&&(le.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),le.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{Vt(),ye&&jo(ye),kt(null),ht(null)}return nt(v),!0},[bt,Ae,O,o,L]);(0,C.useEffect)(()=>{if(typeof window>"u"||Ar.current)return;let A=new URLSearchParams(window.location.search),x=A.get("payment_intent_client_secret");if(!x)return;let U=sd();U&&(Ar.current=!0,(async()=>{let ne,He=0;wt(null),ht(null),kt("processing"),pn(!0);try{if(A.get("redirect_status")==="failed")throw Object.assign(new De.FloPayError("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:Ie,paypalFlopay:ye}=await li({publishableKey:U.publishableKey,paypalPublishableKey:U.paypalPublishableKey,billingApiUrl:O,locale:l,telemetry:o});ne=sn(ye??Ie),ne?.setCheckoutContext(L),He=ne?.now()??0,ne?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),ne?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let le=(ye??Ie)?.getRawProvider();if(!le)throw Object.assign(new De.FloPayError("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:W,error:M}=await le.retrievePaymentIntent(x);if(M)throw Object.assign(new De.FloPayError(M.message??"Failed to retrieve PayPal payment status.","api_error",{code:M.code}),{checkoutMethod:"paypal"});let ge=cs(W?.status);if(!W||ge==="failed")throw Object.assign(new De.FloPayError("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let k=typeof W.payment_method=="string"?W.payment_method:W.payment_method?.id,G=ge;if(U.sessionId){let v=(await new Rr.PaymentAPI(O,{telemetry:!1}).getUnifiedCheckoutSession(U.sessionId)).data.session;if(v&&v.status!=="complete"){let m=await po({billingApiUrl:O,sessionId:U.sessionId,session:v,telemetry:!1,tokenizedData:{id:k??W.id,type:"card",threeDSecureActionResultTokenId:W.id,isPaypal:!0}});if(m.type!=="success")throw Object.assign(new De.FloPayError("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});G=m.result.status}}U.sessionId&&co(U.sessionId),ne?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),ne?.performance({stage:"redirect_resume",durationMs:ne.elapsed(He),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),ne?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),kt("success"),await $o(1200),nt(()=>mt.current?.({status:G,paymentIntentId:W.id,paymentMethodId:k,checkoutMethod:"paypal"}))}catch(Ie){let ye=No(Ie),le=ye.checkoutMethod??"paypal",W=!!(ye.declineCode||ye.code?.toLowerCase().includes("declin"));if(ne)ne.performance({stage:"redirect_resume",durationMs:ne.elapsed(He),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),W?ne.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):ne.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(W){let M=_a(O,o,L);M.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),jo(M)}else bi(O,o,L,"REDIRECT_RESUME_FAILED","redirect_resume");wt(ye.message),ht(ye.message),nt(()=>pe.current?.(ye)),bt(le,ye,{code:ye.code,declineCode:ye.declineCode}),kt("error"),await $o(1500)}finally{Ci(),ld(),kt(null),ht(null),pn(!1)}})())},[bt,l,O,o,L]);let mn=(0,C.useRef)(null),On=(0,C.useMemo)(()=>jt?lo(jt):"",[jt]),fn=(0,C.useRef)(jt);fn.current=jt,(0,C.useEffect)(()=>{nn(e??"")},[e]),(0,C.useEffect)(()=>{Un.current=!1,wt(Le),ht(null),dt(!1),kt(null)},[On,Le,e]);async function Ue(A,x,U){let ne=_a(O,o,L),He=new Rr.PaymentAPI(O,{telemetry:!1}),Ie=!1;try{let ye=A.idempotencyKey===void 0?void 0:(0,De.resolveIdempotencyKey)(A.idempotencyKey),le=ni(x,U),W=ri(x,U);le?.canonicalIdentity===U&&W&&W.canonicalIdentity===void 0&&(ga(x,U,W.idempotencyKey),W={...W,canonicalIdentity:U});let M=ye??(W?.canonicalIdentity===U?W.idempotencyKey:void 0),ge,k=!1;ne.log({name:le?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let G=le?.sid??null,Ze=null,Vt,v,m=!1;if(G)try{Ze=await He.getUnifiedCheckoutSession(G,le?.nonce),le&&le.canonicalIdentity===void 0&&(Ps(Ze.data.session,A)?(fa(x,U,G,le.nonce??Ze.data.session?.clientSecret),W&&W.canonicalIdentity===void 0&&(ga(x,U,W.idempotencyKey),M??(M=W.idempotencyKey))):(ya(x,U),W=null,M=ye,G=null,Ze=null));let ae=Ze?.data.session?.status,Me=Ze?.data.session,ce=Me?.clientSecret||le?.nonce;if(G&&Me?.buyerIdentified===!1&&ce&&(v=eo(He,G,ce,A.account)),G&&Ze&&ae==="complete"){if(oi(G))return{sid:G,result:Ze};ya(x,U),G=null,Ze=null,k=!0}}catch{ne.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),le?.canonicalIdentity===void 0?(ya(x,U),M=ye):ma(x,U),G=null}if(!G){!ye&&(k||!M)&&(M=(0,De.resolveIdempotencyKey)(),ge=M),M&&ga(x,U,M);let ae=ne.now(),Me=0;ne.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let ce={...A,idempotencyKey:M,avsCheck:!!te,avsConfig:typeof te=="object"?te:void 0,checkoutType:"embedded_checkout",checkoutLayout:Si(_e,ie)};Object.defineProperty(ce,Rr.SESSION_CREATE_TELEMETRY,{configurable:!1,enumerable:!1,value:{onAttempt:vt=>{Me=Math.max(Me,vt)}}});let At=()=>{nl(ne,"session_create",ae,Me)},In=vt=>{rl(ne,vt,"session_create",ae,Me)&&Ae({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_create"})};try{if((0,De.isDetachedSessionEligible)(ce)){let vt=await He.createDetachedSession(ce);vt.claimed.catch(()=>{}),Ze=vt.shell,G=vt.sessionId,v=vt.claim;let Dt=ne.now();ne.log({name:"session.claim.started",stage:"session_claim",requestCategory:"session_claim"}),Vt=vt.claimed.then(an=>{let Ee=an.data.session?.id??vt.sessionId;return Ee&&fa(x,U,Ee,an.data.session?.clientSecret??vt.nonce),nl(ne,"session_claim",Dt),At(),an},an=>{throw ma(x,U),rl(ne,an,"session_claim",Dt,0)&&Ae({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_claim"}),an}).finally(()=>jo(ne)),Vt.catch(()=>{}),Ie=!0,ne.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),ne.performance({stage:"session_shell",durationMs:ne.now()-ae,durationMode:"machine",requestCategory:"session_create",attempt:Me,statusClass:"2xx",paymentMethodCategory:"card"})}else Ze=await He.createAndFetchSession(ce),At()}catch(vt){throw In(vt),vt}G=Ze.data.session?.id??G??"",G&&!Vt&&fa(x,U,G,Ze.data.session?.clientSecret)}let g=Ze?.data.session;return!v&&G&&g?.buyerIdentified===!1&&g.clientSecret&&(v=eo(He,G,g.clientSecret,A.account)),{sid:G??"",result:Ze,sdkGeneratedIdempotencyKey:ge,...Vt?{claimed:Vt}:{},...v?{claim:v}:{},...m?{claimRequiresIdentity:!0}:{}}}finally{Ie||jo(ne)}}let ln=(0,C.useRef)(Ue);Ur(()=>{ln.current=Ue},[Ue]);let Ft=(0,C.useCallback)(async(A,x)=>{let U=fn.current;if(!U)throw new De.FloPayError("createSession is required to bootstrap checkout.","validation_error");let ne=Ga(U,A),He=lo(ne),Ie=vs(ne),ye=Ea.get(He);if(!ye){let M={canonicalIdentity:He,promise:ln.current(ne,Ie,He),consumers:0,settled:!1};ye=M,Ea.set(He,M);let ge=()=>{M.settled=!0,tl(He,M)};M.promise.then(ge,ge)}ye.consumers+=1;let le=!1,W=()=>{le||(le=!0,ye.consumers-=1,tl(He,ye))};x?.(W);try{let M=await ye.promise;mn.current=He,A&&(Cn(er),Pn(g=>is(g,A)));let{sid:ge,result:k,claimed:G,claim:Ze,claimRequiresIdentity:Vt}=M;if(Tn.current=Ze,on(Vt===!0),X(k),k.data.session&&j(k.data.session),ge&&nn(ge),G){Ln.current+=1;let g=Ln.current;ot(!0),G.then(ae=>{Ln.current===g&&(X(ae),ae.data.session&&j(ae.data.session),ot(!1),on(!1))},ae=>{Ln.current===g&&(ot(!1),on(!1),hn(ae instanceof De.FloPayError?ae:new De.FloPayError(ae instanceof Error?ae.message:"Failed to create session","api_error")))})}else Ln.current+=1,ot(!1),on(!1);let{flopay:v,paypalFlopay:m}=await Pi(k,{billingApiUrl:O,locale:l,telemetry:o});return Sn(v,m),rn(!1),M}catch(M){throw mn.current===He&&(mn.current=null),M}finally{x||W()}},[er,Sn,l,O,o]),Vn=(0,C.useRef)(Nn);Vn.current=Nn;let sr=(0,C.useRef)(Ft);sr.current=Ft;let br=(0,C.useCallback)(async A=>{if(!dd(A)||ut)return{sessionId:et,session:D};E(!0);try{let x=await Ft(A);return{sessionId:x.sid,session:x.result.data.session??null}}finally{E(!1)}},[Ft,ut,et,D]),Kn=(0,C.useCallback)(async A=>{let x=Tn.current;if(!x)return;let U=Ln.current,ne=await x(A);Ln.current===U&&(X(ne),ne.data.session&&j(ne.data.session))},[]);(0,C.useEffect)(()=>{let A=!1,x,U=++Xe.current;wn(),hn(null),$e(0);let ne=()=>{A=!0,Xe.current===U&&(Xe.current+=1,wn())},He=fn.current;if(On&&He)return un(jn),rn(!1),mn.current===On?ne:(j(ss(He,_)),(async()=>{let le=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),W=jn==="auto"&&!Un.current&&!le;W&&(wt(null),ht(null),kt("processing"));try{let M=await sr.current(void 0,Ze=>{x=Ze}),ge=M.result.data.session??null;pt.current=si(M.result);let k=vi(M.result),G=oi(M.sid||ge?.id);if(!A&&W&&ge&&!k&&!G){Un.current=!0,await od(On,M.sdkGeneratedIdempotencyKey,()=>Vn.current(ge,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:M.result.autoProcessingError,initialAutoProcessingPending:M.result.autoProcessingPending,autoProcessingAttempted:M.result.autoProcessingAttempted,sessionId:M.sid||ge.id}));return}!A&&W&&((k||G)&&(Un.current=!0),kt(null),ht(null))}catch(M){if(A)return;let ge=ra(M);if(W&&ge==="session_auto_completed"){Un.current=!0,kt("success"),await $o(1200),A||(nt(()=>{mt.current?.({status:"succeeded"})}),kt(null),ht(null));return}W&&(kt(null),ht(null));let k=M instanceof De.FloPayError?M:new De.FloPayError(M instanceof Error?M.message:"Failed to create session","api_error");hn(k)}finally{x?.(),x=void 0}})(),()=>{ne(),x?.()});rn(!0);async function Ie(){let le=!1,W=null;try{let M=new Rr.PaymentAPI(O,{telemetry:!1}),ge=await M.getUnifiedCheckoutSession(lt,t);if(W=ge,A)return;X(ge);let k=ge.data.session??null;if(j(k),!k)throw new De.FloPayError("No session data returned","api_error");let G=k.checkoutMode;if(G==="setup")throw new De.FloPayError("This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.","validation_error",{code:"InvalidCardSetupSurface",param:"sessionId"});if(k.status==="authorized"){rn(!1),nt(()=>{mt.current?.(Or(k,lt)),hr.current?.(k.successUrl??"")});return}if(k.status==="complete"){rn(!1),nt(()=>{hr.current?.(k.successUrl??"")});return}if(k.status==="expired")throw na(k);le=!0;let Ze=_??G??"full";un(Ze),Ln.current+=1;let Vt=k.clientSecret||t;Tn.current=k.buyerIdentified===!1&&Vt?eo(M,lt,Vt,{...k.customer?.id?{userId:k.customer.id}:{}}):void 0,ot(!1),on(!1);let v=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),m=vi(ge);if(Ze==="auto"&&!Un.current&&!v&&!m){Un.current=!0;let g=ye(ge);try{if(await Vn.current(k,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>g,sessionId:lt||k.id}),A)return;await g,A||rn(!1);return}catch{if(A)return;await g,A||rn(!1);return}}await ye(ge),A||rn(!1)}catch(M){if(A)return;let ge=as(M,le);if(le&&Ae({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"}),ge){let{errorCode:G,stage:Ze,...Vt}=ge;bi(O,o,L,G,Ze,Vt)}if(ge?.stage==="provider_load"&&(_??W?.data.session?.checkoutMode??"full")==="full"&&os(W,N,de)){let G=id({billingApiUrl:O,locale:l,telemetry:o});be.current=G,Sn(G,null),$e(1),rn(!1);return}let k=M instanceof De.FloPayError&&ge?.stage!=="provider_load"?M:rs();k!==M&&nt(()=>pe.current?.(k)),hn(k),rn(!1)}}async function ye(le){let{flopay:W,paypalFlopay:M,...ge}=await Pi(le,{billingApiUrl:O,locale:l,telemetry:o});pt.current={publishableKey:ge.publishableKey,paypalPublishableKey:ge.paypalPublishableKey},Sn(W,M),$e(0)}return Ie(),ne},[_,On,jn,Wt,t,N,de]);let An=(0,C.useCallback)(async()=>{if(!Z||bn!==1)return;let A=Xe.current;$e(2);try{let{flopay:x,paypalFlopay:U}=await Pi(Z,{billingApiUrl:O,locale:l,telemetry:o});if(Xe.current!==A)return;wn(),Sn(x,U),$e(0)}catch(x){if(Xe.current!==A)return;let{errorCode:U,stage:ne,...He}=Wa(x);bi(O,o,L,U,ne,He)}},[wn,Sn,l,bn,O,o,L,Z]),Mn=(0,C.useCallback)(async()=>{if(!(Gt||!D)){pn(!0),wt(null);try{await Nn(D,{attempt3DS:!0,fallbackToFull:!0,sessionId:lt||D.id})}finally{pn(!1)}}},[lt,Gt,Nn,D]),lr=wi(Z),Vr=vi(Z),Hn=(0,C.useMemo)(()=>{if(!(!Z||!D||!Z.data.stripe?.publishableKey))return{billingApiUrl:O}},[Z,D,O]),cr=!!(n&&!_e&&ie==="buttons"&&he&&jn==="full"),gn=(0,C.useMemo)(()=>({session:D,loading:dn,error:ke,checkoutMode:ct,inlineSessionDraft:jt,applyInlineSessionPatch:cr?br:void 0,inlineSessionPatchProcessing:ut,claimPending:xt,claimRequiresIdentity:Xt,claimBuyerIdentity:Kn}),[D,dn,ke,ct,jt,cr,br,ut,xt,Xt,Kn]),yt=!!n&&ie==="buttons"&&!Vr&&(!$||!Hn),kn=Qn?(0,R.jsx)(Xn,{status:Qn,errorMessage:vn,authorized:Yt}):null;if(dn){if(c)return(0,R.jsxs)(R.Fragment,{children:[c,kn]});if(ie==="buttons"){let A=Ce?.buttonsLayout?.cardButton?.borderRadius??Ce?.appearance.variables?.borderRadius??8,x=U=>(0,R.jsx)("div",{style:{height:U,borderRadius:A,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:[N&&x(jr),de&&(I||re)&&x(jr),de&&x(jr),(0,R.jsx)("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),kn]})}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); } }"})]}),kn]})}return ke?f?(0,R.jsx)(rr.Provider,{value:gn,children:f(ke)}):(0,R.jsx)(rr.Provider,{value:gn,children:(0,R.jsx)("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:ke.message})}):yt?(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(rr.Provider,{value:gn,children:(0,R.jsx)(pd,{onButtonClick:Re,showPayPal:N,showStripe:de,showApplePay:I,showGooglePay:re,theme:se,buttonsTheme:ee,buttonsStyles:Oe,cardButtonContent:ue,cardBackButtonContent:Ct,cardTitleContent:st})}),kn]}):Vr&&D&&lr?(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(rr.Provider,{value:gn,children:(0,R.jsxs)("div",{className:xe,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[$t&&(0,R.jsx)(io,{icon:!1,children:$t}),Zt==="retrying"&&(0,R.jsx)("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),Zt==="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:Mr,children:"Retry PayPal"})]}),xt?c??(0,R.jsx)("div",{role:"status","data-testid":"flopay-paypal-catalog-loading","aria-label":"Preparing PayPal",style:{height:jr,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; } }"})}):Zt!=="exhausted"&&(0,R.jsx)("div",{"aria-hidden":Zt==="retrying"?!0:void 0,style:Zt==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:(0,R.jsx)(bs,{sessionId:lt,nonce:D.clientSecret||void 0,billingApiUrl:O,email:D.customer?.email||jt?.account?.email,billingName:[D.customer?.firstName,D.customer?.lastName].filter(Boolean).join(" ")||[jt?.account?.firstName,jt?.account?.lastName].filter(Boolean).join(" ")||void 0,onBuyerIdentityReady:Kn,clientId:lr.clientId,environment:lr.environment,currency:(D.currency??"usd").toUpperCase(),isSubscription:D.mode==="subscription",providerObjectType:lr.providerObjectType,approvalPresentation:lr.approvalPresentation,onComplete:y,onErrorChange:wt,onDecline:h,onButtonClick:Re,onInitializationStateChange:at,allowAutomaticRetry:Tr===0,session:D,telemetry:o,telemetryContext:L,onInstrument:tn,debug:q},`${ve}:paypal-init-${Tr}`)})]})}),kn]}):!$||!Hn?(0,R.jsx)(R.Fragment,{children:kn}):ct==="confirm"?(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(rr.Provider,{value:gn,children:(0,R.jsx)(Fo,{flopay:$,paypalFlopay:H,options:Hn,onInstrument:tn,children:(0,R.jsxs)("div",{className:xe,children:[$t&&(0,R.jsx)("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:$t}),me?me({onConfirm:Mn,isProcessing:Gt}):(0,R.jsx)("button",{type:"button",onClick:Mn,disabled:Gt,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:Gt?"not-allowed":"pointer",opacity:Gt?.6:1},children:Gt?"Processing...":oe??"Confirm Purchase"})]})},ve)}),kn]}):(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(rr.Provider,{value:gn,children:(0,R.jsxs)(Fo,{flopay:$,paypalFlopay:H,options:Hn,onInstrument:tn,children:[bn===1&&(0,R.jsx)("button",{type:"button",onClick:An,children:"Retry payment methods"}),_e?(0,R.jsxs)(R.Fragment,{children:[$t&&(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:$t}),(0,R.jsx)(ud,{sessionId:lt,nonce:D?.clientSecret||void 0,billingApiUrl:O,session:D,children:_e})]}):(0,R.jsx)(Ia,{sessionId:lt,nonce:D?.clientSecret||void 0,email:D?.customer?.email||jt?.account?.email,userId:D?.customer?.id||jt?.account?.userId,firstName:D?.customer?.firstName||jt?.account?.firstName,lastName:D?.customer?.lastName||jt?.account?.lastName,totalAmount:D?Math.round((0,De.buildCheckoutDisplayData)(D).total*100):0,currency:D?.currency?.toLowerCase()??"usd",onComplete:y,onError:p,onDecline:h,error:$t,onErrorChange:wt,showPayPal:N,showStripe:de,enabledPaymentMethods:bn?[]:K??Z?.data.stripe?.enabledPaymentMethods??D?.gateways?.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:Z?.data.stripe?.enabledPaymentMethodCountries,showApplePay:I,showGooglePay:re,layout:ie,theme:se,buttonsTheme:ee,buttonsStyles:Oe,appearance:Ke,cardButtonContent:ue,cardBackButtonContent:Ct,cardTitleContent:st,onButtonClick:Re,onBeforeButtonClick:he,onBuyerIdentityReady:Kn,enableAVS:te,...Te?{cardFieldOrder:Te}:{},...fe?{cardPreFormSlot:fe}:{},avsLayout:we,country:D?.customer?.country,city:D?.customer?.city,state:D?.customer?.state,onCountryChange:w,onZipChange:B,avsCheck:!!te,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:Si(_e,ie),className:xe,directPaypal:wi(Z),isSubscription:D?.mode==="subscription",session:D,dataAttachmentPending:xt,dataAttachmentRequiresIdentity:Xt,debug:q})]},ve)}),kn]})}function ud({sessionId:e,nonce:t,billingApiUrl:n,session:r,children:o}){return(0,R.jsx)(R.Fragment,{children:C.default.Children.map(o,a=>{if(!C.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:C.default.cloneElement(a,c)})})}function pd({onButtonClick:e,showPayPal:t,showStripe:n=!0,showApplePay:r,showGooglePay:o,theme:a,buttonsTheme:l,buttonsStyles:c,cardButtonContent:f,cardBackButtonContent:y,cardTitleContent:p}){let[b,h]=(0,C.useState)(!1),w=(0,C.useMemo)(()=>(0,De.resolveTheme)(a),[a]),B=(0,C.useMemo)(()=>{let I=w?.buttonsLayout??(0,De.resolveButtonsLayoutTheme)(l);return c?{...I,...c,cardButton:{...I.cardButton,...c.cardButton},cardFormContainer:{...I.cardFormContainer,...c.cardFormContainer},backButton:{...I.backButton,...c.backButton},backButtonIcon:{...I.backButtonIcon,...c.backButtonIcon},submitButton:{...I.submitButton,...c.submitButton},title:{...I.title,...c.title}}:I},[w,l,c]),N=w?.buttonsLayout?.cardButton?.borderRadius??w?.appearance.variables?.borderRadius??8,de=I=>(0,R.jsx)("div",{style:{height:I,borderRadius:N,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),K=f===void 0?{boxSizing:"border-box",height:jr,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(b){let I=B.cardInputBorder??"#e5e7eb",re=B.cardInputBackground??"white",q=Xr(y),ie=Xr(p);return(0,R.jsxs)("div",{style:{backgroundColor:B.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",...B.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:()=>h(!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",...B.backButton},children:[(0,R.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...B.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)(Qr,{content:y})]}),ie?(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,...B.title},children:(0,R.jsx)(Ro,{content:p})})]}),(0,R.jsx)("div",{style:{backgroundColor:re,border:`1px solid ${I}`,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:re,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${I}`,borderLeft:`1px solid ${I}`,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:re,borderTop:"none",borderRight:`1px solid ${I}`,borderBottom:`1px solid ${I}`,borderLeft:`1px solid ${I}`,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:re,border:`1px solid ${I}`,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",...B.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,R.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&ye(Lr),n&&(r||o)&&ye(Lr),n&&(0,R.jsx)("button",{type:"button",onClick:()=>{e?.("card"),h(!0)},style:{width:"100%",...W,backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:"8px",fontSize:D.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,...D.cardButton},onMouseDown:I=>{I.currentTarget.style.transform="scale(0.985)"},onMouseUp:I=>{I.currentTarget.style.transform="scale(1)"},children:(0,R.jsx)(Wr,{content:g})}),(0,R.jsx)("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}var tr=require("react/jsx-runtime"),id=44;function al(e){return new Promise(t=>setTimeout(t,e))}function sd(e,t){return e instanceof Un.FloPayError?e:new Un.FloPayError(e instanceof Error?e.message:t,"api_error")}function ld(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function cd(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 il({sessionId:e,nonce:t,createSession:n,paymentMethodId:r,checkoutMethod:o,clientId:a,products:l,items:c,subscriptions:g,account:y,successUrl:m,cancelUrl:v,couponCodes:h,tagsData:w,utmMetadata:D,billingApiUrl:N,locale:ye,theme:W,appearance:I,buttonsTheme:ie,buttonsStyles:q,onSuccess:ue,onError:re,onDecline:le,children:He,disabled:ce=!1,type:Rt="button",style:Ge,...Te}){let xe=(0,Ke.useMemo)(()=>(0,Un.resolveBillingApiUrl)(N),[N]),oe=(0,Ke.useMemo)(()=>cd({createSession:n,clientId:a,products:l,items:c,subscriptions:g,account:y,successUrl:m,cancelUrl:v,couponCodes:h,tagsData:w,utmMetadata:D}),[y,v,a,h,n,l,c,g,m,w,D]),[ae,z]=(0,Ke.useState)(!1),[De,Ne]=(0,Ke.useState)(null),[Ee,Oe]=(0,Ke.useState)(null),[ke,k]=(0,Ke.useState)(!1),[de,he]=(0,Ke.useState)(null),Y=(0,Ke.useRef)(!0),L=(0,Ke.useRef)(null),Ie=(0,Ke.useRef)(de),tt=(0,Ke.useRef)(ue),gt=(0,Ke.useRef)(re),Ye=(0,Ke.useRef)(le);(0,Ke.useEffect)(()=>{Ie.current=de},[de]),(0,Ke.useEffect)(()=>{tt.current=ue},[ue]),(0,Ke.useEffect)(()=>{gt.current=re},[re]),(0,Ke.useEffect)(()=>{Ye.current=le},[le]),(0,Ke.useEffect)(()=>(Y.current=!0,()=>{Y.current=!1,L.current?.abort()}),[]),(0,Ke.useEffect)(()=>{if(typeof window>"u")return;let T=O=>{O.key==="Escape"&&he(null)};return window.addEventListener("keydown",T),()=>{window.removeEventListener("keydown",T)}},[]);let ee=(0,Ke.useCallback)((T,O=Mo)=>{Ye.current?.(tn(O,T,{code:T.code,declineCode:T.declineCode}))},[]),J=(0,Ke.useCallback)(async T=>{Y.current&&(Oe(null),k(T.result.status==="authorized"),Ne("success"),await al(1200),Y.current&&Qe(()=>tt.current?.(T)))},[]),$=(0,Ke.useCallback)(async(T,O)=>{Y.current&&(gt.current?.(T),O?.emitDecline&&ee(T,O.method),Oe(T.message),k(!1),Ne("error"),await al(1500))},[ee]),qe=(0,Ke.useCallback)(async(T,O,kt)=>{let Le=T.data.session??null;if(!Le)throw new Un.FloPayError("No session data returned","api_error");let Ut=Le.clientSecret||t;if(Jr(Le)){await J({result:Ar(Le,O),session:Le,sessionId:Le.id||O,autoCompleted:!1});return}if(Le.status==="expired")throw Jo(Le);try{if(T.autoProcessingPending){let mt=(await new Sa.PaymentAPI(xe).waitForCheckoutSessionCompletion(T.autoProcessingPending.sessionId,{initialDelayMs:T.autoProcessingPending.retryAfterMs})).data.session;if(!Jr(mt))throw Zo(mt);await J({result:Ar(mt,O),session:mt,sessionId:mt.id||O,autoCompleted:!1});return}if(T.autoProcessingError){if(T.autoProcessingError.type==="3ds_required"&&T.autoProcessingError.nextActionRedirectUrl&&O&&Ut){let X=new AbortController;L.current=X;let Ft;try{Ft=await Ss({billingApiUrl:xe,sessionId:O,nonce:Ut,nextActionRedirectUrl:T.autoProcessingError.nextActionRedirectUrl,signal:X.signal})}finally{L.current===X&&(L.current=null)}if(Ft.status==="declined")throw kr({type:Ft.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:Ft.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:T.autoProcessingError.checkoutMethod});let Gt=(await new Sa.PaymentAPI(xe).waitForCheckoutSessionCompletion(O,{initialDelayMs:0,nonce:Ut})).data.session;if(!Jr(Gt))throw kr({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:T.autoProcessingError.checkoutMethod});await J({result:Ar(Gt,O),session:Gt,sessionId:Gt.id||O,autoCompleted:!1});return}throw kr(T.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:T.autoProcessingError.checkoutMethod})}if(kt?.fromCreateSession&&T.autoProcessingAttempted===!0)throw kr({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let cn=await io({billingApiUrl:xe,sessionId:O??Le.id,session:Le,nonce:Ut});if(cn.type!=="success")throw kr({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await J({result:cn.result,session:Le,sessionId:Le.id||O,autoCompleted:!1})}catch(cn){let X=Ao(cn),Ft=Le.id||O;await $(X,{emitDecline:!0,method:X.checkoutMethod??Mo}),ld(X,Ft)&&Ft&&Y.current&&he({sessionId:Ft,errorMessage:X.message,nonce:Ut||void 0})}},[t,xe,$,J]),et=(0,Ke.useCallback)(async T=>{if(Te.onClick?.(T),!(T.defaultPrevented||ce||ae)){if(he(null),e&&oe){let O=new Un.FloPayError("Provide either sessionId or create-session props, not both.","validation_error");await $(O),Y.current&&(Ne(null),Oe(null));return}if(!e&&!oe){let O=new Un.FloPayError("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await $(O),Y.current&&(Ne(null),Oe(null));return}z(!0),Oe(null),k(!1),Ne("processing");try{let O=new Sa.PaymentAPI(xe);if(e){let kt=await O.getUnifiedCheckoutSession(e,t);await qe(kt,e);return}try{let kt=await O.createAndFetchSession({...oe});await qe(kt,kt.data.session?.id??null,{fromCreateSession:!0})}catch(kt){if(Xo(kt)==="session_auto_completed"){await J({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw kt}}catch(O){await $(sd(O,"Automatic payment failed. Please try again."))}finally{Y.current&&(Ne(null),Oe(null),z(!1))}}},[Te.onClick,oe,ce,ae,t,qe,xe,e,$,J]),ve=(0,Ke.useCallback)(T=>{let O=Ie.current;he(null),tt.current?.({result:T,session:null,sessionId:O?.sessionId??null,autoCompleted:!1})},[]),Je=(0,Ke.useCallback)(T=>{gt.current?.(T)},[]),te=(0,Ke.useCallback)(T=>{Ye.current?.(T)},[]),V=(0,Ke.useMemo)(()=>(0,Un.resolveTheme)(W),[W]),nt=(0,Ke.useMemo)(()=>{let T=V?.buttonsLayout??(0,Un.resolveButtonsLayoutTheme)(ie);return q?{...T,...q,cardButton:{...T.cardButton,...q.cardButton}}:T},[V,ie,q]),B=(0,Ke.useMemo)(()=>{let T=V?.appearance;return I?T?{...T,...I,variables:{...T.variables,...I.variables}}:I:T},[I,V]),Q=B?.variables,ze=Q?.colorPrimary??"#4A49FF",pe=Q?.colorPrimaryHover??lo(ze,.12),lt=Q?.borderRadius??"8px";return(0,tr.jsxs)(tr.Fragment,{children:[(0,tr.jsx)("button",{...Te,type:Rt,onClick:et,disabled:ce||ae,"aria-busy":ae,style:{width:"100%",...He===void 0?{boxSizing:"border-box",height:id,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...nt.cardButton,...ci({themeBundle:V,resolvedPrimaryColor:ze,resolvedBorderRadius:lt,submitButtonStyle:nt.submitButton,explicitPrimaryColor:Q?.colorPrimary}),fontSize:nt.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:ce||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:ce||ae?.6:1,...Ge},onMouseEnter:T=>{Te.onMouseEnter?.(T),!T.defaultPrevented&&!ce&&!ae&&(V||Q?.colorPrimary)&&(T.currentTarget.style.backgroundColor=pe)},onMouseLeave:T=>{Te.onMouseLeave?.(T),!T.defaultPrevented&&(V||Q?.colorPrimary)&&(T.currentTarget.style.backgroundColor=ze)},onMouseDown:T=>{Te.onMouseDown?.(T),T.defaultPrevented||(T.currentTarget.style.transform="scale(0.985)")},onMouseUp:T=>{Te.onMouseUp?.(T),T.defaultPrevented||(T.currentTarget.style.transform="scale(1)")},children:(0,tr.jsx)(Wr,{content:He})}),De&&(0,tr.jsx)(zn,{status:De,errorMessage:Ee,authorized:ke}),de&&(0,tr.jsx)("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:T=>{T.target===T.currentTarget&&he(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,tr.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,tr.jsx)(Pa,{sessionId:de.sessionId,nonce:de.nonce,checkoutMode:"full",billingApiUrl:xe,locale:ye,theme:W,...B?{appearance:B}:{},buttonsTheme:ie,buttonsStyles:q,initialErrorMessage:de.errorMessage,cardTitleContent:null,onComplete:ve,onError:Je,onDecline:te})})})]})}var wa=require("@flopay/js/card-setup"),Bn=require("@flopay/shared"),pt=require("react");var sl={light:{success:"#166534",error:"#991B1B"},dark:{success:"#4ADE80",error:"#FCA5A5"}};function ll(e){let t=e.appearance.variables??{},n=e.buttonsLayout.cardFormContainer??{},r=e.appearance.theme==="night",o=r?sl.dark:sl.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 lr=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 cl(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 dl({sessionId:e,nonce:t,billingApiUrl:n,telemetry:r,theme:o="modern-light",containerStyle:a,loading:l=null,onReady:c,onComplete:g,onDecline:y,onCancel:m,onValidation:v,onError:h}){let[w,D]=(0,pt.useState)(null),[N,ye]=(0,pt.useState)(null),[W,I]=(0,pt.useState)(null),[ie,q]=(0,pt.useState)(null),[ue,re]=(0,pt.useState)(null),le=(0,pt.useRef)(!1),He=(0,pt.useRef)(!1),ce=(0,pt.useMemo)(()=>typeof o=="object"?void 0:(0,Bn.resolveTheme)(o),[o]),Rt=(0,pt.useMemo)(()=>typeof o=="object"?o:ce?ma({appearance:ce.appearance,buttonsStyles:ce.buttonsLayout,layout:"default"}):null,[ce,o]),Ge=(0,pt.useMemo)(()=>Rs(ce?.buttonsLayout.cardFormContainer,a),[ce,a]),Te=(0,pt.useMemo)(()=>ce?ll(ce):void 0,[ce]),xe=(0,pt.useRef)(c),oe=(0,pt.useRef)(h),ae=(0,pt.useRef)(g),z=(0,pt.useRef)(y),De=(0,pt.useRef)(m),Ne=(0,pt.useRef)(v),Ee=(0,pt.useRef)(!1),Oe=(0,pt.useRef)(!1),ke=(0,pt.useRef)(0);return xe.current=c,oe.current=h,ae.current=g,z.current=y,De.current=m,Ne.current=v,(0,pt.useEffect)(()=>{let k=ke.current+1;return ke.current=k,()=>{queueMicrotask(()=>{ke.current===k&&(Ee.current||Oe.current||(Oe.current=!0,Qe(()=>{De.current?.({status:"cancelled",sessionId:e})})))})}},[e]),(0,pt.useEffect)(()=>{let k=!0,de=new wa.PaymentAPI((0,Bn.resolveBillingApiUrl)(n),{telemetry:r});return D(null),ye(null),I(null),Ee.current=!1,Oe.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 he=await de.getUnifiedCheckoutSession(e,t);if(!k)return;let Y=he.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 de.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(!k)return;ye(L),D(new wa.PciVaultCardCapture({sessionId:e,operation:"card_setup",telemetry:r}))}catch(he){if(!k)return;let Y=cl(he);Ee.current=!0,I(Y),Qe(()=>oe.current?.(Y))}})(),()=>{k=!1,de.destroy()}},[n,t,e,r]),(0,pt.useEffect)(()=>{if(!w)return;let k=!1;He.current=!1,le.current=!1;let de=w.on("submitting",()=>{le.current=!0,re(null),q("processing")}),he=w.on("complete",L=>{Ee.current=!0,le.current=!1,q("success"),(async()=>(await new Promise(Ie=>setTimeout(Ie,1200)),!He.current&&(He.current=!0,Qe(()=>{ae.current?.({status:"succeeded",sessionId:e,...L.paymentMethod?{paymentMethod:L.paymentMethod}:{}})}),k||q(null))))()}),Y=w.on("decline",L=>{Ee.current=!0,le.current=!1,re(L.message??null),q("error"),Qe(()=>{z.current?.({status:"declined",sessionId:e,...L.declineReason?{reason:L.declineReason}:{},...L.message?{message:L.message}:{}})}),(async()=>(await new Promise(Ie=>setTimeout(Ie,1500)),k||q(null)))()});return()=>{k=!0,de(),he(),Y()}},[w,e]),W?(0,lr.jsx)("div",{role:"alert",children:W.message}):!w||!N?.html?(0,lr.jsx)(lr.Fragment,{children:l}):(0,lr.jsxs)(lr.Fragment,{children:[ie&&(0,lr.jsx)(zn,{status:ie,errorMessage:ue,processingLabel:"SAVING CARD...",successLabel:"CARD SAVED",errorLabel:"CARD NOT SAVED",successNote:null,...Te?{theme:Te}:{}}),(0,lr.jsx)(so,{capture:w,html:N.html,messageToken:N.messageToken,expectedOrigin:N.expectedOrigin,theme:Rt,containerStyle:Ge,onReady:()=>{Qe(()=>xe.current?.())},onValidation:k=>{Qe(()=>Ne.current?.(k))},onError:k=>{if(!k)return;le.current&&(le.current=!1,re(k),q("error"),setTimeout(()=>q(null),1500));let de=cl(new Error(k),{code:"card_setup_widget_failed",retryable:!0});Qe(()=>oe.current?.(de))}})]})}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&&de(jr),n&&(r||o)&&de(jr),n&&(0,R.jsx)("button",{type:"button",onClick:()=>{e?.("card"),h(!0)},style:{width:"100%",...K,backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:"8px",fontSize:B.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,...B.cardButton},onMouseDown:I=>{I.currentTarget.style.transform="scale(0.985)"},onMouseUp:I=>{I.currentTarget.style.transform="scale(1)"},children:(0,R.jsx)(Zr,{content:f})}),(0,R.jsx)("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}var ir=require("react/jsx-runtime"),md=44;function sl(e){return new Promise(t=>setTimeout(t,e))}function yd(e,t){return e instanceof Zn.FloPayError?e:new Zn.FloPayError(e instanceof Error?e.message:t,"api_error")}function fd(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function gd(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 ll({sessionId:e,nonce:t,createSession:n,paymentMethodId:r,checkoutMethod:o,clientId:a,products:l,items:c,subscriptions:f,account:y,successUrl:p,cancelUrl:b,couponCodes:h,tagsData:w,utmMetadata:B,billingApiUrl:N,locale:de,theme:K,appearance:I,buttonsTheme:re,buttonsStyles:q,onSuccess:ie,onError:se,onDecline:ee,children:Oe,disabled:ue=!1,type:Ct="button",style:st,...Se}){let Re=(0,We.useMemo)(()=>(0,Zn.resolveBillingApiUrl)(N),[N]),he=(0,We.useMemo)(()=>gd({createSession:n,clientId:a,products:l,items:c,subscriptions:f,account:y,successUrl:p,cancelUrl:b,couponCodes:h,tagsData:w,utmMetadata:B}),[y,b,a,h,n,l,c,f,p,w,B]),[te,Te]=(0,We.useState)(!1),[fe,we]=(0,We.useState)(null),[xe,Le]=(0,We.useState)(null),[_e,_]=(0,We.useState)(!1),[oe,me]=(0,We.useState)(null),J=(0,We.useRef)(!0),O=(0,We.useRef)(null),Ce=(0,We.useRef)(oe),Ke=(0,We.useRef)(ie),_t=(0,We.useRef)(se),Qe=(0,We.useRef)(ee);(0,We.useEffect)(()=>{Ce.current=oe},[oe]),(0,We.useEffect)(()=>{Ke.current=ie},[ie]),(0,We.useEffect)(()=>{_t.current=se},[se]),(0,We.useEffect)(()=>{Qe.current=ee},[ee]),(0,We.useEffect)(()=>(J.current=!0,()=>{J.current=!1,O.current?.abort()}),[]),(0,We.useEffect)(()=>{if(typeof window>"u")return;let P=F=>{F.key==="Escape"&&me(null)};return window.addEventListener("keydown",P),()=>{window.removeEventListener("keydown",P)}},[]);let Z=(0,We.useCallback)((P,F=Lo)=>{Qe.current?.(cn(F,P,{code:P.code,declineCode:P.declineCode}))},[]),X=(0,We.useCallback)(async P=>{J.current&&(Le(null),_(P.result.status==="authorized"),we("success"),await sl(1200),J.current&&nt(()=>Ke.current?.(P)))},[]),$=(0,We.useCallback)(async(P,F)=>{J.current&&(_t.current?.(P),F?.emitDecline&&Z(P,F.method),Le(P.message),_(!1),we("error"),await sl(1500))},[Z]),ze=(0,We.useCallback)(async(P,F,qt)=>{let Ae=P.data.session??null;if(!Ae)throw new Zn.FloPayError("No session data returned","api_error");let Et=Ae.clientSecret||t;if(to(Ae)){await X({result:Or(Ae,F),session:Ae,sessionId:Ae.id||F,autoCompleted:!1});return}if(Ae.status==="expired")throw na(Ae);try{if(P.autoProcessingPending){let lt=(await new xa.PaymentAPI(Re).waitForCheckoutSessionCompletion(P.autoProcessingPending.sessionId,{initialDelayMs:P.autoProcessingPending.retryAfterMs})).data.session;if(!to(lt))throw oa(lt);await X({result:Or(lt,F),session:lt,sessionId:lt.id||F,autoCompleted:!1});return}if(P.autoProcessingError){if(P.autoProcessingError.type==="3ds_required"&&P.autoProcessingError.nextActionRedirectUrl&&F&&Et){let et=new AbortController;O.current=et;let nn;try{nn=await Is({billingApiUrl:Re,sessionId:F,nonce:Et,nextActionRedirectUrl:P.autoProcessingError.nextActionRedirectUrl,signal:et.signal})}finally{O.current===et&&(O.current=null)}if(nn.status==="declined")throw Er({type:nn.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:nn.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:P.autoProcessingError.checkoutMethod});let dn=(await new xa.PaymentAPI(Re).waitForCheckoutSessionCompletion(F,{initialDelayMs:0,nonce:Et})).data.session;if(!to(dn))throw Er({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:P.autoProcessingError.checkoutMethod});await X({result:Or(dn,F),session:dn,sessionId:dn.id||F,autoCompleted:!1});return}throw Er(P.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:P.autoProcessingError.checkoutMethod})}if(qt?.fromCreateSession&&P.autoProcessingAttempted===!0)throw Er({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let tn=await po({billingApiUrl:Re,sessionId:F??Ae.id,session:Ae,nonce:Et});if(tn.type!=="success")throw Er({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await X({result:tn.result,session:Ae,sessionId:Ae.id||F,autoCompleted:!1})}catch(tn){let et=No(tn),nn=Ae.id||F;await $(et,{emitDecline:!0,method:et.checkoutMethod??Lo}),fd(et,nn)&&nn&&J.current&&me({sessionId:nn,errorMessage:et.message,nonce:Et||void 0})}},[t,Re,$,X]),Je=(0,We.useCallback)(async P=>{if(Se.onClick?.(P),!(P.defaultPrevented||ue||te)){if(me(null),e&&he){let F=new Zn.FloPayError("Provide either sessionId or create-session props, not both.","validation_error");await $(F),J.current&&(we(null),Le(null));return}if(!e&&!he){let F=new Zn.FloPayError("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await $(F),J.current&&(we(null),Le(null));return}Te(!0),Le(null),_(!1),we("processing");try{let F=new xa.PaymentAPI(Re);if(e){let qt=await F.getUnifiedCheckoutSession(e,t);await ze(qt,e);return}try{let qt=await F.createAndFetchSession({...he});await ze(qt,qt.data.session?.id??null,{fromCreateSession:!0})}catch(qt){if(ra(qt)==="session_auto_completed"){await X({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw qt}}catch(F){await $(yd(F,"Automatic payment failed. Please try again."))}finally{J.current&&(we(null),Le(null),Te(!1))}}},[Se.onClick,he,ue,te,t,ze,Re,e,$,X]),be=(0,We.useCallback)(P=>{let F=Ce.current;me(null),Ke.current?.({result:P,session:null,sessionId:F?.sessionId??null,autoCompleted:!1})},[]),Xe=(0,We.useCallback)(P=>{_t.current?.(P)},[]),H=(0,We.useCallback)(P=>{Qe.current?.(P)},[]),z=(0,We.useMemo)(()=>(0,Zn.resolveTheme)(K),[K]),rt=(0,We.useMemo)(()=>{let P=z?.buttonsLayout??(0,Zn.resolveButtonsLayoutTheme)(re);return q?{...P,...q,cardButton:{...P.cardButton,...q.cardButton}}:P},[z,re,q]),D=(0,We.useMemo)(()=>{let P=z?.appearance;return I?P?{...P,...I,variables:{...P.variables,...I.variables}}:I:P},[I,z]),j=D?.variables,qe=j?.colorPrimary??"#4A49FF",ve=j?.colorPrimaryHover??yo(qe,.12),Bt=j?.borderRadius??"8px";return(0,ir.jsxs)(ir.Fragment,{children:[(0,ir.jsx)("button",{...Se,type:Ct,onClick:Je,disabled:ue||te,"aria-busy":te,style:{width:"100%",...Oe===void 0?{boxSizing:"border-box",height:md,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...rt.cardButton,...hi({themeBundle:z,resolvedPrimaryColor:qe,resolvedBorderRadius:Bt,submitButtonStyle:rt.submitButton,explicitPrimaryColor:j?.colorPrimary}),fontSize:rt.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:ue||te?"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:ue||te?.6:1,...st},onMouseEnter:P=>{Se.onMouseEnter?.(P),!P.defaultPrevented&&!ue&&!te&&(z||j?.colorPrimary)&&(P.currentTarget.style.backgroundColor=ve)},onMouseLeave:P=>{Se.onMouseLeave?.(P),!P.defaultPrevented&&(z||j?.colorPrimary)&&(P.currentTarget.style.backgroundColor=qe)},onMouseDown:P=>{Se.onMouseDown?.(P),P.defaultPrevented||(P.currentTarget.style.transform="scale(0.985)")},onMouseUp:P=>{Se.onMouseUp?.(P),P.defaultPrevented||(P.currentTarget.style.transform="scale(1)")},children:(0,ir.jsx)(Zr,{content:Oe})}),fe&&(0,ir.jsx)(Xn,{status:fe,errorMessage:xe,authorized:_e}),oe&&(0,ir.jsx)("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:P=>{P.target===P.currentTarget&&me(null)},style:{position:"fixed",inset:0,background:"rgba(0, 0, 0, 0.45)",display:"flex",alignItems:"center",justifyContent:"center",padding:"1.5rem",zIndex:1100},children:(0,ir.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,ir.jsx)(Ta,{sessionId:oe.sessionId,nonce:oe.nonce,checkoutMode:"full",billingApiUrl:Re,locale:de,theme:K,...D?{appearance:D}:{},buttonsTheme:re,buttonsStyles:q,initialErrorMessage:oe.errorMessage,cardTitleContent:null,onComplete:be,onError:Xe,onDecline:H})})})]})}var Aa=require("@flopay/js/card-setup"),zn=require("@flopay/shared"),gt=require("react");var cl={light:{success:"#166534",error:"#991B1B"},dark:{success:"#4ADE80",error:"#FCA5A5"}};function dl(e){let t=e.appearance.variables??{},n=e.buttonsLayout.cardFormContainer??{},r=e.appearance.theme==="night",o=r?cl.dark:cl.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 gr=require("react/jsx-runtime"),Vo=class extends zn.FloPayError{constructor(t,n,r){super(t,n,r),this.name="FloPayCardSetupError",this.retryable=r.retryable}};function ul(e,t={}){let n=e instanceof zn.FloPayError?e:void 0,r=n?.statusCode,o=t.retryable??(n?.type==="network_error"||n?.type==="rate_limit_error"||typeof r=="number"&&r>=500||n?.code==="vault_capture_timeout"||!n);return new Vo(n?.message??(e instanceof Error?e.message:"Failed to load the secure card form."),n?.type??"api_error",{code:t.code??n?.code??"card_setup_load_failed",retryable:o,...n?.param?{param:n.param}:{},...r===void 0?{}:{statusCode:r}})}function pl({sessionId:e,nonce:t,billingApiUrl:n,telemetry:r,theme:o="modern-light",containerStyle:a,loading:l=null,onReady:c,onComplete:f,onDecline:y,onCancel:p,onValidation:b,onError:h}){let[w,B]=(0,gt.useState)(null),[N,de]=(0,gt.useState)(null),[K,I]=(0,gt.useState)(null),[re,q]=(0,gt.useState)(null),[ie,se]=(0,gt.useState)(null),ee=(0,gt.useRef)(!1),Oe=(0,gt.useRef)(!1),ue=(0,gt.useMemo)(()=>typeof o=="object"?void 0:(0,zn.resolveTheme)(o),[o]),Ct=(0,gt.useMemo)(()=>typeof o=="object"?o:ue?Ca({appearance:ue.appearance,buttonsStyles:ue.buttonsLayout,layout:"default"}):null,[ue,o]),st=(0,gt.useMemo)(()=>Es(ue?.buttonsLayout.cardFormContainer,a),[ue,a]),Se=(0,gt.useMemo)(()=>ue?dl(ue):void 0,[ue]),Re=(0,gt.useRef)(c),he=(0,gt.useRef)(h),te=(0,gt.useRef)(f),Te=(0,gt.useRef)(y),fe=(0,gt.useRef)(p),we=(0,gt.useRef)(b),xe=(0,gt.useRef)(!1),Le=(0,gt.useRef)(!1),_e=(0,gt.useRef)(0);return Re.current=c,he.current=h,te.current=f,Te.current=y,fe.current=p,we.current=b,(0,gt.useEffect)(()=>{let _=_e.current+1;return _e.current=_,()=>{queueMicrotask(()=>{_e.current===_&&(xe.current||Le.current||(Le.current=!0,nt(()=>{fe.current?.({status:"cancelled",sessionId:e})})))})}},[e]),(0,gt.useEffect)(()=>{let _=!0,oe=new Aa.PaymentAPI((0,zn.resolveBillingApiUrl)(n),{telemetry:r});return B(null),de(null),I(null),xe.current=!1,Le.current=!1,(async()=>{try{if(!e.trim())throw new zn.FloPayError("FloPayCardSetup requires a sessionId.","validation_error",{code:"MissingCheckoutSessionId",param:"sessionId"});if(!t.trim())throw new zn.FloPayError("FloPayCardSetup requires a session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let me=await oe.getUnifiedCheckoutSession(e,t);if(!_)return;let J=me.data.session;if(!J||!(0,zn.isCardSetupCheckoutSession)(J))throw new zn.FloPayError("FloPayCardSetup only accepts a zero-amount, productless setup session.","validation_error",{code:"InvalidCardSetupSession",param:"sessionId"});let O=J.vault;if(O?.html?.trim()||(O=await oe.getVaultCapture(e,t)),!O.html?.trim())throw new zn.FloPayError("FloPay: this setup session has no vault card capability. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});if(!_)return;de(O),B(new Aa.PciVaultCardCapture({sessionId:e,operation:"card_setup",telemetry:r}))}catch(me){if(!_)return;let J=ul(me);xe.current=!0,I(J),nt(()=>he.current?.(J))}})(),()=>{_=!1,oe.destroy()}},[n,t,e,r]),(0,gt.useEffect)(()=>{if(!w)return;let _=!1;Oe.current=!1,ee.current=!1;let oe=w.on("submitting",()=>{ee.current=!0,se(null),q("processing")}),me=w.on("complete",O=>{xe.current=!0,ee.current=!1,q("success"),(async()=>(await new Promise(Ce=>setTimeout(Ce,1200)),!Oe.current&&(Oe.current=!0,nt(()=>{te.current?.({status:"succeeded",sessionId:e,...O.paymentMethod?{paymentMethod:O.paymentMethod}:{}})}),_||q(null))))()}),J=w.on("decline",O=>{xe.current=!0,ee.current=!1,se(O.message??null),q("error"),nt(()=>{Te.current?.({status:"declined",sessionId:e,...O.declineReason?{reason:O.declineReason}:{},...O.message?{message:O.message}:{}})}),(async()=>(await new Promise(Ce=>setTimeout(Ce,1500)),_||q(null)))()});return()=>{_=!0,oe(),me(),J()}},[w,e]),K?(0,gr.jsx)("div",{role:"alert",children:K.message}):!w||!N?.html?(0,gr.jsx)(gr.Fragment,{children:l}):(0,gr.jsxs)(gr.Fragment,{children:[re&&(0,gr.jsx)(Xn,{status:re,errorMessage:ie,processingLabel:"SAVING CARD...",successLabel:"CARD SAVED",errorLabel:"CARD NOT SAVED",successNote:null,...Se?{theme:Se}:{}}),(0,gr.jsx)(mo,{capture:w,html:N.html,messageToken:N.messageToken,expectedOrigin:N.expectedOrigin,theme:Ct,containerStyle:st,onReady:()=>{nt(()=>Re.current?.())},onValidation:_=>{nt(()=>we.current?.(_))},onError:_=>{if(!_)return;ee.current&&(ee.current=!1,se(_),q("error"),setTimeout(()=>q(null),1500));let oe=ul(new Error(_),{code:"card_setup_widget_failed",retryable:!0});nt(()=>he.current?.(oe))}})]})}0&&(module.exports={DirectPayPalButton,FloPayAutomaticPaymentButton,FloPayCardSetup,FloPayCardSetupError,FloPayCheckout,FloPayProvider,SplitCardForm,VaultCardFields,dropThirdPartyOnlyError,useCheckout,useFloPay,usePayPalFloPay});