@flopay/react 1.4.23 → 1.4.24
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/README.md +12 -0
- package/dist/card-setup-entry.cjs +6 -0
- package/dist/card-setup-entry.d.cts +75 -0
- package/dist/card-setup-entry.d.ts +75 -0
- package/dist/card-setup-entry.mjs +1 -0
- package/dist/chunk-P5QXEIBB.mjs +6 -0
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +3 -73
- package/dist/index.d.ts +3 -73
- package/dist/index.mjs +8 -13
- package/package.json +8 -3
package/dist/index.mjs
CHANGED
|
@@ -1,12 +1,7 @@
|
|
|
1
|
-
import{useCallback as As,useEffect as $r,useState as Qo,useMemo as Bs,useRef as Zo}from"react";import{resolveBillingApiUrl as Fs}from"@flopay/shared";import{createContext as li}from"react";var Mn=li({flopay:null,paypalFlopay:null,elements:null,billingApiUrl:""}),yn=li({session:null,loading:!1,error:null});var _s=Symbol.for("@flopay/js.telemetry.bridge.v1"),xs=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function Ts(){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:()=>{},flush:async()=>{},destroy:()=>{}}}function Ms(e){let t=Ts(),n=(r,i)=>r?r.bind(e):i,a=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:a,elapsed:e.elapsed?e.elapsed.bind(e):r=>Math.max(0,a()-r),setCheckoutContext:n(e.setCheckoutContext,t.setCheckoutContext),beginCheckout:n(e.beginCheckout,t.beginCheckout),disable:n(e.disable,t.disable),flush:n(e.flush,t.flush),destroy:n(e.destroy,t.destroy)}}function fo(e){let t=globalThis[xs];return Ms(t?.(e)??{})}function At(e){if(e)return e[_s]}import{jsx as Ds}from"react/jsx-runtime";function go({flopay:e,paypalFlopay:t,options:n,children:a}){let[r,i]=Qo(e instanceof Promise?null:e),[c,l]=Qo(t instanceof Promise||!t?null:t),[b,x]=Qo(null),g=Zo(null),w=Zo(null),v=Zo(null);$r(()=>{if(!r)return;let k=At(r);return g.current=k?.beginCheckout()??k?.now()??0,k?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{k?.log({name:"checkout.unmount",stage:"unmount"})}},[r]),$r(()=>{let k=!1;return e instanceof Promise?e.then(E=>{k||i(E)}):i(e),()=>{k=!0}},[e]),$r(()=>{let k=!1;if(!t){l(null);return}return t instanceof Promise?t.then(E=>{k||l(E)}):l(t),()=>{k=!0}},[t]),$r(()=>{if(!r){x(null);return}let k=r.elements({appearance:n?.appearance,clientSecret:n?.clientSecret,amount:n?.amount,currency:n?.currency,paymentMethodCreation:n?.paymentMethodCreation,setupFutureUsage:n?.setupFutureUsage});return x(k),()=>{k.destroy()}},[r,n?.appearance,n?.clientSecret,n?.amount,n?.currency,n?.paymentMethodCreation,n?.setupFutureUsage]),$r(()=>{if(!r||!b||w.current===b)return;w.current=b;let k=At(r);k?.log({name:"checkout.rendered",stage:"checkout_render"}),k?.performance({stage:"checkout_render",durationMs:k.elapsed(g.current??0),durationMode:"machine"})},[b,r]);let R=As(()=>{if(!r||!b||v.current===b)return;v.current=b;let k=At(r);k?.log({name:"checkout.interactive",stage:"checkout_interactive"}),k?.performance({stage:"checkout_interactive",durationMs:k.elapsed(g.current??0),durationMode:"machine"})},[b,r]),d=Fs(n?.billingApiUrl),h=Bs(()=>({flopay:r,paypalFlopay:c,elements:b,billingApiUrl:d,reportInteractive:R}),[r,c,b,d,R]);return Ds(Mn.Provider,{value:h,children:a})}import Ca,{useCallback as ar,useEffect as Fn,useMemo as gn,useRef as Nt,useState as Ct}from"react";import{PaymentAPI as Ao,SESSION_CREATE_TELEMETRY as Nl}from"@flopay/js";import{SDK_VERSION as ns,FloPayError as It,classifyTelemetryFailure as Gi,isDetachedSessionEligible as Ul,resolveBillingApiUrl as $l,buildCheckoutDisplayData as Ji,resolveButtonsLayoutTheme as ql,resolveIdempotencyKey as Xi,resolveTheme as rs,telemetryStatusClass as Vl}from"@flopay/shared";import"react";import{Fragment as pr,jsx as sn,jsxs as ci}from"react/jsx-runtime";function Ls(){return ci(pr,{children:[ci("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:[sn("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),sn("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",sn("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:sn("path",{d:"M9 18l6-6-6-6"})})]})}function zs(){return sn(pr,{children:"Go back"})}function Os(){return sn(pr,{children:"Secure card checkout"})}function cr(e){return e!==void 0&&(e===""||e===null||e===!1)}function dr({content:e}){return sn(pr,{children:e===void 0?sn(Ls,{}):e})}function ur({content:e}){return sn(pr,{children:e===void 0?sn(zs,{}):e})}function qr({content:e}){return sn(pr,{children:e===void 0?sn(Os,{}):e})}import{ExpressCheckoutElement as zi,PaymentElement as tl,Elements as rr,useElements as ya,useStripe as fa}from"@stripe/react-stripe-js";import{isAuthorizationOnlySession as ca,normalizeCheckoutFailureOutcome as nl,resolveButtonsLayoutTheme as rl,getPostalCodeLabel as pa,getStateLabel as Ri,getStateOptions as ol,COUNTRY_OPTIONS as al,resolveAVSConfig as il,isAVSFieldVisible as Le,getStateFromPostalCode as Ei,isPostalCodeSupported as sl,isValidPostalCode as ll,getPostalCodeExample as cl,filterStripeMethodsByCountry as dl,getStripeMethodDisplayName as Cr,hasVendoredStripeMethodLogo as ul,needsStripeMethodExplicitConfirm as Ii,resolveStripeMethodBrandVariant as pl,partitionStripeMethods as ml,stripeExpressMethodToOptionKey as _i}from"@flopay/shared";function mr(e,t=.12){let n=/^#?([0-9a-fA-F]{6})$/.exec(e.trim());if(!n)return e;let a=parseInt(n[1],16),r=Math.max(0,Math.min(1,1-t)),i=Math.round((a>>16&255)*r),c=Math.round((a>>8&255)*r),l=Math.round((a&255)*r);return`#${(1<<24|i<<16|c<<8|l).toString(16).slice(1)}`}function ea(e){if(typeof e=="number"||typeof e=="string")return e}function ho({appearance:e,buttonsStyles:t,layout:n="default"}){let a=e?.variables,r=x=>typeof x=="string"&&x?x:void 0,i=t.submitButton,c=r(a?.colorPrimary)??r(i?.backgroundColor)??"#4A49FF",l=n==="buttons",b=t.nameInput;return{primaryColor:c,primaryHoverColor:r(a?.colorPrimaryHover)??mr(c,.12),inputBackgroundColor:r(t.cardInputBackground)??r(a?.colorBackground)??"#ffffff",textColor:r(t.cardInputColor)??r(b?.color)??r(a?.colorText)??"#262833",borderColor:r(t.cardInputBorder)??(l?"#e5e7eb":"#A4A4FF"),placeholderColor:r(t.cardInputPlaceholderColor)??"#9ca3af",errorColor:r(a?.colorDanger)??"#dc2626",successColor:"#16a34a",fontFamily:r(b?.fontFamily)??r(a?.fontFamily)??"Poppins, sans-serif",fontSize:r(t.cardInputFontSize)??r(a?.fontSizeBase)??"16px",fontWeight:String(ea(b?.fontWeight)??400),borderRadius:r(a?.borderRadius)??"8px"}}import{PaymentAPI as qn,toStripeAppearance as yl}from"@flopay/js";import{useEffect as di,useRef as Vr}from"react";import{jsx as Ns}from"react/jsx-runtime";function jr({capture:e,html:t,messageToken:n,expectedOrigin:a,theme:r,containerStyle:i,onReady:c,onError:l,onValidation:b}){let x=Vr(null),g=Vr(c),w=Vr(l),v=Vr(b);g.current=c,w.current=l,v.current=b;let R=Vr(r);return R.current=r,di(()=>{let d=x.current;if(!d)return;let h=!0,k=!1,E=()=>{!h||k||(k=!0,g.current?.())},f=e.on("ready",()=>{E()}),de=e.on("error",Z=>{w.current?.(Z.message??"There was a problem loading the secure card form.")}),S=e.on("validation",Z=>{v.current?.(Z.message??null)}),le={html:t,...n?{messageToken:n}:{},...a?{expectedOrigin:a}:{},...R.current?{theme:R.current}:{}};return e.mount(d,le).then(()=>{E()}).catch(Z=>{h&&w.current?.(Z instanceof Error?Z.message:"Failed to load the secure card form.")}),()=>{h=!1,f(),de(),S(),e.unmount()}},[e,t,n,a]),di(()=>{r&&e.applyTheme?.(r)},[e,r]),Ns("div",{ref:x,"data-testid":"flopay-vault-card-fields",style:i})}import"react";import{jsx as ui,jsxs as Us}from"react/jsx-runtime";function yr({children:e,margin:t,icon:n=!0,styleOverride:a}){return Us("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"}:{},...a??{}},children:[n&&ui("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:ui("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 pi={alipay:new URL("./payment-logos/alipay.svg",import.meta.url).href,bancontact:new URL("./payment-logos/bancontact.svg",import.meta.url).href,blik:new URL("./payment-logos/blik.svg",import.meta.url).href,eps:new URL("./payment-logos/eps.svg",import.meta.url).href,giropay:new URL("./payment-logos/giropay.svg",import.meta.url).href,ideal:new URL("./payment-logos/ideal.svg",import.meta.url).href,klarna:new URL("./payment-logos/klarna.svg",import.meta.url).href,p24:new URL("./payment-logos/p24.svg",import.meta.url).href,sepa_debit:new URL("./payment-logos/sepa_debit.svg",import.meta.url).href,wechat_pay:new URL("./payment-logos/wechat_pay.svg",import.meta.url).href};import fl,{useCallback as ke,useContext as gl,useEffect as pt,useMemo as ut,useRef as De,useState as we}from"react";import{useContext as Hr}from"react";import{resolveBillingApiUrl as $s}from"@flopay/shared";function wn(){return Hr(Mn).flopay}function ta(){return Hr(Mn).paypalFlopay??null}function na(){return Hr(Mn).elements}function qs(){return Hr(yn)}function Po(){return Hr(Mn).billingApiUrl||$s()}import"react";import{jsx as ln,jsxs as fr}from"react/jsx-runtime";var fn=1200,Jt=1500;function cn({status:e,errorMessage:t,authorized:n=!1,processingLabel:a="PROCESSING...",successLabel:r,errorLabel:i="PAYMENT FAILED",successNote:c="You will be automatically redirected, do not close or navigate away from this window."}){return ln("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:fr("div",{style:{background:"white",borderRadius:12,padding:"2rem 2.5rem",textAlign:"center",boxShadow:"0 8px 32px rgba(0,0,0,0.18)",minWidth:240,display:"flex",flexDirection:"column",alignItems:"center",gap:16},children:[fr("div",{style:{width:48,height:48,position:"relative"},children:[e==="processing"&&fr("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:{animation:"flopay-spin 0.8s linear infinite"},children:[ln("circle",{cx:"12",cy:"12",r:"10",stroke:"#e5e7eb",strokeWidth:"3"}),ln("path",{d:"M4 12a8 8 0 018-8v3a5 5 0 00-5 5H4z",fill:"#4A49FF"})]}),e==="success"&&ln("div",{style:{animation:"flopay-pop 0.4s cubic-bezier(0.34,1.56,0.64,1)"},children:fr("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[ln("circle",{cx:"12",cy:"12",r:"11",fill:"#22c55e"}),ln("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"&&ln("div",{style:{animation:"flopay-shake 0.4s ease"},children:fr("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[ln("circle",{cx:"12",cy:"12",r:"11",fill:"#ef4444"}),ln("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"}})]})})]}),fr("span",{style:{fontSize:14,fontWeight:600,letterSpacing:"0.05em",color:e==="success"?"#16a34a":e==="error"?"#dc2626":"#374151"},children:[e==="processing"&&a,e==="success"&&(r??(n?"PAYMENT AUTHORISED":"PAYMENT SUCCESSFUL")),e==="error"&&i]}),e==="success"&&c!==null&&ln("p",{style:{fontSize:13,color:"#6b7280",fontWeight:400,maxWidth:260,lineHeight:1.4,margin:0},children:c}),e==="error"&&t&&ln("p",{style:{fontSize:13,color:"#6b7280",fontWeight:400,maxWidth:260,lineHeight:1.4,margin:0},children:t}),ln("style",{children:`
|
|
2
|
-
@keyframes flopay-spin { to { transform: rotate(360deg); } }
|
|
3
|
-
@keyframes flopay-pop { 0% { transform: scale(0); } 100% { transform: scale(1); } }
|
|
4
|
-
@keyframes flopay-draw { to { stroke-dashoffset: 0; } }
|
|
5
|
-
@keyframes flopay-shake { 0%,100% { transform: translateX(0); } 20%,60% { transform: translateX(-4px); } 40%,80% { transform: translateX(4px); } }
|
|
6
|
-
`})]})})}import{FloPayError as mi,isMoneySettledOutcome as Vs,isSetupIntentClientSecret as Cd}from"@flopay/shared";function yi(e,t){return t?e?{account:{...e.account??{},...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}:t:e}function ra(e,t){return t?{...e,account:{...e.account,...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}:e}function fi(e,t){let n=e.products??[...(e.subscriptions??[]).map(i=>({type:"subscription",code:i.code??i.providerPlanId,name:i.subscriptionName??i.providerPlanName??i.code??i.providerPlanId??null,quantity:i.quantity??1,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount,currency:i.currency,metadata:i.metadata})),...(e.items??[]).map(i=>({type:"item",code:i.code??i.providerItemId,name:i.itemName??i.providerItemName??i.code??i.providerItemId??null,quantity:i.quantity??1,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount,currency:i.currency,metadata:i.metadata}))],a=n.reduce((i,c)=>i+(c.overrideAmount??c.totalAmount??0),0),r=e.currency??n.find(i=>i.currency)?.currency??"USD";return{id:"",clientSecret:"",mode:n.some(i=>i.type==="subscription")?"subscription":"payment",amount:Math.round(a*100),currency:r,status:"open",captureMethod:e.captureMethod,customer:{id:e.account.userId,email:e.account.email??"",firstName:e.account.firstName,lastName:e.account.lastName,gender:e.account.gender??void 0,city:e.account.city??void 0,state:e.account.state??void 0,country:e.account.country??void 0,zip:e.account.zip??void 0},successUrl:e.successUrl,cancelUrl:e.cancelUrl,checkoutMode:t??e.checkoutMode??"full",products:n.map((i,c)=>({uuid:`synthetic-${i.type??"item"}-${c}`,checkoutSessionId:"",type:i.type??"item",code:i.code,name:i.name??null,quantity:i.quantity??1,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount??null,currency:i.currency??r,metadata:i.metadata??null}))}}function oa(e,t){return t?{...e,...t}:e}function Et(e,t,n){let a=typeof t=="string"?t:t.message,r=typeof t=="string"?n?.code:n?.code??t.code,i=typeof t=="string"?n?.declineCode:n?.declineCode??t.declineCode;return{method:e,message:a,...r?{code:r}:{},...i?{declineCode:i}:{}}}var js=[{match:/^paypal authorization required\.?$/i,replacement:"For your additional security, please re-authenticate this payment via PayPal."}];function Un(e){if(typeof e!="string")return e??void 0;let t=e.trim();if(!t)return e;for(let{match:n,replacement:a}of js)if(n.test(t))return a;return e}function er(e,t){return e.status!=="authorized"?{status:"succeeded"}:{status:"authorized",paymentId:e.paymentId,sessionId:e.id||t||void 0,authorizationExpiresAt:e.authorizationExpiresAt}}function gr(e){return e?.status==="authorized"||e?.status==="complete"}function gi(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function bo(e){let t=gi(e);return new mi(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function vo(e){let t=gi(e);return new mi(t?"Authorization has expired.":"Automatic payment failed. Please try again.","api_error",{code:t?"authorization_expired":e?.status==="expired"?"checkout_session_expired":"checkout_processing_timeout"})}function Co(e,t){return e==="processing"||Vs(e,t)}function hi(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}function Pi(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?{mode:"setup"}:{mode:"payment",amount:e}}function Kr(e){let t=[e?.id,e?.originalPaymentMethodId];for(let n of t)if(typeof n=="string"&&n.startsWith("pm_"))return n}var So="flopay_recent_completion_";function hr(e){if(!(!e||typeof window>"u"))try{let t={expiresAt:Date.now()+6e4};window.sessionStorage.setItem(So+e,JSON.stringify(t))}catch{}}function aa(e){if(!e||typeof window>"u")return!1;try{let t=window.sessionStorage.getItem(So+e);if(!t)return!1;let n=JSON.parse(t);return typeof n?.expiresAt!="number"||n.expiresAt<=Date.now()?(window.sessionStorage.removeItem(So+e),!1):!0}catch{return!1}}function bi(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}import{useCallback as wo,useEffect as ht,useMemo as Yr,useRef as et,useState as nr}from"react";import{loadScript as Ks}from"@paypal/paypal-js";import{PaymentAPI as ia}from"@flopay/js";import{FloPayError as vi,SDK_VERSION as Ws,generateIdempotencyKey as Ys,normalizeGatewayEnvironment as Gs}from"@flopay/shared";function Ke(e){if(!e)return;let t=n=>{console.error("[FloPay] Merchant callback failed; checkout continued.",n)};try{Promise.resolve(e()).catch(t)}catch(n){t(n)}}function Hs(e){if(e instanceof Error)return e.message;if(typeof e=="object"&&e!==null){let t=e.message;return typeof t=="string"?t:void 0}return typeof e=="string"?e:void 0}function tr(e){if(typeof e!="string")return;let t=e.trim();return/^[a-z0-9_.-]{1,64}$/i.test(t)?t:void 0}function An(e){if(typeof e!="object"||e===null)return;let t=e;return tr(t.code)??tr(t.type)??tr(t.name)}function Pr(e){if(!(typeof e!="object"||e===null))return tr(e.decline_code)}function Wr(e){return typeof e!="object"||e===null?!1:tr(e.type)?.toLowerCase()==="card_error"||Pr(e)!==void 0}function $n(e){let t=Hs(e)?.toLowerCase()??"",a=`${An(e)?.toLowerCase()??""} ${t}`;return a.includes("popup")&&a.includes("block")}import{jsx as br,jsxs as sa}from"react/jsx-runtime";var ko=45,Js=1e3,Xs=11e3,Qs=["https://www.paypal.com","https://www.sandbox.paypal.com"],Ci="We couldn't open PayPal. Try again or choose another payment method.",Zs={width:"100%",minHeight:ko,margin:"0 0 0.5rem",padding:"0.75rem 0.875rem",border:"1px solid #2563eb",borderRadius:8,background:"#eff6ff",color:"#1d4ed8",fontSize:"0.95rem",fontWeight:700,cursor:"pointer"};function Si(e){return e.includes("No ack for postMessage init()")&&Qs.some(t=>e.includes(t))&&e.includes("10000ms")}function el(e){return e?`${Ci} Allow pop-ups for this site, then try again.`:Ci}function wi({sessionId:e,nonce:t,billingApiUrl:n,email:a,clientId:r,environment:i,currency:c,isSubscription:l,onTokenizedBody:b,onComplete:x,onErrorChange:g,onDecline:w,onTechnicalFailure:v,isProcessing:R=!1,onLoadStateChange:d,onInitializationStateChange:h,allowAutomaticRetry:k=!0,onButtonClick:E,runBeforeButtonClick:f,session:de,existingOrderId:S,telemetry:le,telemetryContext:Z,debug:F=!1}){let G=wn(),W=Yr(()=>{if(G)return null;let D=fo({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:Ws,enabled:le!==!1});return D.setCheckoutContext(Z??{}),D.beginCheckout(Z??{}),D},[n,G,le,Z?.checkoutMode,Z?.layout]),oe=Yr(()=>At(G),[G]);ht(()=>()=>{W&&W.flush().catch(()=>{}).finally(()=>W.destroy())},[W]);let N=Yr(()=>({error:D=>{oe?oe.error(D):W?.error(D)},log:D=>{oe?oe.log(D):W?.log(D)},performance:D=>{oe?oe.performance(D):W?.performance(D)},terminal:D=>{oe?oe.terminal(D):W?.terminal(D)},startTiming:()=>oe?.now()??W?.now()??0,elapsed:D=>oe?.elapsed(D)??Math.max(0,(W?.now()??D)-D)}),[oe,W]),j=et(null),ce=et(0),Re=et(null),fe=et(!1),[ae,ee]=nr(!1),[pe,Y]=nr(!1),[K,Ee]=nr(0),ge=et(0),[te,q]=nr(!1),C=et(!1),ie=et(!1),[$e,Oe]=nr(!1),[me,T]=nr(!1),ue=Yr(()=>n.replace(/\/+$/,""),[n]),J=Yr(()=>JSON.stringify([ue,r,c,i??"",l,e,S??""]),[ue,r,c,i,S,l,e]),_e=et(J),mt=_e.current!==J,[Je,yt]=nr([]),A=D=>{F&&yt(it=>[...it,`${new Date().toISOString().slice(11,23)} ${D}`])},X=et(b),tt=et(x),qe=et(g),ft=et(w),Ne=et(v),We=et(E),Xt=et(d),Ge=et(h),Qt=et(f),I=et(de),be=et(a),Ye=et(t),xe=et(null),St=et(0),je=et(null),Ve=et(null),nt=et(new Map),Xe=et(new Map),In=et(!1);ht(()=>(In.current=!0,()=>{In.current=!1}),[]),ht(()=>{X.current=b},[b]),ht(()=>{tt.current=x},[x]),ht(()=>{qe.current=g},[g]),ht(()=>{ft.current=w},[w]),ht(()=>{Ne.current=v},[v]),ht(()=>{We.current=E},[E]),ht(()=>{Xt.current=d},[d]),ht(()=>{Ge.current=h},[h]),ht(()=>{Qt.current=f},[f]),ht(()=>{I.current=de},[de]),ht(()=>{be.current=a},[a]),ht(()=>{Ye.current=t},[t]),ht(()=>{ge.current=K},[K]),ht(()=>{te&&Re.current?.focus()},[te,K]);let at=wo(()=>{window.setTimeout(()=>{Re.current?.focus()},0)},[]),Hn=wo(()=>{ee(!1),Ee(D=>D+1)},[]),Wt=wo(()=>{q(!1),(j.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??j.current)?.focus?.()},[]);ht(()=>{!ae||!fe.current||(fe.current=!1,Wt())},[Wt,ae,K]);let Pn=wo((D,it)=>{let Lt=Ne.current;if(Lt){Lt("paypal",D,it);return}qe.current?.(el(it?.popupBlocked??$n(D)))},[]),Zt=()=>{je.current?.timer&&(clearTimeout(je.current.timer),je.current.timer=null)},ir=()=>{Zt();let D=St.current+1;return St.current=D,Ve.current=null,je.current={generation:D,timer:null,yieldedControl:!1},q(!1),D},Bt=D=>D!==void 0&&je.current?.generation!==D?!1:(Zt(),je.current=null,Ve.current=null,!0),kt=D=>{let it=D?.generation??je.current?.generation??St.current;(!D?.generation||je.current?.generation===it)&&(Zt(),je.current=null),Ve.current=it,D?.showRetry&&q(!0),D?.remount&&Hn(),D?.focus!==!1&&at()},en=D=>je.current?.generation===D&&Ve.current!==D,tn=D=>{typeof document<"u"&&document.visibilityState!=="visible"||(Zt(),D.timer=setTimeout(()=>{je.current?.generation===D.generation&&(je.current=null,Ve.current=D.generation,Pn(new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}),q(!0),Hn(),at())},600))},Ft=()=>{let D=je.current;D?.yieldedControl&&tn(D)},Dt=()=>{let D=je.current;D&&(D.yieldedControl=!0,Zt())},wt=D=>{let it=xe.current;return it&&Xe.current.set(D,it),D};ht(()=>{let D=()=>{document.visibilityState==="visible"?Ft():Dt()};return document.addEventListener("visibilitychange",D),window.addEventListener("focus",Ft),window.addEventListener("blur",Dt),()=>{document.removeEventListener("visibilitychange",D),window.removeEventListener("focus",Ft),window.removeEventListener("blur",Dt),Zt()}},[]),ht(()=>{_e.current!==J&&(_e.current=J,C.current=!1,ie.current=!1,ee(!1),Y(!1),Oe(!1),Ge.current?.("loading"))},[J]),ht(()=>{Ke(()=>Xt.current?.(ae&&!$e))},[ae,$e]);let ne=Gs(i);ht(()=>{let D=r?`${r.slice(0,6)}\u2026(len ${r.length})`:"(empty)",it=typeof navigator<"u"?navigator.userAgent:"(no navigator)";if(A(`mount clientId=${D} env=${i??"(unset)"}\u2192${ne??"live"} ccy=${c} sub=${l}`),A(`ua=${it.slice(0,80)}${it.length>80?"\u2026":""}`),!r){A("FAIL: clientId empty \u2014 gateway misconfigured"),Oe(!0),N.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(!j.current){A("FAIL: containerRef not attached");return}ce.current=N.startTiming(),N.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let Lt=!1,Ln=!1,Be=()=>Lt||Ln,st,He=!1,_n=()=>{st=Ys(),st||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),He=!0},xn=null,zn=!1,Wn=null,Tn=!1,rt=()=>{!Wn||Tn||(Tn=!0,Wn.close().catch(()=>{}))},zt=null,dn=()=>{zt!==null&&(N.log({name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal"}),N.performance({stage:"overlay_return",durationMs:N.elapsed(zt),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal"}),zt=null)},Pt=!1,xt=j.current,nn=null,un=null,Yt=[],Ut=m=>{if(!m||typeof m.getBoundingClientRect!="function")return"(no rect)";let o=m.getBoundingClientRect();return`${Math.round(o.width)}\xD7${Math.round(o.height)}`},$t=m=>{if(!m)return"(empty)";try{let o=new URL(m,typeof window<"u"?window.location.href:"https://localhost"),y=o.pathname.toLowerCase();return y.includes("checkcaptcha")||y.includes("captcha")?`CAPTCHA(${o.host}${y})`:y.includes("risk")||y.includes("challenge")?`RISK(${o.host}${y})`:y.includes("smart/buttons")?`smart-buttons(${o.host})`:`${o.host}${y}`.slice(0,100)}catch{return m.slice(0,80)}},Te=m=>{let o=m.getAttribute("src"),y=m.getAttribute("srcdoc"),B=m.getAttribute("name"),P=m.getAttribute("sandbox"),U=[];return o&&U.push(`src=${$t(o)}`),y&&U.push(`srcdoc[${y.length}ch]`),!o&&!y&&U.push("src=(empty) srcdoc=(empty)"),B&&U.push(`name=${B.slice(0,40)}`),P!==null&&U.push(`sandbox="${P.slice(0,40)}"`),U.join(" ")},qt=m=>{if(!(m instanceof HTMLIFrameElement))return"";try{let o=m.contentDocument;if(!o)return"cd=null";let y=o.body?.children.length??0,B=o.body?.innerHTML.length??0,P=o.head?.innerHTML.length??0;return`cd=same-origin readyState=${o.readyState} body[${y}children,${B}ch] head[${P}ch]`}catch(o){return`cd=cross-origin(${o.message.slice(0,30)})`}},gt=[],bn=m=>{if(Be())return;let o=m.message??String(m.error??"(no message)");o&&(o.toLowerCase().includes("paypal")||o.toLowerCase().includes("zoid")||o.toLowerCase().includes("postrobot")||o.toLowerCase().includes("storage"))&&(A(`window:error ${o.slice(0,140)}`),gt.push(o))},Yn=m=>{if(Be())return;let o=m.reason instanceof Error?m.reason.message:String(m.reason??"(no reason)");o&&(o.toLowerCase().includes("paypal")||o.toLowerCase().includes("zoid")||o.toLowerCase().includes("postrobot")||o.toLowerCase().includes("storage"))&&(A(`window:rejection ${o.slice(0,140)}`),gt.push(o))};F&&typeof window<"u"&&(window.addEventListener("error",bn),window.addEventListener("unhandledrejection",Yn));let Vt={value:0};if(F&&typeof PerformanceObserver<"u")try{un=new PerformanceObserver(m=>{if(!Be())for(let o of m.getEntries()){if(!o.name.toLowerCase().includes("paypal"))continue;Vt.value+=1;let y=Math.round(o.duration);A(`net ${y}ms ${o.name.slice(0,90)}`)}}),un.observe({type:"resource",buffered:!0})}catch{}let jt=()=>{for(nn?.disconnect(),nn=null,un?.disconnect(),un=null;Yt.length;)clearTimeout(Yt.pop());F&&typeof window<"u"&&(window.removeEventListener("error",bn),window.removeEventListener("unhandledrejection",Yn))},Ot=m=>{if(!m)return!1;let o=m.toLowerCase();return o.includes("zoid destroyed")||o.includes("destroyed all components")||o.includes("window closed")||o.includes("detected container element removed")},On=m=>{if(Be()||Ot(m))return;let o=Un(m)??m;Ke(()=>qe.current?.(o))},Nn=m=>{Lt||(Oe(!0),m.includes("paypal_ineligible")||N.error({errorCode:"PROVIDER_LOAD_FAILED",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime"}),console.error("[FloPay] DirectPayPal load/render failure:",m))},rn=(m,o=!1)=>{if(Lt)return;let y=C.current||!k;if(zn)return;zn=!0,Ln=!0,jt(),rt();let B=o||Si(m);if(B&&k&&!C.current){C.current=!0,ee(!1),T(!1),Y(!0),Ge.current?.("retrying"),xn=setTimeout(()=>{Lt||Ee(P=>P+1)},Js);return}if(B||y){if(ee(!1),T(!1),Y(!1),Oe(!0),Ge.current?.("exhausted"),!ie.current){ie.current=!0;let P=Si(m)?"paypal_init_timeout":o?"paypal_render_timeout":"paypal_init_failure";console.error("[FloPay] Direct PayPal initialization failed:",P)}return}Nn(m)};Oe(!1);let Gt=async(m,o=xe.current)=>{if(Be())return;let y=o?.sessionId??e;if(X.current){await X.current(m,{sessionId:y,accountPatch:o?.accountPatch,nonce:o?.nonce});return}let B=N.startTiming();N.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let P=()=>{N.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),N.performance({stage:"processing",durationMs:N.elapsed(B),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})};try{let U=I.current,Fe=o?.accountPatch?.email??be.current,Qe=o?.accountPatch?.userId??U?.customer?.id??U?.accountData?.userId??"",$=await new ia(ue,{telemetry:!1}).processPayment(Qe,{sessionId:y,nonce:o?.nonce??Ye.current,tokenizedData:m,accountData:{userId:Qe,email:Fe??U?.customer?.email??"",firstName:o?.accountPatch?.firstName??U?.customer?.firstName??U?.accountData?.firstName??"",lastName:o?.accountPatch?.lastName??U?.customer?.lastName??U?.accountData?.lastName??"",country:o?.accountPatch?.country??U?.customer?.country??U?.accountData?.country??void 0,zip:o?.accountPatch?.zip??U?.customer?.zip??U?.accountData?.zip??void 0}});if($.ok){if(Ln||Lt&&In.current)return;P(),N.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),Ke(()=>tt.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(Be())return;let p=await $.json().catch(()=>null),O=p?.message??"PayPal payment failed.",he=Un(O)??O;P(),$.status===400&&(typeof p?.declineCode=="string"||!Array.isArray(p?.fields))?N.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):$.status===400||$.status===422?N.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx"}):N.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:$.status>=500?"5xx":$.status>=400?"4xx":$.status>=300?"3xx":"unknown",failureCategory:$.status>=500?"server_error":void 0}),On(he),Ke(()=>ft.current?.(Et("paypal",he,{code:p?.code,declineCode:p?.declineCode})));return}catch(U){if(Be())return;P(),N.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let Fe=U instanceof Error?U.message:"PayPal payment failed.",Qe=Un(Fe)??Fe;On(Qe),Ke(()=>ft.current?.(Et("paypal",Qe)));return}},on=()=>new vi("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),Ue=m=>Be()?Promise.reject(on()):Promise.resolve(m),_=async m=>{if(Be())throw on();He||_n();let o=xe.current,y=o?.sessionId??e,B=o?.nonce??Ye.current;N.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let P=await new ia(ue,{telemetry:!1}).createSessionIntent(y,B??"",{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"},{idempotencyKey:st});if(Be())throw on();if(P.provider!=="paypal")throw new Error(m);return N.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),P.providerObjectId},z=(m,o)=>{let y=o?.nonce??Ye.current;if(!y)return;let B=o?.sessionId??e,P=Pr(m)??An(m)??"provider_declined";new ia(ue,{telemetry:!1}).reportSessionIntentDecline(B,y,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:P}).catch(()=>{})},M=K;A("loadScript:scheduled (deferred 1 tick)");let ve=null,Ce=setTimeout(()=>{if(Lt){A("loadScript:skipped (cancelled before defer ran)");return}A("loadScript:start");let m=ne==="live"?"production":ne;ve=Ks({clientId:r,currency:c,intent:l?"subscription":"capture",vault:l?!0:void 0,...m?{environment:m}:{},...m==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}}),ve.then(o=>{if(A(`loadScript:resolved inactive=${Be()} ns=${!!o} buttons=${!!o?.Buttons}`),Be())return;if(!o?.Buttons){A("FAIL: namespace missing Buttons factory"),rn("PayPal SDK did not expose the Buttons factory.");return}N.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),N.performance({stage:"provider_ready",durationMs:N.elapsed(ce.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),N.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let y=async Q=>{if(Be()||ge.current!==M)return;let $=Q.subscriptionID??Q.orderID??"",p=$?Xe.current.get($):nt.current.get(M);if(!(!p||!en(p.generation))&&Bt(p.generation)){Xe.current.delete($),nt.current.delete(p.surfaceKey),dn();try{if(T(!0),Ke(()=>qe.current?.(null)),!$)throw new vi("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});await Gt({id:$,isPaypal:!0},p)}catch(O){On(O instanceof Error?O.message:"PayPal capture failed.")}finally{Be()||T(!1)}}},B=o.Buttons({style:{layout:"horizontal",height:ko,tagline:!1},onClick:async(Q,$)=>{if(Be()){await $.reject();return}_n();let p=Qt.current,O={};if(p)try{let Me=await p("paypal");if(Be()){await $.reject();return}if(!Me.proceed){xe.current=null,nt.current.delete(M),await $.reject();return}O={sessionId:Me.sessionId,accountPatch:Me.accountPatch,nonce:Me.nonce}}catch(Me){A(`onClick:runBeforeButtonClick rejected msg=${(Me instanceof Error?Me.message:String(Me)).slice(0,120)}`),xe.current=null,nt.current.delete(M),await $.reject();return}Ke(()=>We.current?.("paypal"));let Ie={generation:ir(),surfaceKey:M,...O};xe.current=Ie,nt.current.set(M,Ie),await $.resolve(),N.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),N.log({name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),N.log({name:"provider.overlay.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),zt=N.startTiming()},createOrder:l?void 0:S?()=>Ue(S).then(wt):()=>_("Failed to create PayPal order.").then(wt),createSubscription:l?S?()=>Ue(S).then(wt):()=>_("Failed to create PayPal subscription.").then(wt):void 0,onApprove:y,onCancel:()=>{if(Be())return;let Q=nt.current.get(M)??xe.current;Q&&nt.current.delete(Q.surfaceKey),xe.current=null,dn(),N.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),fe.current=!0,kt({generation:Q?.generation,remount:!0,focus:!1})},onError:Q=>{if(Be()||ge.current!==M)return;let $=Q instanceof Error?Q.message:"PayPal failed to render.";if(A(`onError rendered=${Pt} msg=${$.slice(0,120)}`),Pt){let p=nt.current.get(M)??xe.current;if(p&&!en(p.generation)||!p&&Ve.current===St.current)return;if(Ot($)){Bt(p?.generation);return}if(dn(),Wr(Q)){N.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),z(Q,p),Ke(()=>ft.current?.(Et("paypal",$))),p&&nt.current.delete(p.surfaceKey),xe.current=null,Bt(p?.generation);return}let O=$.toLowerCase();N.error({errorCode:O.includes("popup")&&O.includes("block")?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),p&&nt.current.delete(p.surfaceKey),xe.current=null,kt({generation:p?.generation,remount:!0,showRetry:!0,focus:!0}),Pn(Q,{code:"paypal_runtime_failed"});return}rn($)}}),P=B.isEligible();if(A(`isEligible=${P}`),N.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!P){ee(!1),rn("PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}Wn=B,F&&A(`container:dims ${Ut(xt)} visibility=${typeof document<"u"?document.visibilityState:"(no document)"}`),F&&typeof MutationObserver<"u"&&(nn=new MutationObserver(Q=>{if(!Be()){for(let $ of Q)if($.type==="childList")$.addedNodes.forEach(p=>{if(!(p instanceof Element))return;let O=p.tagName.toLowerCase(),he=(p.getAttribute("title")??"").slice(0,40),Ie=O==="iframe"?` ${Te(p)}`:"";A(`child+ ${O}${he?` title="${he}"`:""}${Ie} dims=${Ut(p)}`)});else if($.type==="attributes"&&$.target instanceof Element){let p=$.target;if(p.tagName.toLowerCase()!=="iframe")continue;let O=$.attributeName;(O==="src"||O==="srcdoc")&&A(`attr~ iframe ${O}=${O==="srcdoc"?`[${(p.getAttribute("srcdoc")??"").length}ch]`:$t(p.getAttribute("src"))} dims=${Ut(p)}`)}}}),nn.observe(xt,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let Fe=Q=>{if(Be()||Pt)return;let $=xt.querySelectorAll("iframe"),p=typeof document<"u"&&"hasStorageAccess"in document;A(`watchdog:${Q} container=${Ut(xt)} children=${xt.childElementCount} iframes=${$.length} visibility=${typeof document<"u"?document.visibilityState:"(no document)"} cookies=${typeof navigator<"u"?navigator.cookieEnabled:"?"} hasStorageAccessApi=${p} paypalNetRequests=${Vt.value}`),$.forEach((O,he)=>{let Ie=(O.getAttribute("title")??"").slice(0,40);A(` iframe[${he}] ${Ut(O)}${Ie?` title="${Ie}"`:""} ${Te(O)}`);let Me=qt(O);Me&&A(` ${Me}`)}),gt.length===0&&A(" (no PayPal/zoid window errors captured)")};F&&(Yt.push(setTimeout(()=>Fe("3s"),3e3)),Yt.push(setTimeout(()=>Fe("8s"),8e3)),Yt.push(setTimeout(()=>Fe("15s"),15e3))),A("render:start");let Qe=N.startTiming();Yt.push(setTimeout(()=>{Be()||Pt||(A("watchdog:11s retryable render timeout"),rn("PayPal Buttons render did not settle within 11000ms.",!0))},Xs)),B.render(xt).then(()=>{if(A(`render:resolved inactive=${Be()}`),jt(),Be()){rt();return}Pt=!0,ee(!0),Y(!1),Ge.current?.("ready"),N.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),N.performance({stage:"checkout_render",durationMs:N.elapsed(Qe),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}).catch(Q=>{let $=Q instanceof Error?Q.message:"PayPal failed to render.";A(`render:rejected msg=${$.slice(0,120)}`),jt(),rn($)})}).catch(o=>{let y=o instanceof Error?o.message:"PayPal SDK failed to load.";A(`loadScript:rejected msg=${y.slice(0,120)}`),rn(y)})},0);return()=>{Lt=!0,clearTimeout(Ce),xn&&clearTimeout(xn),jt(),rt()}},[k,ue,r,c,i,l,e,S,K,N]);let Kn=F?sa("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:$e?"#fef2f2":"#f3f4f6",border:`1px solid ${$e?"#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=${ae} failed=${$e})`,Je.length===0?`
|
|
1
|
+
import{a as qo,b as ut,c as _n,d as Pn,e as bn,f as Lr,g as Xa,h as Qa,i as gs,j as hs}from"./chunk-P5QXEIBB.mjs";import{useCallback as Ss,useEffect as zr,useState as jo,useMemo as ws,useRef as Ko}from"react";import{resolveBillingApiUrl as ks}from"@flopay/shared";import{createContext as Za}from"react";var xn=Za({flopay:null,paypalFlopay:null,elements:null,billingApiUrl:""}),un=Za({session:null,loading:!1,error:null});var Ps=Symbol.for("@flopay/js.telemetry.bridge.v1"),bs=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function vs(){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:()=>{},flush:async()=>{},destroy:()=>{}}}function Cs(e){let t=vs(),n=(a,i)=>a?a.bind(e):i,s=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:s,elapsed:e.elapsed?e.elapsed.bind(e):a=>Math.max(0,s()-a),setCheckoutContext:n(e.setCheckoutContext,t.setCheckoutContext),beginCheckout:n(e.beginCheckout,t.beginCheckout),disable:n(e.disable,t.disable),flush:n(e.flush,t.flush),destroy:n(e.destroy,t.destroy)}}function so(e){let t=globalThis[bs];return Cs(t?.(e)??{})}function At(e){if(e)return e[Ps]}import{jsx as Rs}from"react/jsx-runtime";function lo({flopay:e,paypalFlopay:t,options:n,children:s}){let[a,i]=jo(e instanceof Promise?null:e),[u,l]=jo(t instanceof Promise||!t?null:t),[v,N]=jo(null),h=Ko(null),E=Ko(null),C=Ko(null);zr(()=>{if(!a)return;let k=At(a);return h.current=k?.beginCheckout()??k?.now()??0,k?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{k?.log({name:"checkout.unmount",stage:"unmount"})}},[a]),zr(()=>{let k=!1;return e instanceof Promise?e.then(T=>{k||i(T)}):i(e),()=>{k=!0}},[e]),zr(()=>{let k=!1;if(!t){l(null);return}return t instanceof Promise?t.then(T=>{k||l(T)}):l(t),()=>{k=!0}},[t]),zr(()=>{if(!a){N(null);return}let k=a.elements({appearance:n?.appearance,clientSecret:n?.clientSecret,amount:n?.amount,currency:n?.currency,paymentMethodCreation:n?.paymentMethodCreation,setupFutureUsage:n?.setupFutureUsage});return N(k),()=>{k.destroy()}},[a,n?.appearance,n?.clientSecret,n?.amount,n?.currency,n?.paymentMethodCreation,n?.setupFutureUsage]),zr(()=>{if(!a||!v||E.current===v)return;E.current=v;let k=At(a);k?.log({name:"checkout.rendered",stage:"checkout_render"}),k?.performance({stage:"checkout_render",durationMs:k.elapsed(h.current??0),durationMode:"machine"})},[v,a]);let F=Ss(()=>{if(!a||!v||C.current===v)return;C.current=v;let k=At(a);k?.log({name:"checkout.interactive",stage:"checkout_interactive"}),k?.performance({stage:"checkout_interactive",durationMs:k.elapsed(h.current??0),durationMode:"machine"})},[v,a]),c=ks(n?.billingApiUrl),P=ws(()=>({flopay:a,paypalFlopay:u,elements:v,billingApiUrl:c,reportInteractive:F}),[a,u,v,c,F]);return Rs(xn.Provider,{value:P,children:s})}import ua,{useCallback as rr,useEffect as An,useMemo as pn,useRef as Ot,useState as bt}from"react";import{PaymentAPI as ko,SESSION_CREATE_TELEMETRY as _l}from"@flopay/js";import{SDK_VERSION as Hi,FloPayError as Et,classifyTelemetryFailure as Oi,isDetachedSessionEligible as xl,resolveBillingApiUrl as Tl,buildCheckoutDisplayData as Ui,resolveButtonsLayoutTheme as Ml,resolveIdempotencyKey as $i,resolveTheme as Wi,telemetryStatusClass as Al}from"@flopay/shared";import"react";import{Fragment as dr,jsx as an,jsxs as ei}from"react/jsx-runtime";function Is(){return ei(dr,{children:[ei("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:[an("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),an("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",an("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:an("path",{d:"M9 18l6-6-6-6"})})]})}function Es(){return an(dr,{children:"Go back"})}function _s(){return an(dr,{children:"Secure card checkout"})}function sr(e){return e!==void 0&&(e===""||e===null||e===!1)}function lr({content:e}){return an(dr,{children:e===void 0?an(Is,{}):e})}function cr({content:e}){return an(dr,{children:e===void 0?an(Es,{}):e})}function Nr({content:e}){return an(dr,{children:e===void 0?an(_s,{}):e})}import{ExpressCheckoutElement as Ei,PaymentElement as Ks,Elements as tr,useElements as oa,useStripe as aa}from"@stripe/react-stripe-js";import{isAuthorizationOnlySession as Zo,normalizeCheckoutFailureOutcome as Vs,resolveButtonsLayoutTheme as Hs,getPostalCodeLabel as na,getStateLabel as fi,getStateOptions as Ws,COUNTRY_OPTIONS as Ys,resolveAVSConfig as Gs,isAVSFieldVisible as De,getStateFromPostalCode as gi,isPostalCodeSupported as Js,isValidPostalCode as Xs,getPostalCodeExample as Qs,filterStripeMethodsByCountry as Zs,getStripeMethodDisplayName as hr,hasVendoredStripeMethodLogo as el,needsStripeMethodExplicitConfirm as hi,resolveStripeMethodBrandVariant as tl,partitionStripeMethods as nl,stripeExpressMethodToOptionKey as Pi}from"@flopay/shared";import{PaymentAPI as Un,toStripeAppearance as rl}from"@flopay/js";import"react";import{jsx as ti,jsxs as xs}from"react/jsx-runtime";function ur({children:e,margin:t,icon:n=!0,styleOverride:s}){return xs("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"}:{},...s??{}},children:[n&&ti("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:ti("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 ni={alipay:new URL("./payment-logos/alipay.svg",import.meta.url).href,bancontact:new URL("./payment-logos/bancontact.svg",import.meta.url).href,blik:new URL("./payment-logos/blik.svg",import.meta.url).href,eps:new URL("./payment-logos/eps.svg",import.meta.url).href,giropay:new URL("./payment-logos/giropay.svg",import.meta.url).href,ideal:new URL("./payment-logos/ideal.svg",import.meta.url).href,klarna:new URL("./payment-logos/klarna.svg",import.meta.url).href,p24:new URL("./payment-logos/p24.svg",import.meta.url).href,sepa_debit:new URL("./payment-logos/sepa_debit.svg",import.meta.url).href,wechat_pay:new URL("./payment-logos/wechat_pay.svg",import.meta.url).href};import ol,{useCallback as Ce,useContext as al,useEffect as ct,useMemo as lt,useRef as Be,useState as ve}from"react";import{useContext as Or}from"react";import{resolveBillingApiUrl as Ts}from"@flopay/shared";function vn(){return Or(xn).flopay}function Vo(){return Or(xn).paypalFlopay??null}function Ho(){return Or(xn).elements}function Ms(){return Or(un)}function co(){return Or(xn).billingApiUrl||Ts()}import{FloPayError as ri,isMoneySettledOutcome as As,isSetupIntentClientSecret as Kc}from"@flopay/shared";function oi(e,t){return t?e?{account:{...e.account??{},...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}:t:e}function Wo(e,t){return t?{...e,account:{...e.account,...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}:e}function ai(e,t){let n=e.products??[...(e.subscriptions??[]).map(i=>({type:"subscription",code:i.code??i.providerPlanId,name:i.subscriptionName??i.providerPlanName??i.code??i.providerPlanId??null,quantity:i.quantity??1,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount,currency:i.currency,metadata:i.metadata})),...(e.items??[]).map(i=>({type:"item",code:i.code??i.providerItemId,name:i.itemName??i.providerItemName??i.code??i.providerItemId??null,quantity:i.quantity??1,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount,currency:i.currency,metadata:i.metadata}))],s=n.reduce((i,u)=>i+(u.overrideAmount??u.totalAmount??0),0),a=e.currency??n.find(i=>i.currency)?.currency??"USD";return{id:"",clientSecret:"",mode:n.some(i=>i.type==="subscription")?"subscription":"payment",amount:Math.round(s*100),currency:a,status:"open",captureMethod:e.captureMethod,customer:{id:e.account.userId,email:e.account.email??"",firstName:e.account.firstName,lastName:e.account.lastName,gender:e.account.gender??void 0,city:e.account.city??void 0,state:e.account.state??void 0,country:e.account.country??void 0,zip:e.account.zip??void 0},successUrl:e.successUrl,cancelUrl:e.cancelUrl,checkoutMode:t??e.checkoutMode??"full",products:n.map((i,u)=>({uuid:`synthetic-${i.type??"item"}-${u}`,checkoutSessionId:"",type:i.type??"item",code:i.code,name:i.name??null,quantity:i.quantity??1,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount??null,currency:i.currency??a,metadata:i.metadata??null}))}}function Yo(e,t){return t?{...e,...t}:e}function It(e,t,n){let s=typeof t=="string"?t:t.message,a=typeof t=="string"?n?.code:n?.code??t.code,i=typeof t=="string"?n?.declineCode:n?.declineCode??t.declineCode;return{method:e,message:s,...a?{code:a}:{},...i?{declineCode:i}:{}}}var Bs=[{match:/^paypal authorization required\.?$/i,replacement:"For your additional security, please re-authenticate this payment via PayPal."}];function Nn(e){if(typeof e!="string")return e??void 0;let t=e.trim();if(!t)return e;for(let{match:n,replacement:s}of Bs)if(n.test(t))return s;return e}function Qn(e,t){return e.status!=="authorized"?{status:"succeeded"}:{status:"authorized",paymentId:e.paymentId,sessionId:e.id||t||void 0,authorizationExpiresAt:e.authorizationExpiresAt}}function pr(e){return e?.status==="authorized"||e?.status==="complete"}function ii(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function uo(e){let t=ii(e);return new ri(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function po(e){let t=ii(e);return new ri(t?"Authorization has expired.":"Automatic payment failed. Please try again.","api_error",{code:t?"authorization_expired":e?.status==="expired"?"checkout_session_expired":"checkout_processing_timeout"})}function mo(e,t){return e==="processing"||As(e,t)}function si(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}function li(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?{mode:"setup"}:{mode:"payment",amount:e}}function Ur(e){let t=[e?.id,e?.originalPaymentMethodId];for(let n of t)if(typeof n=="string"&&n.startsWith("pm_"))return n}var yo="flopay_recent_completion_";function mr(e){if(!(!e||typeof window>"u"))try{let t={expiresAt:Date.now()+6e4};window.sessionStorage.setItem(yo+e,JSON.stringify(t))}catch{}}function Go(e){if(!e||typeof window>"u")return!1;try{let t=window.sessionStorage.getItem(yo+e);if(!t)return!1;let n=JSON.parse(t);return typeof n?.expiresAt!="number"||n.expiresAt<=Date.now()?(window.sessionStorage.removeItem(yo+e),!1):!0}catch{return!1}}function ci(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}import{useCallback as fo,useEffect as ft,useMemo as qr,useRef as Ze,useState as er}from"react";import{loadScript as Ds}from"@paypal/paypal-js";import{PaymentAPI as Jo}from"@flopay/js";import{FloPayError as di,SDK_VERSION as Ls,generateIdempotencyKey as zs,normalizeGatewayEnvironment as Ns}from"@flopay/shared";function Fs(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 Zn(e){if(typeof e!="string")return;let t=e.trim();return/^[a-z0-9_.-]{1,64}$/i.test(t)?t:void 0}function Tn(e){if(typeof e!="object"||e===null)return;let t=e;return Zn(t.code)??Zn(t.type)??Zn(t.name)}function yr(e){if(!(typeof e!="object"||e===null))return Zn(e.decline_code)}function $r(e){return typeof e!="object"||e===null?!1:Zn(e.type)?.toLowerCase()==="card_error"||yr(e)!==void 0}function On(e){let t=Fs(e)?.toLowerCase()??"",s=`${Tn(e)?.toLowerCase()??""} ${t}`;return s.includes("popup")&&s.includes("block")}import{jsx as fr,jsxs as Xo}from"react/jsx-runtime";var go=45,Os=1e3,Us=11e3,$s=["https://www.paypal.com","https://www.sandbox.paypal.com"],ui="We couldn't open PayPal. Try again or choose another payment method.",qs={width:"100%",minHeight:go,margin:"0 0 0.5rem",padding:"0.75rem 0.875rem",border:"1px solid #2563eb",borderRadius:8,background:"#eff6ff",color:"#1d4ed8",fontSize:"0.95rem",fontWeight:700,cursor:"pointer"};function pi(e){return e.includes("No ack for postMessage init()")&&$s.some(t=>e.includes(t))&&e.includes("10000ms")}function js(e){return e?`${ui} Allow pop-ups for this site, then try again.`:ui}function mi({sessionId:e,nonce:t,billingApiUrl:n,email:s,clientId:a,environment:i,currency:u,isSubscription:l,onTokenizedBody:v,onComplete:N,onErrorChange:h,onDecline:E,onTechnicalFailure:C,isProcessing:F=!1,onLoadStateChange:c,onInitializationStateChange:P,allowAutomaticRetry:k=!0,onButtonClick:T,runBeforeButtonClick:g,session:me,existingOrderId:M,telemetry:le,telemetryContext:ce,debug:z=!1}){let J=vn(),H=qr(()=>{if(J)return null;let A=so({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:Ls,enabled:le!==!1});return A.setCheckoutContext(ce??{}),A.beginCheckout(ce??{}),A},[n,J,le,ce?.checkoutMode,ce?.layout]),oe=qr(()=>At(J),[J]);ft(()=>()=>{H&&H.flush().catch(()=>{}).finally(()=>H.destroy())},[H]);let j=qr(()=>({error:A=>{oe?oe.error(A):H?.error(A)},log:A=>{oe?oe.log(A):H?.log(A)},performance:A=>{oe?oe.performance(A):H?.performance(A)},terminal:A=>{oe?oe.terminal(A):H?.terminal(A)},startTiming:()=>oe?.now()??H?.now()??0,elapsed:A=>oe?.elapsed(A)??Math.max(0,(H?.now()??A)-A)}),[oe,H]),K=Ze(null),ie=Ze(0),xe=Ze(null),he=Ze(!1),[de,Q]=er(!1),[ye,Te]=er(!1),[Z,Ue]=er(0),Fe=Ze(0),[we,V]=er(!1),b=Ze(!1),te=Ze(!1),[$e,ze]=er(!1),[ae,R]=er(!1),re=qr(()=>n.replace(/\/+$/,""),[n]),W=qr(()=>JSON.stringify([re,a,u,i??"",l,e,M??""]),[re,a,u,i,M,l,e]),ke=Ze(W),dt=ke.current!==W,[Ge,pt]=er([]),_=A=>{z&&pt(at=>[...at,`${new Date().toISOString().slice(11,23)} ${A}`])},Y=Ze(v),et=Ze(N),qe=Ze(h),mt=Ze(E),Ne=Ze(C),He=Ze(T),Jt=Ze(c),Ye=Ze(P),Xt=Ze(g),S=Ze(me),fe=Ze(s),We=Ze(t),Re=Ze(null),vt=Ze(0),Ke=Ze(null),je=Ze(null),tt=Ze(new Map),Je=Ze(new Map),kn=Ze(!1);ft(()=>(kn.current=!0,()=>{kn.current=!1}),[]),ft(()=>{Y.current=v},[v]),ft(()=>{et.current=N},[N]),ft(()=>{qe.current=h},[h]),ft(()=>{mt.current=E},[E]),ft(()=>{Ne.current=C},[C]),ft(()=>{He.current=T},[T]),ft(()=>{Jt.current=c},[c]),ft(()=>{Ye.current=P},[P]),ft(()=>{Xt.current=g},[g]),ft(()=>{S.current=me},[me]),ft(()=>{fe.current=s},[s]),ft(()=>{We.current=t},[t]),ft(()=>{Fe.current=Z},[Z]),ft(()=>{we&&xe.current?.focus()},[we,Z]);let ot=fo(()=>{window.setTimeout(()=>{xe.current?.focus()},0)},[]),jn=fo(()=>{Q(!1),Ue(A=>A+1)},[]),Wt=fo(()=>{V(!1),(K.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??K.current)?.focus?.()},[]);ft(()=>{!de||!he.current||(he.current=!1,Wt())},[Wt,de,Z]);let mn=fo((A,at)=>{let Lt=Ne.current;if(Lt){Lt("paypal",A,at);return}qe.current?.(js(at?.popupBlocked??On(A)))},[]),Qt=()=>{Ke.current?.timer&&(clearTimeout(Ke.current.timer),Ke.current.timer=null)},or=()=>{Qt();let A=vt.current+1;return vt.current=A,je.current=null,Ke.current={generation:A,timer:null,yieldedControl:!1},V(!1),A},Bt=A=>A!==void 0&&Ke.current?.generation!==A?!1:(Qt(),Ke.current=null,je.current=null,!0),St=A=>{let at=A?.generation??Ke.current?.generation??vt.current;(!A?.generation||Ke.current?.generation===at)&&(Qt(),Ke.current=null),je.current=at,A?.showRetry&&V(!0),A?.remount&&jn(),A?.focus!==!1&&ot()},Zt=A=>Ke.current?.generation===A&&je.current!==A,en=A=>{typeof document<"u"&&document.visibilityState!=="visible"||(Qt(),A.timer=setTimeout(()=>{Ke.current?.generation===A.generation&&(Ke.current=null,je.current=A.generation,mn(new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}),V(!0),jn(),ot())},600))},Ft=()=>{let A=Ke.current;A?.yieldedControl&&en(A)},Dt=()=>{let A=Ke.current;A&&(A.yieldedControl=!0,Qt())},Ct=A=>{let at=Re.current;return at&&Je.current.set(A,at),A};ft(()=>{let A=()=>{document.visibilityState==="visible"?Ft():Dt()};return document.addEventListener("visibilitychange",A),window.addEventListener("focus",Ft),window.addEventListener("blur",Dt),()=>{document.removeEventListener("visibilitychange",A),window.removeEventListener("focus",Ft),window.removeEventListener("blur",Dt),Qt()}},[]),ft(()=>{ke.current!==W&&(ke.current=W,b.current=!1,te.current=!1,Q(!1),Te(!1),ze(!1),Ye.current?.("loading"))},[W]),ft(()=>{ut(()=>Jt.current?.(de&&!$e))},[de,$e]);let X=Ns(i);ft(()=>{let A=a?`${a.slice(0,6)}\u2026(len ${a.length})`:"(empty)",at=typeof navigator<"u"?navigator.userAgent:"(no navigator)";if(_(`mount clientId=${A} env=${i??"(unset)"}\u2192${X??"live"} ccy=${u} sub=${l}`),_(`ua=${at.slice(0,80)}${at.length>80?"\u2026":""}`),!a){_("FAIL: clientId empty \u2014 gateway misconfigured"),ze(!0),j.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(!K.current){_("FAIL: containerRef not attached");return}ie.current=j.startTiming(),j.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let Lt=!1,Fn=!1,Me=()=>Lt||Fn,it,Ve=!1,Rn=()=>{it=zs(),it||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),Ve=!0},In=null,Dn=!1,Vn=null,En=!1,nt=()=>{!Vn||En||(En=!0,Vn.close().catch(()=>{}))},zt=null,sn=()=>{zt!==null&&(j.log({name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal"}),j.performance({stage:"overlay_return",durationMs:j.elapsed(zt),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal"}),zt=null)},gt=!1,xt=K.current,tn=null,ln=null,Yt=[],Ut=m=>{if(!m||typeof m.getBoundingClientRect!="function")return"(no rect)";let r=m.getBoundingClientRect();return`${Math.round(r.width)}\xD7${Math.round(r.height)}`},$t=m=>{if(!m)return"(empty)";try{let r=new URL(m,typeof window<"u"?window.location.href:"https://localhost"),y=r.pathname.toLowerCase();return y.includes("checkcaptcha")||y.includes("captcha")?`CAPTCHA(${r.host}${y})`:y.includes("risk")||y.includes("challenge")?`RISK(${r.host}${y})`:y.includes("smart/buttons")?`smart-buttons(${r.host})`:`${r.host}${y}`.slice(0,100)}catch{return m.slice(0,80)}},Ie=m=>{let r=m.getAttribute("src"),y=m.getAttribute("srcdoc"),x=m.getAttribute("name"),f=m.getAttribute("sandbox"),O=[];return r&&O.push(`src=${$t(r)}`),y&&O.push(`srcdoc[${y.length}ch]`),!r&&!y&&O.push("src=(empty) srcdoc=(empty)"),x&&O.push(`name=${x.slice(0,40)}`),f!==null&&O.push(`sandbox="${f.slice(0,40)}"`),O.join(" ")},qt=m=>{if(!(m instanceof HTMLIFrameElement))return"";try{let r=m.contentDocument;if(!r)return"cd=null";let y=r.body?.children.length??0,x=r.body?.innerHTML.length??0,f=r.head?.innerHTML.length??0;return`cd=same-origin readyState=${r.readyState} body[${y}children,${x}ch] head[${f}ch]`}catch(r){return`cd=cross-origin(${r.message.slice(0,30)})`}},yt=[],yn=m=>{if(Me())return;let r=m.message??String(m.error??"(no message)");r&&(r.toLowerCase().includes("paypal")||r.toLowerCase().includes("zoid")||r.toLowerCase().includes("postrobot")||r.toLowerCase().includes("storage"))&&(_(`window:error ${r.slice(0,140)}`),yt.push(r))},Hn=m=>{if(Me())return;let r=m.reason instanceof Error?m.reason.message:String(m.reason??"(no reason)");r&&(r.toLowerCase().includes("paypal")||r.toLowerCase().includes("zoid")||r.toLowerCase().includes("postrobot")||r.toLowerCase().includes("storage"))&&(_(`window:rejection ${r.slice(0,140)}`),yt.push(r))};z&&typeof window<"u"&&(window.addEventListener("error",yn),window.addEventListener("unhandledrejection",Hn));let jt={value:0};if(z&&typeof PerformanceObserver<"u")try{ln=new PerformanceObserver(m=>{if(!Me())for(let r of m.getEntries()){if(!r.name.toLowerCase().includes("paypal"))continue;jt.value+=1;let y=Math.round(r.duration);_(`net ${y}ms ${r.name.slice(0,90)}`)}}),ln.observe({type:"resource",buffered:!0})}catch{}let Kt=()=>{for(tn?.disconnect(),tn=null,ln?.disconnect(),ln=null;Yt.length;)clearTimeout(Yt.pop());z&&typeof window<"u"&&(window.removeEventListener("error",yn),window.removeEventListener("unhandledrejection",Hn))},Nt=m=>{if(!m)return!1;let r=m.toLowerCase();return r.includes("zoid destroyed")||r.includes("destroyed all components")||r.includes("window closed")||r.includes("detected container element removed")},Ln=m=>{if(Me()||Nt(m))return;let r=Nn(m)??m;ut(()=>qe.current?.(r))},zn=m=>{Lt||(ze(!0),m.includes("paypal_ineligible")||j.error({errorCode:"PROVIDER_LOAD_FAILED",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime"}),console.error("[FloPay] DirectPayPal load/render failure:",m))},nn=(m,r=!1)=>{if(Lt)return;let y=b.current||!k;if(Dn)return;Dn=!0,Fn=!0,Kt(),nt();let x=r||pi(m);if(x&&k&&!b.current){b.current=!0,Q(!1),R(!1),Te(!0),Ye.current?.("retrying"),In=setTimeout(()=>{Lt||Ue(f=>f+1)},Os);return}if(x||y){if(Q(!1),R(!1),Te(!1),ze(!0),Ye.current?.("exhausted"),!te.current){te.current=!0;let f=pi(m)?"paypal_init_timeout":r?"paypal_render_timeout":"paypal_init_failure";console.error("[FloPay] Direct PayPal initialization failed:",f)}return}zn(m)};ze(!1);let Gt=async(m,r=Re.current)=>{if(Me())return;let y=r?.sessionId??e;if(Y.current){await Y.current(m,{sessionId:y,accountPatch:r?.accountPatch,nonce:r?.nonce});return}let x=j.startTiming();j.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let f=()=>{j.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),j.performance({stage:"processing",durationMs:j.elapsed(x),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})};try{let O=S.current,Ae=r?.accountPatch?.email??fe.current,Xe=r?.accountPatch?.userId??O?.customer?.id??O?.accountData?.userId??"",U=await new Jo(re,{telemetry:!1}).processPayment(Xe,{sessionId:y,nonce:r?.nonce??We.current,tokenizedData:m,accountData:{userId:Xe,email:Ae??O?.customer?.email??"",firstName:r?.accountPatch?.firstName??O?.customer?.firstName??O?.accountData?.firstName??"",lastName:r?.accountPatch?.lastName??O?.customer?.lastName??O?.accountData?.lastName??"",country:r?.accountPatch?.country??O?.customer?.country??O?.accountData?.country??void 0,zip:r?.accountPatch?.zip??O?.customer?.zip??O?.accountData?.zip??void 0}});if(U.ok){if(Fn||Lt&&kn.current)return;f(),j.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),ut(()=>et.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(Me())return;let p=await U.json().catch(()=>null),L=p?.message??"PayPal payment failed.",ue=Nn(L)??L;f(),U.status===400&&(typeof p?.declineCode=="string"||!Array.isArray(p?.fields))?j.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):U.status===400||U.status===422?j.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx"}):j.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:U.status>=500?"5xx":U.status>=400?"4xx":U.status>=300?"3xx":"unknown",failureCategory:U.status>=500?"server_error":void 0}),Ln(ue),ut(()=>mt.current?.(It("paypal",ue,{code:p?.code,declineCode:p?.declineCode})));return}catch(O){if(Me())return;f(),j.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let Ae=O instanceof Error?O.message:"PayPal payment failed.",Xe=Nn(Ae)??Ae;Ln(Xe),ut(()=>mt.current?.(It("paypal",Xe)));return}},rn=()=>new di("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),Oe=m=>Me()?Promise.reject(rn()):Promise.resolve(m),w=async m=>{if(Me())throw rn();Ve||Rn();let r=Re.current,y=r?.sessionId??e,x=r?.nonce??We.current;j.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let f=await new Jo(re,{telemetry:!1}).createSessionIntent(y,x??"",{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"},{idempotencyKey:it});if(Me())throw rn();if(f.provider!=="paypal")throw new Error(m);return j.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),f.providerObjectId},D=(m,r)=>{let y=r?.nonce??We.current;if(!y)return;let x=r?.sessionId??e,f=yr(m)??Tn(m)??"provider_declined";new Jo(re,{telemetry:!1}).reportSessionIntentDecline(x,y,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:f}).catch(()=>{})},I=Z;_("loadScript:scheduled (deferred 1 tick)");let ge=null,Pe=setTimeout(()=>{if(Lt){_("loadScript:skipped (cancelled before defer ran)");return}_("loadScript:start");let m=X==="live"?"production":X;ge=Ds({clientId:a,currency:u,intent:l?"subscription":"capture",vault:l?!0:void 0,...m?{environment:m}:{},...m==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}}),ge.then(r=>{if(_(`loadScript:resolved inactive=${Me()} ns=${!!r} buttons=${!!r?.Buttons}`),Me())return;if(!r?.Buttons){_("FAIL: namespace missing Buttons factory"),nn("PayPal SDK did not expose the Buttons factory.");return}j.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),j.performance({stage:"provider_ready",durationMs:j.elapsed(ie.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),j.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let y=async G=>{if(Me()||Fe.current!==I)return;let U=G.subscriptionID??G.orderID??"",p=U?Je.current.get(U):tt.current.get(I);if(!(!p||!Zt(p.generation))&&Bt(p.generation)){Je.current.delete(U),tt.current.delete(p.surfaceKey),sn();try{if(R(!0),ut(()=>qe.current?.(null)),!U)throw new di("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});await Gt({id:U,isPaypal:!0},p)}catch(L){Ln(L instanceof Error?L.message:"PayPal capture failed.")}finally{Me()||R(!1)}}},x=r.Buttons({style:{layout:"horizontal",height:go,tagline:!1},onClick:async(G,U)=>{if(Me()){await U.reject();return}Rn();let p=Xt.current,L={};if(p)try{let Ee=await p("paypal");if(Me()){await U.reject();return}if(!Ee.proceed){Re.current=null,tt.current.delete(I),await U.reject();return}L={sessionId:Ee.sessionId,accountPatch:Ee.accountPatch,nonce:Ee.nonce}}catch(Ee){_(`onClick:runBeforeButtonClick rejected msg=${(Ee instanceof Error?Ee.message:String(Ee)).slice(0,120)}`),Re.current=null,tt.current.delete(I),await U.reject();return}ut(()=>He.current?.("paypal"));let Se={generation:or(),surfaceKey:I,...L};Re.current=Se,tt.current.set(I,Se),await U.resolve(),j.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),j.log({name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),j.log({name:"provider.overlay.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),zt=j.startTiming()},createOrder:l?void 0:M?()=>Oe(M).then(Ct):()=>w("Failed to create PayPal order.").then(Ct),createSubscription:l?M?()=>Oe(M).then(Ct):()=>w("Failed to create PayPal subscription.").then(Ct):void 0,onApprove:y,onCancel:()=>{if(Me())return;let G=tt.current.get(I)??Re.current;G&&tt.current.delete(G.surfaceKey),Re.current=null,sn(),j.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),he.current=!0,St({generation:G?.generation,remount:!0,focus:!1})},onError:G=>{if(Me()||Fe.current!==I)return;let U=G instanceof Error?G.message:"PayPal failed to render.";if(_(`onError rendered=${gt} msg=${U.slice(0,120)}`),gt){let p=tt.current.get(I)??Re.current;if(p&&!Zt(p.generation)||!p&&je.current===vt.current)return;if(Nt(U)){Bt(p?.generation);return}if(sn(),$r(G)){j.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),D(G,p),ut(()=>mt.current?.(It("paypal",U))),p&&tt.current.delete(p.surfaceKey),Re.current=null,Bt(p?.generation);return}let L=U.toLowerCase();j.error({errorCode:L.includes("popup")&&L.includes("block")?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),p&&tt.current.delete(p.surfaceKey),Re.current=null,St({generation:p?.generation,remount:!0,showRetry:!0,focus:!0}),mn(G,{code:"paypal_runtime_failed"});return}nn(U)}}),f=x.isEligible();if(_(`isEligible=${f}`),j.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!f){Q(!1),nn("PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}Vn=x,z&&_(`container:dims ${Ut(xt)} visibility=${typeof document<"u"?document.visibilityState:"(no document)"}`),z&&typeof MutationObserver<"u"&&(tn=new MutationObserver(G=>{if(!Me()){for(let U of G)if(U.type==="childList")U.addedNodes.forEach(p=>{if(!(p instanceof Element))return;let L=p.tagName.toLowerCase(),ue=(p.getAttribute("title")??"").slice(0,40),Se=L==="iframe"?` ${Ie(p)}`:"";_(`child+ ${L}${ue?` title="${ue}"`:""}${Se} dims=${Ut(p)}`)});else if(U.type==="attributes"&&U.target instanceof Element){let p=U.target;if(p.tagName.toLowerCase()!=="iframe")continue;let L=U.attributeName;(L==="src"||L==="srcdoc")&&_(`attr~ iframe ${L}=${L==="srcdoc"?`[${(p.getAttribute("srcdoc")??"").length}ch]`:$t(p.getAttribute("src"))} dims=${Ut(p)}`)}}}),tn.observe(xt,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let Ae=G=>{if(Me()||gt)return;let U=xt.querySelectorAll("iframe"),p=typeof document<"u"&&"hasStorageAccess"in document;_(`watchdog:${G} container=${Ut(xt)} children=${xt.childElementCount} iframes=${U.length} visibility=${typeof document<"u"?document.visibilityState:"(no document)"} cookies=${typeof navigator<"u"?navigator.cookieEnabled:"?"} hasStorageAccessApi=${p} paypalNetRequests=${jt.value}`),U.forEach((L,ue)=>{let Se=(L.getAttribute("title")??"").slice(0,40);_(` iframe[${ue}] ${Ut(L)}${Se?` title="${Se}"`:""} ${Ie(L)}`);let Ee=qt(L);Ee&&_(` ${Ee}`)}),yt.length===0&&_(" (no PayPal/zoid window errors captured)")};z&&(Yt.push(setTimeout(()=>Ae("3s"),3e3)),Yt.push(setTimeout(()=>Ae("8s"),8e3)),Yt.push(setTimeout(()=>Ae("15s"),15e3))),_("render:start");let Xe=j.startTiming();Yt.push(setTimeout(()=>{Me()||gt||(_("watchdog:11s retryable render timeout"),nn("PayPal Buttons render did not settle within 11000ms.",!0))},Us)),x.render(xt).then(()=>{if(_(`render:resolved inactive=${Me()}`),Kt(),Me()){nt();return}gt=!0,Q(!0),Te(!1),Ye.current?.("ready"),j.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),j.performance({stage:"checkout_render",durationMs:j.elapsed(Xe),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}).catch(G=>{let U=G instanceof Error?G.message:"PayPal failed to render.";_(`render:rejected msg=${U.slice(0,120)}`),Kt(),nn(U)})}).catch(r=>{let y=r instanceof Error?r.message:"PayPal SDK failed to load.";_(`loadScript:rejected msg=${y.slice(0,120)}`),nn(y)})},0);return()=>{Lt=!0,clearTimeout(Pe),In&&clearTimeout(In),Kt(),nt()}},[k,re,a,u,i,l,e,M,Z,j]);let Kn=z?Xo("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:$e?"#fef2f2":"#f3f4f6",border:`1px solid ${$e?"#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=${de} failed=${$e})`,Ge.length===0?`
|
|
7
2
|
(waiting for first lifecycle event\u2026)`:`
|
|
8
|
-
${
|
|
9
|
-
`)}`]}):null;return $e&&!
|
|
3
|
+
${Ge.join(`
|
|
4
|
+
`)}`]}):null;return $e&&!dt?z?fr("div",{children:Kn}):null:Xo("div",{children:[Kn,Xo("div",{"aria-hidden":ye?!0:void 0,style:ye?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:go},children:[!de&&!ye&&fr("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"}}),fr("div",{ref:K,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,"aria-label":"PayPal payment method",style:{minHeight:go,display:"flex",opacity:de?1:0},"aria-busy":ae||F},Z)]},Z),we&&fr("button",{ref:xe,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:Wt,style:qs,children:"Try PayPal again"})]})}function ho(e){return fr(mi,{...e})}function yi(e){return fr(mi,{...e})}import{FloPayError as Cn,isSetupIntentClientSecret as il,resolveTheme as sl}from"@flopay/shared";import{Fragment as gr,jsx as d,jsxs as Le}from"react/jsx-runtime";var Sn="flopay_stripe_resume",bi="flopay_wallet_resume",jr="flopay_paypal_resume",ll=250,vi="Just a moment \u2014 we are finalizing your order. Please press pay again.";function ia(e,t,n){e?.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:"provider_runtime",stage:"provider_load",provider:t,paymentMethodCategory:n,requestCategory:"provider_sdk"})}async function bo({billingApiUrl:e,sessionId:t,nonce:n,request:s}){if(!(!t||!n))try{await new Un(e,{telemetry:!1}).reportSessionIntentDecline(t,n,s)}catch{}}function cl(e){return e instanceof Cn&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function ea(e){return e?.html?{html:e.html,...e.messageToken?{messageToken:e.messageToken}:{},...e.expectedOrigin?{expectedOrigin:e.expectedOrigin}:{}}:null}var dl=`
|
|
10
5
|
.paypal-buttons { margin: 0 !important; vertical-align: top !important; }
|
|
11
6
|
@keyframes flopay-spin { to { transform: rotate(360deg); } }
|
|
12
7
|
@keyframes flopay-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }
|
|
@@ -27,7 +22,7 @@ ${Je.join(`
|
|
|
27
22
|
0% { opacity: 1; transform: translateX(0) scale(1); }
|
|
28
23
|
100% { opacity: 0; transform: translateX(16px) scale(0.97); }
|
|
29
24
|
}
|
|
30
|
-
`,Eo=44;function ha(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 Sl={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"},Oi={width:"100%",minHeight:Eo,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 wl(e){switch(e){case"paypal":return"PayPal";case"apple_pay":return"Apple Pay";case"google_pay":return"Google Pay";default:return"Card"}}function Mi(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function Ni(e){return e==="paypal"?"PayPal":Cr(e)}function kl(e,t){let n=`We couldn't open ${Ni(e)}. Try again or choose another payment method.`;return t?`${n} Allow pop-ups for this site, then try again.`:n}function Ui(e){let t=De(0),n=De(null),a=De(null),r=ke((d=a.current)=>{let h=d;h?.timer&&(clearTimeout(h.timer),h.timer=null)},[]),i=ke((d,h)=>{typeof document<"u"&&document.visibilityState!=="visible"||(r(d),d.timer=setTimeout(()=>{d.timer=null,a.current?.generation===d.generation&&(a.current=null,n.current=d.generation,e(d.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}))},h))},[r,e]),c=ke(d=>{d.yieldedControl&&i(d,600)},[i]),l=ke(d=>{r();let h=t.current+1;t.current=h,n.current=null;let k={generation:h,method:d,timer:null,yieldedControl:!1};return a.current=k,h},[r]),b=ke(d=>{let h=a.current;return typeof d=="number"&&h?.generation!==d?!1:(r(h),a.current=null,(typeof d!="number"||n.current===d)&&(n.current=null),!0)},[r]),x=ke(d=>{let h=a.current,k=d??h?.generation??t.current;(!d||h?.generation===d)&&(r(h),a.current=null),n.current=k},[r]),g=ke(d=>n.current===(d??t.current),[]),w=ke(d=>a.current?.generation===d&&n.current!==d,[]),v=ke(()=>{let d=a.current;d&&c(d)},[c]),R=ke(()=>{let d=a.current;d&&(d.yieldedControl=!0,r(d))},[r]);return pt(()=>{let d=()=>{document.visibilityState==="visible"?v():R()},h=()=>{R()};return document.addEventListener("visibilitychange",d),window.addEventListener("blur",h),window.addEventListener("focus",v),()=>{document.removeEventListener("visibilitychange",d),window.removeEventListener("blur",h),window.removeEventListener("focus",v),r()}},[r,R,v]),{startAttempt:l,finishAttempt:b,invalidateAttempt:x,isAttemptInvalidated:g,isAttemptCurrent:w}}function Rl(e){let t=cl(e);return`Enter a valid ${pa(e)}${t?` (e.g. ${t})`:""}`}function El(e,t,n){let a=sl(e),r=t.trim(),i=n&&a,c=i&&!r,l=i&&!!r&&!ll(e,r);return{visible:n,supported:a,required:i,empty:c,malformed:l}}function Ai(e,t){return t instanceof kn?t:new kn(t instanceof Error?t.message:`${wl(e)} before-click hook failed.`,"validation_error")}function ua(){return u("style",{children:Cl})}function Il(e){return typeof e=="number"?`${e}px`:e}function $i(e,t){let n=e.availablePaymentMethods;return n&&t.some(a=>n[a])?"ready":"unavailable"}function qi({state:e,placeholderTestId:t,borderRadius:n=8,children:a}){return e==="unavailable"||e==="load_error"?null:ze("div",{style:{position:"relative",minHeight:44},children:[u("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"}}),u("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:a})]})}function Bi(e){return e!=="unavailable"&&e!=="load_error"}function Pa(e){return u(xl,{...e})}function Fi({sessionId:e,nonce:t,email:n,billingApiUrl:a,onTokenizedBody:r,onErrorChange:i,isProcessing:c=!1,onButtonClick:l,onDecline:b,onTechnicalFailure:x,runBeforeButtonClick:g,onLoadStateChange:w,placeholderBorderRadius:v}){let R=wn(),d=fa(),h=ya(),[k,E]=we("loading");pt(()=>{w?.(k)},[k,w]);let[f,de]=we(!1),S=De(!1),le=De(null),Z=De(null),[F,G]=we(0),[W,oe]=we(!1),N=De(!1),j=De(new Map),{startAttempt:ce,finishAttempt:Re,invalidateAttempt:fe,isAttemptInvalidated:ae,isAttemptCurrent:ee}=Ui((q,C,ie)=>{x?.(q,C,{...ie,popupBlocked:ie?.popupBlocked??$n(C)}),oe(!0),G($e=>$e+1)});pt(()=>{W&&Z.current?.focus()},[W,F]);let pe=ke(()=>{G(q=>q+1)},[]),Y=ke((q,C,ie)=>{fe(ie),x?.("paypal",q,{code:C,popupBlocked:$n(q)}),oe(!0),pe()},[fe,x,pe]),K=ke(()=>{window.setTimeout(()=>{(le.current?.querySelector("iframe")??le.current)?.focus()},0)},[]);pt(()=>{N.current&&(N.current=!1,K())},[K,F]);let Ee=ke(()=>{oe(!1),i?.(null),K()},[K,i]);pt(()=>{if(!d||S.current)return;let q=new URLSearchParams(window.location.search),C=q.get("payment_intent"),ie=q.get("payment_intent_client_secret"),$e=q.get("redirect_status");if(!C||!ie)return;S.current=!0;let Oe;try{let T=localStorage.getItem(Gr);if(T){let ue=JSON.parse(T);ue.clientSecret===ie&&(Oe={...ue.accountPatch?{accountPatch:ue.accountPatch}:{},...ue.sessionId?{sessionId:ue.sessionId}:{},...ue.nonce?{nonce:ue.nonce}:{}})}}catch{}try{localStorage.removeItem(Gr)}catch{}let me=new URL(window.location.href);me.searchParams.delete("payment_intent"),me.searchParams.delete("payment_intent_client_secret"),me.searchParams.delete("redirect_status"),window.history.replaceState({},"",me.toString()),(async()=>{try{if(de(!0),$e==="failed"){let J="PayPal payment was declined. Please try again.";i?.(J),b?.(Et("paypal",J));return}let{paymentIntent:T,error:ue}=await d.retrievePaymentIntent(ie);if(ue){i?.(ue.message??"Failed to retrieve PayPal payment status.");return}if(T&&(T.status==="requires_capture"||T.status==="succeeded")){let J=typeof T.payment_method=="string"?T.payment_method:T.payment_method?.id;r({id:J??T.id,type:"card",threeDSecureActionResultTokenId:T.id,isPaypal:!0},Oe)}else{let J="PayPal payment was not completed. Please try again.";i?.(J),b?.(Et("paypal",J))}}catch(T){i?.(T instanceof Error?T.message:"Failed to complete PayPal payment.")}finally{de(!1)}})()},[d,r,i,b]);let ge=ke(async q=>{if(c||f){q.reject();return}let C=g?await g("paypal"):{proceed:!0};if(!C.proceed){j.current.delete(F),q.reject();return}let ie=ce("paypal");j.current.set(F,{generation:ie,accountPatch:C.accountPatch,sessionId:C.sessionId,nonce:C.nonce}),oe(!1),l?.("paypal"),q.resolve()},[j,c,l,g,ce,f,F]),te=ke(async q=>{if(!d||!h)return;let C=j.current.get(F);if(C&&!ee(C.generation)){j.current.delete(F);return}if(!C&&ae()||C&&!Re(C.generation))return;C||Re();let ie=C??null;if(j.current.delete(F),!ie&&g){let T=await g("paypal");if(!T.proceed){q.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}ie={accountPatch:T.accountPatch,sessionId:T.sessionId,nonce:T.nonce}}let $e=ie?.sessionId??e,Oe=ie?.nonce??t,me=ie?.accountPatch?.email??n;try{if(de(!0),i?.(null),!$e||!me)throw new Error("Missing sessionId or email for PayPal payment");let T=d.createPaymentMethod,{error:ue,paymentMethod:J}=await T({type:"paypal"});if(ue){Y(ue,"stripe_paypal_create_payment_method_failed",C?.generation),q.paymentFailed({reason:"fail"});return}let _e=await new qn(a).createSessionIntent($e,Oe??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:J?.id??null,intentKind:"payment"});if(_e.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let mt=_e.clientSecret,Je={return_url:window.location.href};if(J?.id&&(Je.payment_method=J.id),typeof window<"u")try{localStorage.setItem(Gr,JSON.stringify({clientSecret:mt,sessionId:$e,nonce:Oe,accountPatch:ie?.accountPatch}))}catch{}let{error:yt,paymentIntent:A}=await d.confirmPayment({clientSecret:mt,confirmParams:Je,redirect:"if_required"});if(yt){if(typeof window<"u")try{localStorage.removeItem(Gr)}catch{}if(Wr(yt)){let tt=yt.message??"Your payment was declined.";i?.(tt),b?.(Et("paypal",tt,{code:An(yt),declineCode:Pr(yt)})),await Io({billingApiUrl:a,sessionId:$e,nonce:Oe,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:An(yt)??"provider_declined"}})}else Y(yt,"stripe_paypal_confirm_failed",C?.generation);return}if(typeof window<"u")try{localStorage.removeItem(Gr)}catch{}let X=typeof A?.payment_method=="string"?A.payment_method:A?.payment_method?.id;r({id:X??A?.id,type:"card",threeDSecureActionResultTokenId:A?.id,isPaypal:!0},{accountPatch:ie?.accountPatch,sessionId:$e,nonce:Oe});return}catch(T){Y(T,"stripe_paypal_failed",C?.generation)}finally{de(!1)}},[d,h,e,t,n,a,r,i,b,g,Y,Re,ee,ae,F]);return ze(vr,{children:[u(qi,{state:k,placeholderTestId:"flopay-paypal-placeholder",borderRadius:v,children:ze("div",{ref:le,tabIndex:-1,"data-testid":"flopay-paypal-focus-target","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[W&&u("button",{ref:Z,type:"button","data-testid":"flopay-paypal-retry-button",onClick:Ee,style:Oi,children:"Try PayPal again"}),u(zi,{onReady:q=>E($i(q,["paypal"])),onLoadError:()=>{E("load_error"),ga(At(R),"paypal","paypal")},onClick:ge,onConfirm:te,onCancel:()=>{let q=j.current.get(F);j.current.delete(F),At(R)?.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),fe(q?.generation),oe(!1),N.current=!0,pe()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:!1,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},F)]})}),f&&u(cn,{status:"processing"})]})}function Di({sessionId:e,nonce:t,email:n,billingApiUrl:a,intentKind:r,expressMethods:i,onTokenizedBody:c,onErrorChange:l,onButtonClick:b,onDecline:x,onTechnicalFailure:g,runBeforeButtonClick:w,onLoadStateChange:v,placeholderBorderRadius:R}){let d=wn(),h=fa(),k=ya(),[E,f]=we("loading");pt(()=>{v?.(E)},[E,v]);let[de,S]=we(!1),le=De(null),Z=De(null),[F,G]=we(0),[W,oe]=we(!1),[N,j]=we("google_pay"),ce=De(!1),Re=De("google_pay"),fe=De("google_pay"),ae=De(new Map),{startAttempt:ee,finishAttempt:pe,invalidateAttempt:Y,isAttemptInvalidated:K,isAttemptCurrent:Ee}=Ui((me,T,ue)=>{g?.(me,T,{...ue,popupBlocked:ue?.popupBlocked??$n(T)}),j(me),oe(!0),G(J=>J+1)});pt(()=>{W&&Z.current?.focus()},[W,F]);let ge=ke(()=>{G(me=>me+1)},[]),te=ke((me,T,ue,J)=>{Y(J),g?.(me,T,{code:ue,popupBlocked:$n(T)}),j(me),oe(!0),ge()},[Y,g,ge]),q=ke(()=>{window.setTimeout(()=>{(le.current?.querySelector("iframe")??le.current)?.focus()},0)},[]);pt(()=>{ce.current&&(ce.current=!1,q())},[q,F]);let C=ke(()=>{oe(!1),l?.(null),q()},[q,l]),ie=ke(async me=>{if(!h||!k)return;let T=ae.current.get(F);if(T&&!Ee(T.generation)){ae.current.delete(F);return}if(!T&&K()||T&&!pe(T.generation))return;T||pe();let ue=me.expressPaymentType??T?.method??Re.current,J=T??null;ae.current.delete(F);let _e=Mi(ue);if(!J&&w){let X=await w(_e);if(!X.proceed){me.paymentFailed({reason:"fail",message:"Wallet checkout was cancelled."});return}J={accountPatch:X.accountPatch,sessionId:X.sessionId,nonce:X.nonce}}let mt=_e,Je=J?.sessionId??e,yt=J?.nonce??t,A=J?.accountPatch?.email??n;try{S(!0),l?.(null);let{error:X}=await k.submit();if(X){te(ue,X,"stripe_wallet_submit_failed",T?.generation);return}let{error:tt,paymentMethod:qe}=await h.createPaymentMethod({elements:k});if(tt||!qe){te(ue,tt??new Error("Failed to create payment method."),"stripe_wallet_create_payment_method_failed",T?.generation);return}if(!Je||!A)throw new Error("Missing sessionId or email for wallet payment");let ft=await new qn(a).createSessionIntent(Je,yt??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:ue??_e,paymentMethodId:qe.id,intentKind:r});if(ft.provider!=="stripe")throw new Error("Invalid provider returned for wallet intent");let Ne=ft.clientSecret,{error:We,intentId:Xt}=hl(Ne)?await h.confirmCardSetup(Ne,{payment_method:qe.id}).then(Ge=>({error:Ge.error,intentId:Ge.setupIntent?.id})):await h.confirmCardPayment(Ne,{payment_method:qe.id}).then(Ge=>({error:Ge.error,intentId:Ge.paymentIntent?.id}));if(We){if(Wr(We)){let Ge=We.message??"Your payment was declined.";l?.(Ge),x?.(Et(mt,Ge,{code:An(We),declineCode:Pr(We)})),await Io({billingApiUrl:a,sessionId:Je,nonce:yt,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:ue??_e,providerDeclineReason:An(We)??"provider_declined"}})}else te(ue,We,"stripe_wallet_confirm_failed",T?.generation);return}c({id:qe.id,type:"card",threeDSecureActionResultTokenId:Xt},{accountPatch:J?.accountPatch,sessionId:Je,nonce:yt})}catch(X){te(ue,X,"stripe_wallet_failed",T?.generation)}finally{S(!1)}},[h,k,e,t,n,a,r,c,l,x,w,te,pe,Ee,K,F]),$e=ut(()=>{let me=["applePay","googlePay","paypal","link","amazonPay","klarna"],T=new Set(["applePay","googlePay"]),ue=new Set(i.map(_i)),J={};for(let _e of me)ue.has(_e)?J[_e]=T.has(_e)?"always":"auto":J[_e]="never";return J},[i]),Oe=ut(()=>i.map(_i),[i]);return ze(vr,{children:[u(qi,{state:E,placeholderTestId:"flopay-wallet-placeholder",borderRadius:R,children:ze("div",{ref:le,tabIndex:-1,"data-testid":"flopay-wallet-focus-target","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[W&&ze("button",{ref:Z,type:"button","data-testid":"flopay-wallet-retry-button",onClick:C,style:Oi,children:["Try ",Ni(N)," again"]}),u(zi,{onReady:me=>{f($i(me,Oe))},onLoadError:me=>{f("load_error"),ga(At(d),"stripe","wallet")},onClick:async me=>{Re.current=me.expressPaymentType,fe.current=Mi(me.expressPaymentType);let T=w?await w(fe.current):{proceed:!0};if(!T.proceed){ae.current.delete(F),me.reject();return}let ue=ee(me.expressPaymentType);ae.current.set(F,{generation:ue,method:me.expressPaymentType,accountPatch:T.accountPatch,sessionId:T.sessionId,nonce:T.nonce}),oe(!1),b?.(fe.current),me.resolve()},onConfirm:ie,onCancel:()=>{let me=ae.current.get(F);ae.current.delete(F),At(d)?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet"}),Y(me?.generation),oe(!1),ce.current=!0,ge()},options:{buttonType:{applePay:"plain",googlePay:"plain"},paymentMethods:$e,layout:{maxColumns:1,overflow:"never"}}},F)]})}),de&&u(cn,{status:"processing"})]})}function _l({method:e,themeId:t,submitting:n=!1,disabled:a=!1,highlighted:r=!1,hasNextStep:i=!1,onClick:c,backgroundColor:l,borderColor:b,textColor:x,borderRadius:g,fontFamily:w}){let v=pl(e,t),R=pi[e],d=v?.backgroundColor??l??"#ffffff",h=v?.borderColor??b??"#d1d5db",k=v?.textColor??x??"#262833";return u("button",{type:"button","data-testid":`flopay-stripe-method-button-${e}`,"data-method":e,onClick:()=>{!n&&!a&&c()},disabled:n||a,"aria-busy":n||void 0,style:{position:"relative",width:"100%",boxSizing:"border-box",height:Eo,padding:"0 1rem",backgroundColor:d,color:k,border:`1px solid ${h}`,borderRadius:g??8,fontSize:"0.95rem",fontWeight:600,fontFamily:w,cursor:n||a?"not-allowed":"pointer",opacity:a&&!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:r?"0 0 0 2px rgba(74, 73, 255, 0.15)":void 0},children:n?u("span",{style:{margin:"0 auto"},children:`Connecting to ${Cr(e)}\u2026`}):ze(vr,{children:[ze("span",{style:{display:"inline-flex",alignItems:"center",gap:ul(e)?8:0},children:[R?u("img",{src:R,alt:"","aria-hidden":"true",loading:"lazy",decoding:"async",width:30,height:20,style:{width:30,height:20,flexShrink:0,borderRadius:3,objectFit:"contain",display:"inline-flex"}}):v?.logoSvg?u("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:v.logoSvg}}):null,u("span",{children:Cr(e)})]}),i&&u("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:k,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:u("path",{d:"M9 18l6-6-6-6"})})]})})}function ma({method:e,sessionId:t,nonce:n,email:a,billingName:r,billingApiUrl:i,onTokenizedBody:c,onErrorChange:l,onDecline:b,onCancel:x,runBeforeButtonClick:g,onButtonClick:w,isProcessing:v,submitButtonColor:R,submitButtonBorderRadius:d,submitButtonStyle:h,errorText:k}){let E=wn(),f=fa(),de=ya(),[S,le]=we(!1),Z=De(!1),[F,G]=we(!1),[W,oe]=we("loading"),N=ke(async()=>{if(!f||!de||v||Z.current||!F)return;Z.current=!0,le(!0);let j=g?await g("card"):{proceed:!0};if(!j.proceed){Z.current=!1,le(!1);return}w?.("card");let ce=j.sessionId??t,Re=j.nonce??n,fe=j.accountPatch?.email??a;try{l?.(null);let ae=await de.submit();if(ae.error){l?.(ae.error.message??"Payment failed.");return}let ee=await f.createPaymentMethod({elements:de});if(ee.error||!ee.paymentMethod){l?.(ee.error?.message??"Failed to create payment method.");return}let pe=ee.paymentMethod;if(!ce||!fe)throw new Error("Missing sessionId or email for payment.");let Y=pe.type||e,K=await new qn(i).createSessionIntent(ce,Re??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:Y,paymentMethodId:null,intentKind:"payment"});if(K.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Ee=K.clientSecret;if(typeof window<"u")try{localStorage.setItem(Rn,JSON.stringify({clientSecret:Ee,sessionId:ce,nonce:Re,accountPatch:j.accountPatch,paymentMethodId:pe.id,paymentMethodType:pe.type??e,gateway:"stripe"}))}catch{}let{error:ge,paymentIntent:te}=await f.confirmPayment({clientSecret:Ee,confirmParams:{return_url:window.location.href,payment_method:pe.id},redirect:"if_required"});if(ge){if(typeof window<"u")try{localStorage.removeItem(Rn)}catch{}let ie=ge.message??"Payment failed.";l?.(ie),b?.(Et("card",ie,{code:ge.code})),await Io({billingApiUrl:i,sessionId:ce,nonce:Re,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:ge.code??"provider_declined"}});return}let q=te?.status;if(!Co(q)){if(typeof window<"u")try{localStorage.removeItem(Rn)}catch{}let ie=q==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";l?.(ie),b?.(Et("card",ie,{code:q??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(Rn)}catch{}let C=typeof te?.payment_method=="string"?te.payment_method:te?.payment_method?.id;c({id:C??pe.id,type:"card",threeDSecureActionResultTokenId:te?.id,gateway:"stripe",paymentMethodType:pe.type??e},{accountPatch:j.accountPatch,sessionId:ce,nonce:Re})}catch(ae){l?.(ae instanceof Error?ae.message:"Payment failed. Please try again.")}finally{Z.current=!1,le(!1)}},[f,de,v,F,g,w,t,n,a,i,e,c,l,b]);return ze("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[u(tl,{onReady:()=>oe("ready"),onLoadError:()=>{oe("load_error"),ga(At(E),"stripe","apm")},onChange:j=>{G(!!j.complete)},options:{layout:{type:"accordion",defaultCollapsed:!1,radios:"never"},defaultValues:{billingDetails:{name:r&&r.trim().length>=3?r.trim():"FloPay Customer",...a?{email:a}:{}}}}}),u("button",{type:"button","data-testid":`flopay-stripe-method-pay-${e}`,onClick:()=>{N()},disabled:!F||S||v||W!=="ready",style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:R,color:"white",border:"none",borderRadius:d,fontSize:"1rem",fontWeight:600,cursor:!F||S||v||W!=="ready"?"not-allowed":"pointer",opacity:!F||S||v||W!=="ready"?.5:1,transition:"opacity 120ms ease-out",...h??{}},children:S?"Processing\u2026":`Pay with ${Cr(e)}`}),k&&u(yr,{margin:"0.75rem 0 0",children:k})]})}function Li({sessionId:e,nonce:t,email:n,billingName:a,billingApiUrl:r,paymentElementMethods:i,stripeInstance:c,paymentElementBaseOptions:l,onTokenizedBody:b,onErrorChange:x,onButtonClick:g,onDecline:w,runBeforeButtonClick:v,onLoadStateChange:R,isProcessing:d=!1,submitButtonColor:h="#4A49FF",submitButtonBorderRadius:k=8,submitButtonStyle:E,buttonAppearance:f,themeId:de,onExpandApm:S,expandedApmMethod:le}){let[Z,F]=we(null),[G,W]=we(null),oe=De(!1);pt(()=>{i.length>0&&c?R?.("ready"):c||R?.("loading")},[i.length,c,R]);let N=ke(async ee=>{if(!c||oe.current||d)return;oe.current=!0,W(ee);let pe=v?await v("card"):{proceed:!0};if(!pe.proceed){oe.current=!1,W(null);return}g?.("card");let Y=pe.sessionId??e,K=pe.nonce??t,Ee=pe.accountPatch?.email??n;try{if(x?.(null),!Y||!Ee)throw new Error("Missing sessionId or email for payment.");let ge=await new qn(r).createSessionIntent(Y,K??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:ee,paymentMethodId:null,intentKind:"payment"});if(ge.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let te=ge.clientSecret;if(typeof window<"u")try{localStorage.setItem(Rn,JSON.stringify({clientSecret:te,sessionId:Y,nonce:K,accountPatch:pe.accountPatch,paymentMethodType:ee,gateway:"stripe"}))}catch{}let{error:q,paymentIntent:C}=await c.confirmPayment({clientSecret:te,confirmParams:{return_url:window.location.href,payment_method_data:{type:ee,billing_details:{name:a&&a.trim().length>=3?a.trim():"FloPay Customer",...Ee?{email:Ee}:{}}}},redirect:"if_required"});if(q){if(typeof window<"u")try{localStorage.removeItem(Rn)}catch{}let Oe=q.message??"Payment failed.";x?.(Oe),w?.(Et("card",Oe,{code:q.code})),await Io({billingApiUrl:r,sessionId:Y,nonce:K,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:ee,providerDeclineReason:q.code??"provider_declined"}});return}let ie=C?.status;if(!Co(ie)){if(typeof window<"u")try{localStorage.removeItem(Rn)}catch{}let Oe=ie==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";x?.(Oe),w?.(Et("card",Oe,{code:ie??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(Rn)}catch{}let $e=typeof C?.payment_method=="string"?C.payment_method:C?.payment_method?.id;b({id:$e??C?.id,type:"card",threeDSecureActionResultTokenId:C?.id,gateway:"stripe",paymentMethodType:ee},{accountPatch:pe.accountPatch,sessionId:Y,nonce:K})}catch(ge){x?.(ge instanceof Error?ge.message:"Payment failed. Please try again.")}finally{oe.current=!1,W(null)}},[c,d,v,g,e,t,n,r,a,b,x,w]),[j,ce]=we(null),Re=S?le??null:j,fe=ke(ee=>{oe.current||d||Re&&Re!==ee||(Ii(ee)?S?S(ee):ce(ee):N(ee))},[Re,d,N,S]),ae=ut(()=>j?{...l,paymentMethodTypes:[j]}:null,[j,l]);return u("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:i.map(ee=>{let pe=le===ee,Y=G===ee,K=G!==null&&G!==ee||le!=null&&le!==ee;return ze(fl.Fragment,{children:[u(_l,{method:ee,themeId:de,submitting:Y,disabled:K,highlighted:pe,hasNextStep:Ii(ee),onClick:()=>fe(ee),backgroundColor:f?.backgroundColor,borderColor:f?.borderColor,textColor:f?.textColor,borderRadius:f?.borderRadius,fontFamily:f?.fontFamily}),!S&&j===ee&&ae&&c&&u(rr,{stripe:c,options:ae,children:u(ma,{method:ee,sessionId:e,email:n,billingName:a,billingApiUrl:r,onTokenizedBody:b,onErrorChange:x,onDecline:w,onCancel:()=>ce(null),runBeforeButtonClick:v,onButtonClick:g,isProcessing:d,submitButtonColor:h,submitButtonBorderRadius:k,submitButtonStyle:E})},ee)]},ee)})})}function xl({sessionId:e,nonce:t,billingApiUrl:n,email:a,userId:r,onComplete:i,onError:c,onDecline:l,onTokenizedBody:b,firstName:x,lastName:g,chv:w,className:v,isProcessing:R,error:d,onErrorChange:h,showPayPal:k=!0,showStripe:E=!0,enabledPaymentMethods:f,enabledPaymentMethodCountries:de,showApplePay:S=!0,showGooglePay:le=!0,layout:Z="default",theme:F,buttonsTheme:G,buttonsStyles:W,appearance:oe,cardButtonContent:N,cardBackButtonContent:j,cardTitleContent:ce,showSecurityFooter:Re,onButtonClick:fe,onBeforeButtonClick:ae,enableAVS:ee,cardFieldOrder:pe,cardPreFormSlot:Y,avsLayout:K="row",country:Ee,zip:ge,addressLine1:te,addressLine2:q,city:C,state:ie,onCountryChange:$e,onZipChange:Oe,avsCheck:me,checkoutType:T,checkoutLayout:ue,totalAmount:J=0,currency:_e="usd",initialCardOpen:mt=!1,directPaypal:Je,isSubscription:yt=!1,session:A,dataAttachmentPending:X=!1,debug:tt=!1}){let qe=wn(),ft=ta(),Ne=gl(yn),We=X||Ne.claimPending===!0,Xt=Po(),[Ge,Qt]=we(!1),[I,be]=we(null),[Ye,xe]=we(Ee??"US"),[St,je]=we(ge??""),[Ve,nt]=we(te??""),[Xe,In]=we(q??""),[at,Hn]=we(C??""),[Wt,Pn]=we(ie??""),[Zt,ir]=we({}),Bt=De(ge??""),kt=De(Ee??"US"),en=De(te??""),tn=De(q??""),Ft=De(C??""),Dt=De(ie??""),wt=De({});pt(()=>{let s=(L,H,se,V,Se)=>{if(wt.current[L])return;let Ae=H?.trim();!Ae||Ae===se.current||(se.current=Ae,V(Ae),Se?.(Ae))};s("country",Ee,kt,xe,$e),s("zip",ge,Bt,je,Oe),s("addressLine1",te,en,nt),s("addressLine2",q,tn,In),s("city",C,Ft,Hn),s("state",ie,Dt,Pn)},[Ee,ge,te,q,C,ie,$e,Oe]);let ne=ut(()=>il(ee),[ee]),Kn=ne!==null,D=ut(()=>ca(A),[A]),it=!!A?.vault?.html,Lt=!!A?.gateways?.pcivault,Be=!!(A?.gateways?.stripe?.enabledPaymentMethods??f)?.includes("card"),st=it||Be||Lt,He=!!(E&&st&&qe&&e),[_n,xn]=we(()=>Z!=="buttons"||mt?e??null:null),[zn,Wn]=we(0),Tn=Z!=="buttons"||mt||!!e&&_n===e,rt=ut(()=>!qe||!He||!e||!Tn?null:qe.cardCapture({sessionId:e,captureMethod:A?.captureMethod}),[qe,He,e,Tn,A?.captureMethod]),zt=ut(()=>{let s=Ye,L=ne?Le(ne.postal_code,s):!1;return El(s,St,L)},[ne,Ye,St]),{avsInvalid:dn,invalidAvsFields:Pt}=ut(()=>{let s={line1:!1,city:!1,state:!1,zip:!1};if(!He||!ne)return{avsInvalid:!1,invalidAvsFields:s};let L=Ye,H=(Se,Ae)=>Le(Se,L)&&!Ae.trim(),se={line1:H(ne.address_line_1,Ve),city:H(ne.city,at),state:H(ne.state,Wt),zip:zt.empty||zt.malformed};return{avsInvalid:se.line1||se.city||se.state||se.zip,invalidAvsFields:se}},[He,ne,Ye,Ve,at,Wt,zt]),[xt,nn]=we(!1),[un,Yt]=we(!1),[Ut,$t]=we(()=>da(A?.vault)),[Te,qt]=we(mt&&st?"card":"buttons"),[gt,bn]=we(null),Yn=Te==="expanding"||Te==="card",Vt=280,jt=De(null),Ot=ke(s=>{jt.current&&clearTimeout(jt.current),jt.current=setTimeout(()=>{jt.current=null,s()},Vt)},[Vt]);pt(()=>()=>{jt.current&&clearTimeout(jt.current)},[]);let On=ke(()=>{xn(e??null),Wn(s=>s+1),qt("expanding"),Ot(()=>qt("card"))},[Ot,e]),Nn=ke(()=>{qt("collapsing"),Ot(()=>qt("buttons"))},[Ot]),rn=ke(s=>{bn(s),qt("apm-expanding"),Ot(()=>qt("apm-form"))},[Ot]),Gt=ke(()=>{qt("apm-collapsing"),Ot(()=>{qt("buttons"),bn(null)})},[Ot]);pt(()=>{Z==="buttons"&&mt&&st&&(xn(e??null),qt("card"))},[Z,mt,st,e]);let[on,Ue]=we(null),_=De(!1),z=De(null),M=De("idle"),[ve,Ce]=we(null),m=De(ve);pt(()=>{m.current=ve},[ve]);let o=n||Xt,y=d??I,B=ut(()=>Pl(F),[F]),P=ut(()=>{let s=B?.buttonsLayout??rl(G);return W?{...s,...W,cardButton:{...s.cardButton,...W.cardButton},cardFormContainer:{...s.cardFormContainer,...W.cardFormContainer},backButton:{...s.backButton,...W.backButton},backButtonIcon:{...s.backButtonIcon,...W.backButtonIcon},submitButton:{...s.submitButton,...W.submitButton},title:{...s.title,...W.title}}:s},[B,G,W]),U=oe??B?.appearance,Fe=ut(()=>ho({appearance:U,buttonsStyles:P,layout:Z}),[U,P,Z]),Qe=Ne.inlineSessionPatchProcessing??!1,Q=(R??Ge)||Qe,$=o.replace(/\/+$/,""),p=ut(()=>oa({userId:r,email:a,firstName:x,lastName:g,country:Ee,zip:ge},Zt),[r,a,x,g,Ee,ge,Zt]),O=[p.firstName,p.lastName].filter(s=>!!s?.trim()).join(" "),he=ut(()=>qe?qe.getRawProvider():null,[qe]),Ie=ut(()=>ft?ft.getRawProvider():null,[ft]),Me=J||100,vn=ut(()=>U?yl(U):null,[U]),Tr=vn?{appearance:vn}:null,Oo=ut(()=>{let s=vn??{},L=s.rules??{};return{...s,rules:{...L,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...L[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...L[".AccordionItemContents"]??{}}}}},[vn]),ro=ut(()=>{let s=Pi(J);return{...s,currency:_e.toLowerCase(),paymentMethodCreation:"manual",...s.mode==="payment"?{captureMethod:"manual"}:{},...Tr}},[J,_e,Tr]),Fa=ut(()=>({mode:"payment",amount:Me,currency:_e.toLowerCase(),captureMethod:"manual",setupFutureUsage:"off_session",...Tr}),[Me,_e,Tr]),ye=ke(s=>{be(s),h?.(s)},[h]);pt(()=>{!He||!rt||rt.setCardFieldOrder?.(pe??null,ne==null)},[He,rt,pe,ne]),pt(()=>{(Te==="expanding"||Te==="collapsing"||Te==="apm-expanding"||Te==="apm-collapsing")&&ye(null)},[Te,ye]);let pn=ke((s,L,H)=>{l?.(Et(s,L,H))},[l]),sr=ke((s,L,H)=>{let se=H?.popupBlocked??$n(L),V=kl(s,se),Se=tr(H?.code)??An(L)??"external_payment_method_failed",Ae=new kn(V,"api_error",{code:"external_payment_method_failed",param:s});Ue(null),Z==="buttons"&&(qt("buttons"),bn(null)),ye(V),c?.(Ae),console.error("[FloPay] External payment method failed:",{method:s,code:Se,popupBlocked:se})},[Z,c,ye]);pt(()=>{if(!He||!e){$t(null);return}let s=da(A?.vault);if(s){$t(s);return}if(!Tn){$t(null);return}$t(null);let L=!0;return new qn($).getVaultCapture(e,t).then(H=>{if(!L)return;let se=da(H);se?$t(se):ye("Failed to load the secure card form.")}).catch(H=>{L&&ye(H instanceof Error?H.message:"Failed to load the secure card form.")}),()=>{L=!1}},[He,Tn,zn,e,A?.vault?.html,A?.vault?.messageToken,A?.vault?.expectedOrigin,$,t,ye]);let Cn=De({onComplete:i,onError:c,updateError:ye,emitDecline:pn,resolvedAccount:p,avsConfig:ne,avsCheckProp:me,sessionId:e,nonce:t,baseUrl:$,captureMethod:A?.captureMethod,paymentId:A?.paymentId,authorizationExpiresAt:A?.authorizationExpiresAt});Cn.current={onComplete:i,onError:c,updateError:ye,emitDecline:pn,resolvedAccount:p,avsConfig:ne,avsCheckProp:me,sessionId:e,nonce:t,baseUrl:$,captureMethod:A?.captureMethod,paymentId:A?.paymentId,authorizationExpiresAt:A?.authorizationExpiresAt};let No=De(!1),ds=ke(()=>{let{resolvedAccount:s,avsConfig:L,avsCheckProp:H}=Cn.current,se=kt.current||s.country||"US",V=L?Le(L.state,se):!1,Se=L?Le(L.address_line_1,se):!1,Ae=L?Le(L.postal_code,se):!1,lt=L?Le(L.city,se):!1,vt=L?Le(L.address_line_2,se):!1,Ze=Se&&!V&&Ae?Ei(se,(Bt.current??"").trim()):null,Rt=V?Dt.current:Ze;return{accountData:{userId:s.userId??"",email:s.email??"",firstName:s.firstName??"",lastName:s.lastName??"",...Ae&&Bt.current?{zip:Bt.current}:{},...lt&&Ft.current?{city:Ft.current}:{},...Rt?{state:Rt}:{},...Se&&en.current?{addressLine1:en.current}:{},...vt&&tn.current?{addressLine2:tn.current}:{},country:se},...H!==void 0?{avsCheck:H}:{},...L?{avsConfig:{country:Le(L.country,se),postal_code:Ae,address_line_1:Se,address_line_2:vt,city:lt,state:V}}:{}}},[]),Da=De(We);Da.current=We,pt(()=>{We||y!==Ti||Cn.current.updateError(null)},[We,y]),pt(()=>{!He||!rt||rt.setSubmitGate?.(dn||We)},[He,rt,dn,We]),pt(()=>{if(!He||!rt)return;No.current=!1;let s=!1,L=rt.on("submitting",()=>{nn(!0),z.current&&clearTimeout(z.current),M.current="validation-window",z.current=setTimeout(()=>{z.current=null,M.current==="validation-window"&&(M.current="processing")},bl),Ue("processing");let{baseUrl:Ae,sessionId:lt,nonce:vt,updateError:Ze,onError:Rt}=Cn.current;!lt||!vt||new qn(Ae).patchAccountSnapshot(lt,vt,ds(),{telemetryMode:"best_effort"}).catch(Pe=>{if(!vl(Pe))return;let Tt=Pe instanceof Error?Pe.message:"Please check your billing address and try again.";Ze(Tt),M.current="idle",Ue(null),Rt?.(Pe instanceof kn?Pe:new kn(Tt,"api_error"))})}),H=rt.on("complete",async Ae=>{if(hr(Ae.sessionId??Cn.current.sessionId),M.current="terminal",Ue("success"),await new Promise(Ze=>setTimeout(Ze,fn)),No.current)return;No.current=!0;let lt=Cn.current,vt=ca(lt)||Ae.outcome==="authorized";Cn.current.onComplete?.(vt?{status:"authorized",paymentIntentId:Ae.intentId,paymentId:Ae.paymentId??lt.paymentId,sessionId:Ae.sessionId??lt.sessionId,authorizationExpiresAt:Ae.authorizationExpiresAt??lt.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",paymentIntentId:Ae.intentId,checkoutMethod:"card"})}),se=rt.on("decline",async Ae=>{let{updateError:lt,emitDecline:vt}=Cn.current,Ze=Ae.message??"Your payment was declined. Please try another card or contact your bank.";M.current="terminal",lt(Ze),Ue("error");let Rt=Ae.failureOutcome??nl(Ae.declineReason)??"authorization_declined";vt("card",Ze,{code:Rt,declineCode:Rt}),await new Promise(Pe=>setTimeout(Pe,Jt)),!s&&(M.current="idle",Ue(null))}),V=rt.on("error",async Ae=>{let{updateError:lt,onError:vt}=Cn.current,Ze=Ae.message??"There was a problem processing your payment. Please try again.";M.current="terminal",lt(Ze),Ue("error"),vt?.(new kn(Ze,"api_error",{code:Ae.failureOutcome??"capture_failed"})),await new Promise(Rt=>setTimeout(Rt,Jt)),!s&&(M.current="idle",Ue(null))}),Se=rt.on("blocked",()=>{if(!Da.current){nn(!0);return}Cn.current.updateError(Ti)});return()=>{s=!0,z.current&&(clearTimeout(z.current),z.current=null),M.current="idle",L(),H(),se(),V(),Se()}},[He,rt]);let Sn=!!Je?.clientId,Mr=Array.isArray(f),oo=Mr&&f.length>0,us=Mr&&f.includes("paypal"),{expressMethods:ao,paymentElementMethods:Ar}=ut(()=>ml(f,{excludePaypal:Sn}),[f,Sn]),La=Sn||!!ft,ps=ut(()=>La?ao.filter(s=>s!=="paypal"):ao,[ao,La]),ms=ut(()=>{let s=[];return S&&s.push("apple_pay"),le&&s.push("google_pay"),s},[S,le]),io=Mr?ps:ms,ys=E&&io.length>0,Uo=Kn?Ye:Ee,so=ut(()=>{let s=Uo?.trim().toUpperCase();return s?de?Ar.filter(L=>{let H=de[L];return!H||H.length===0||H.includes(s)}):dl(Ar,Uo):Ar},[Ar,Uo,de]),$o=ut(()=>({mode:"payment",amount:Me,currency:_e.toLowerCase(),paymentMethodCreation:"manual",appearance:Oo}),[Me,_e,Oo]),[za,Oa]=we("loading"),[Na,Ua]=we("loading"),[$a,qa]=we("loading"),[fs,qo]=we(!1),[Va,Vo]=we("loading"),[lo,gs]=we();pt(()=>{gs(bi())},[]);let ja=k&&(Sn||(Mr?us:lo===!1)),Ha=E&&ys,Br=!We&&ja&&Sn,Ka=Va==="retrying"||Va==="exhausted",Fr=!We&&ja&&!!Ie&&(!Sn||Ka),Dr=!We&&Ha&&!!he,Lr=!We&&E&&oo&&so.length>0&&!!he,hs=Br&&!Ka?fs:Fr&&Bi(za),Ps=Dr&&Bi(Na),bs=Lr&&$a!=="load_error",Wa=s=>s==="loading"||s==="ready",Ya=Br||Fr&&Wa(za)||Dr&&Wa(Na)||Lr&&$a!=="load_error",co=De(!1);pt(()=>{if(!co.current){if(!E&&!k){co.current=!0;let s=new kn("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");c?.(s),ye(s.message)}else if(!E&&k&&!Sn&&!Ie){co.current=!0;let s=new kn("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");c?.(s),ye(s.message)}else if(lo!==void 0&&!We&&!st&&!Ya){co.current=!0;let s=new kn("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"});c?.(s),ye(s.message)}}},[E,k,Sn,Ie,lo,We,st,Ya,c,ye]);let Ga=De(!1);pt(()=>{if(Ga.current||!oo)return;let s=[];S!==!0&&s.push("showApplePay"),le!==!0&&s.push("showGooglePay"),s.length!==0&&(Ga.current=!0,console.warn(`[FloPay] ${s.join(" / ")} ${s.length===1?"is":"are"} deprecated: the Apple Pay / Google Pay surface is now driven by \`gateways.stripe.enabledPaymentMethods\` on the session response. Remove the legacy prop(s) to silence this warning.`))},[oo,S,le]);let Ja=ke((s,L)=>Ne.applyInlineSessionPatch?Ne.applyInlineSessionPatch(s).then(H=>({error:null,sessionId:H.sessionId||e,nonce:H.session?.clientSecret||t})).catch(H=>{let se=Ai(L,H);return ye(se.message),c?.(se),{error:se,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[Ne.applyInlineSessionPatch,t,c,e,ye]),mn=ke(async s=>{if(!ae)return{proceed:!0};try{let L=await ae({method:s,sessionId:e||void 0,createSession:Ne.inlineSessionDraft});if(L===!1)return{proceed:!1};if(L&&typeof L=="object"){L.account&&ir(se=>({...se??{},...L.account}));let H=await Ja(L,s);return H.error?{proceed:!1,accountPatch:L.account}:{proceed:!0,accountPatch:L.account,sessionId:H.sessionId,nonce:H.nonce}}return{proceed:!0}}catch(L){let H=Ai(s,L);return ye(H.message),c?.(H),{proceed:!1}}},[Ja,Ne.inlineSessionDraft,ae,c,e,ye]),Xa=ke(async(s,L)=>{if(_.current)return;_.current=!0,Qt(!0),Ue("processing"),ye(null);let H=L?.sessionId??e,se=L?.nonce??t,V=oa(p,L?.accountPatch),Se=L?.completionPaymentMethodId??Kr(s),Ae=s.originalPaymentMethodId?{...s,originalPaymentMethodId:void 0}:s;try{let vt=await new qn($).processPayment(V.userId??"",{sessionId:H,nonce:se,tokenizedData:Ae,accountData:{userId:V.userId??"",email:V.email??"",firstName:V.firstName??"",lastName:V.lastName??"",...ne?(()=>{let Pe=kt.current,Tt=Le(ne.state,Pe),Kt=Le(ne.address_line_1,Pe),Qn=Le(ne.postal_code,Pe),Zn=Kt&&!Tt&&Qn?Ei(Pe,(Bt.current??"").trim()):null,Mt=Tt?Dt.current:Zn;return{country:Pe,...Qn&&Bt.current?{zip:Bt.current}:{},...Le(ne.city,Pe)&&Ft.current?{city:Ft.current}:{},...Mt?{state:Mt}:{},...Kt&&en.current?{addressLine1:en.current}:{},...Le(ne.address_line_2,Pe)&&tn.current?{addressLine2:tn.current}:{}}})():{}},chv:w,avsCheck:me??!1,checkoutType:T,checkoutLayout:ue,avsConfig:ne?{country:Le(ne.country,kt.current),postal_code:Le(ne.postal_code,kt.current),address_line_1:Le(ne.address_line_1,kt.current),address_line_2:Le(ne.address_line_2,kt.current),city:Le(ne.city,kt.current),state:Le(ne.state,kt.current)}:void 0});if(vt.ok){let Pe=vt.status===204?null:await vt.json().catch(()=>null),Tt=ca(A)||Pe?.status==="authorized";hr(H),Ue("success"),Ce(null),await new Promise(Kt=>setTimeout(Kt,fn)),i?.(Tt?{status:"authorized",...typeof Pe?.paymentId=="string"?{paymentId:Pe.paymentId}:A?.paymentId?{paymentId:A.paymentId}:{},sessionId:typeof Pe?.sessionId=="string"?Pe.sessionId:H,...typeof Pe?.authorizationExpiresAt=="string"?{authorizationExpiresAt:Pe.authorizationExpiresAt}:A?.authorizationExpiresAt?{authorizationExpiresAt:A.authorizationExpiresAt}:{},paymentIntentId:s.threeDSecureActionResultTokenId,paymentMethodId:Se,checkoutMethod:s.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:s.threeDSecureActionResultTokenId,paymentMethodId:Se,checkoutMethod:s.isPaypal?"paypal":"card"});return}let Ze=await vt.json().catch(()=>null);if(Ze?.type==="paypal_redirect_required"){let Pe=Ze.threeDSecureToken,Tt=Ze.paymentMethodId||s.id||"";if(!qe||!Pe){Ue("error"),ye("PayPal authorization required but no token provided.");return}try{let Kt=ft?.getRawProvider();if(!Kt){ye("PayPal is not available.");return}let Qn={return_url:window.location.href};Tt&&(Qn.payment_method=Tt);let{error:Zn}=await Kt.confirmPayment({clientSecret:Pe,confirmParams:Qn,redirect:"if_required"});if(Zn){Ue("error");let Mt=Zn.message??"PayPal payment failed.";ye(Mt),pn("paypal",Mt,{code:Zn.code})}}catch(Kt){Ue("error"),ye(Kt instanceof Error?Kt.message:"PayPal authorization failed.")}return}if(Ze?.type==="paypal_direct_required"){let Pe=Ze.orderId;if(!Pe){Ue("error"),ye("PayPal retry required but no order id provided.");return}let Tt=m.current?.attempts??0;if(Tt>=2){Ue("error"),ye("PayPal payment could not be completed after multiple attempts."),pn("paypal","paypal_direct_required retry limit exceeded");return}qo(!1),Vo("loading"),Ce({orderId:Pe,attempts:Tt+1}),Ue(null);return}Ue("error");let Rt=Ze?.message??"Payment failed. Please try again.";ye(Rt),pn(s.isPaypal?"paypal":"card",Rt,{code:Ze?.code??Ze?.gatewayErrorCode,declineCode:Ze?.declineCode??Ze?.gatewayDeclineReason}),await new Promise(Pe=>setTimeout(Pe,Jt))}catch(lt){Ue("error"),ye(lt instanceof Error?lt.message:"An unexpected error occurred"),await new Promise(vt=>setTimeout(vt,Jt))}finally{Qt(!1),Ue(null),_.current=!1}},[$,e,t,p,O,w,qe,ft,A,i,c,ye,pn]),an=ke((s,L)=>{b?b(s):Xa(s,L)},[b,Xa]),Qa=De(!1);pt(()=>{if(typeof window>"u"||Qa.current)return;let s=new URLSearchParams(window.location.search),L=s.get("payment_intent"),H=s.get("payment_intent_client_secret"),se=s.get("redirect_status");if(!L||!H)return;let V=Rt=>{let Pe=localStorage.getItem(Rt);if(!Pe)return null;try{return JSON.parse(Pe)}catch{return localStorage.removeItem(Rt),null}},Se=V(Rn)??V(xi),Ae;if(Se?.clientSecret){if(Se.clientSecret!==H)return;Ae={...Se.accountPatch?{accountPatch:Se.accountPatch}:{},...Se.sessionId?{sessionId:Se.sessionId}:{},...Se.nonce?{nonce:Se.nonce}:{}}}else if(Se?.sessionId&&Se.sessionId!==e)return;Qa.current=!0,localStorage.removeItem(Rn),localStorage.removeItem(xi);let lt=new URL(window.location.href);lt.searchParams.delete("payment_intent"),lt.searchParams.delete("payment_intent_client_secret"),lt.searchParams.delete("redirect_status"),window.history.replaceState({},"",lt.toString());let vt=Se?.paymentMethodType??Se?.tokenType??"card",Ze="card";(async()=>{let Rt=qe?.getRawProvider();if(!Rt){let Mt="Payment is not available \u2014 please refresh and try again.";ye(Mt),pn(Ze,Mt);return}if(se==="failed"){let Mt="Payment was declined. Please try again.";ye(Mt),pn(Ze,Mt);return}let{paymentIntent:Pe,error:Tt}=await Rt.retrievePaymentIntent(H);if(Tt){let Mt=Tt.message??"Failed to retrieve payment status.";ye(Mt),pn(Ze,Mt,{code:Tt.code});return}let Kt=Pe?.status,Qn=Co(Kt);if(!Pe||!Qn){let Mt=Kt==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";ye(Mt),pn(Ze,Mt,{code:Kt??"missing_payment_intent"});return}let Zn=typeof Pe.payment_method=="string"?Pe.payment_method:Pe.payment_method?.id;an({id:Zn??Se?.paymentMethodId??Se?.tokenId??Pe.id,type:"card",threeDSecureActionResultTokenId:Pe.id,gateway:Se?.gateway??"stripe",paymentMethodType:vt},Ae)})()},[e,an,qe,ye,pn]);let jo=ke(s=>{s.preventDefault()},[]);if(!(qe!==null))return u("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let zr=Z==="buttons",Ht=U?.variables,vs=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),Ho=Ht?.colorBackground,Cs=Ho&&!vs.has(Ho)?Ho:void 0,Or=P.cardInputBorder??(zr?"#e5e7eb":"#A4A4FF"),Ko=Ht?.colorDanger??"#dc2626",Gn=s=>xt&&s?Ko:Or,uo=(zt.malformed||zt.empty)&&(un||xt),Ss=uo?Ko:Gn(Pt.zip),Wo=P.cardFormContainer?.backgroundColor??Cs??(zr?"white":"#EDEDFF"),Nr=P.cardInputBackground??Ht?.colorBackground??"white",Yo=cr(j),Za=cr(ce),lr=P.nameInput,ei=P.cardInputFontSize??Il(lr?.fontSize)??Ht?.fontSizeBase??"16px",ti=typeof lr?.fontFamily=="string"?lr.fontFamily:Ht?.fontFamily??"Poppins, sans-serif",ni=ea(lr?.fontWeight)??400,ws=P.cardInputColor??(typeof lr?.color=="string"?lr.color:void 0)??Ht?.colorText??"#262833",ks=P.cardInputPlaceholderColor??"#9ca3af",bt=Ht?.borderRadius??"8px",Jn=Ht?.borderRadius??P.cardButton?.borderRadius??bt,Xn=Ht?.colorPrimary??"#4A49FF",Rs=Ht?.colorPrimaryHover??mr(Xn,.12),Go=Ht?.colorText??"#262833",ri={fontSize:ei,fontFamily:ti,fontWeight:ni,color:ws,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},Es={"--flopay-input-placeholder-color":ks,"--flopay-input-font-size":ei,"--flopay-input-font-family":ti,"--flopay-input-font-weight":String(ni)},Ur=P.cardFormContainer??{},Jo=Ur.padding??(zr?"0":"1rem"),Xo=Ur.borderRadius??bt,Is=rt&&Ut?u(jr,{capture:rt,html:Ut.html,messageToken:Ut.messageToken,expectedOrigin:Ut.expectedOrigin,theme:Fe,onReady:()=>{if(!ne||typeof document>"u")return;let s=()=>{document.querySelector('[data-testid="flopay-avs-fields"]')?.querySelector("input:not([disabled]), select:not([disabled])")?.focus()};s();let L=0,H=window.setInterval(()=>{L+=1;let se=document.activeElement;!!se&&se.tagName==="IFRAME"&&se.id==="flopay_vault_form_iframe"?(s(),window.clearInterval(H)):L>=50&&window.clearInterval(H)},100)},onError:s=>ye(s),onValidation:s=>{let L=M.current;(L==="idle"||L==="validation-window")&&(ye(s),s&&M.current==="validation-window"&&(z.current&&(clearTimeout(z.current),z.current=null),M.current="idle",Ue(null)))}}):u("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"}),oi=ze("div",{style:{backgroundColor:Wo,borderRadius:Xo,...Ur,padding:Jo,...Es,display:"flex",flexDirection:"column"},children:[u("style",{children:`
|
|
25
|
+
`,Po=44;function sa(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 ul={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"},_i={width:"100%",minHeight:Po,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 pl(e){switch(e){case"paypal":return"PayPal";case"apple_pay":return"Apple Pay";case"google_pay":return"Google Pay";default:return"Card"}}function Ci(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function xi(e){return e==="paypal"?"PayPal":hr(e)}function ml(e,t){let n=`We couldn't open ${xi(e)}. Try again or choose another payment method.`;return t?`${n} Allow pop-ups for this site, then try again.`:n}function Ti(e){let t=Be(0),n=Be(null),s=Be(null),a=Ce((c=s.current)=>{let P=c;P?.timer&&(clearTimeout(P.timer),P.timer=null)},[]),i=Ce((c,P)=>{typeof document<"u"&&document.visibilityState!=="visible"||(a(c),c.timer=setTimeout(()=>{c.timer=null,s.current?.generation===c.generation&&(s.current=null,n.current=c.generation,e(c.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}))},P))},[a,e]),u=Ce(c=>{c.yieldedControl&&i(c,600)},[i]),l=Ce(c=>{a();let P=t.current+1;t.current=P,n.current=null;let k={generation:P,method:c,timer:null,yieldedControl:!1};return s.current=k,P},[a]),v=Ce(c=>{let P=s.current;return typeof c=="number"&&P?.generation!==c?!1:(a(P),s.current=null,(typeof c!="number"||n.current===c)&&(n.current=null),!0)},[a]),N=Ce(c=>{let P=s.current,k=c??P?.generation??t.current;(!c||P?.generation===c)&&(a(P),s.current=null),n.current=k},[a]),h=Ce(c=>n.current===(c??t.current),[]),E=Ce(c=>s.current?.generation===c&&n.current!==c,[]),C=Ce(()=>{let c=s.current;c&&u(c)},[u]),F=Ce(()=>{let c=s.current;c&&(c.yieldedControl=!0,a(c))},[a]);return ct(()=>{let c=()=>{document.visibilityState==="visible"?C():F()},P=()=>{F()};return document.addEventListener("visibilitychange",c),window.addEventListener("blur",P),window.addEventListener("focus",C),()=>{document.removeEventListener("visibilitychange",c),window.removeEventListener("blur",P),window.removeEventListener("focus",C),a()}},[a,F,C]),{startAttempt:l,finishAttempt:v,invalidateAttempt:N,isAttemptInvalidated:h,isAttemptCurrent:E}}function yl(e){let t=Qs(e);return`Enter a valid ${na(e)}${t?` (e.g. ${t})`:""}`}function fl(e,t,n){let s=Js(e),a=t.trim(),i=n&&s,u=i&&!a,l=i&&!!a&&!Xs(e,a);return{visible:n,supported:s,required:i,empty:u,malformed:l}}function Si(e,t){return t instanceof Cn?t:new Cn(t instanceof Error?t.message:`${pl(e)} before-click hook failed.`,"validation_error")}function ta(){return d("style",{children:dl})}function gl(e){return typeof e=="number"?`${e}px`:e}function Mi(e,t){let n=e.availablePaymentMethods;return n&&t.some(s=>n[s])?"ready":"unavailable"}function Ai({state:e,placeholderTestId:t,borderRadius:n=8,children:s}){return e==="unavailable"||e==="load_error"?null:Le("div",{style:{position:"relative",minHeight:44},children:[d("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"}}),d("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:s})]})}function wi(e){return e!=="unavailable"&&e!=="load_error"}function la(e){return d(Pl,{...e})}function ki({sessionId:e,nonce:t,email:n,billingApiUrl:s,onTokenizedBody:a,onErrorChange:i,isProcessing:u=!1,onButtonClick:l,onDecline:v,onTechnicalFailure:N,runBeforeButtonClick:h,onLoadStateChange:E,placeholderBorderRadius:C}){let F=vn(),c=aa(),P=oa(),[k,T]=ve("loading");ct(()=>{E?.(k)},[k,E]);let[g,me]=ve(!1),M=Be(!1),le=Be(null),ce=Be(null),[z,J]=ve(0),[H,oe]=ve(!1),j=Be(!1),K=Be(new Map),{startAttempt:ie,finishAttempt:xe,invalidateAttempt:he,isAttemptInvalidated:de,isAttemptCurrent:Q}=Ti((V,b,te)=>{N?.(V,b,{...te,popupBlocked:te?.popupBlocked??On(b)}),oe(!0),J($e=>$e+1)});ct(()=>{H&&ce.current?.focus()},[H,z]);let ye=Ce(()=>{J(V=>V+1)},[]),Te=Ce((V,b,te)=>{he(te),N?.("paypal",V,{code:b,popupBlocked:On(V)}),oe(!0),ye()},[he,N,ye]),Z=Ce(()=>{window.setTimeout(()=>{(le.current?.querySelector("iframe")??le.current)?.focus()},0)},[]);ct(()=>{j.current&&(j.current=!1,Z())},[Z,z]);let Ue=Ce(()=>{oe(!1),i?.(null),Z()},[Z,i]);ct(()=>{if(!c||M.current)return;let V=new URLSearchParams(window.location.search),b=V.get("payment_intent"),te=V.get("payment_intent_client_secret"),$e=V.get("redirect_status");if(!b||!te)return;M.current=!0;let ze;try{let R=localStorage.getItem(jr);if(R){let re=JSON.parse(R);re.clientSecret===te&&(ze={...re.accountPatch?{accountPatch:re.accountPatch}:{},...re.sessionId?{sessionId:re.sessionId}:{},...re.nonce?{nonce:re.nonce}:{}})}}catch{}try{localStorage.removeItem(jr)}catch{}let ae=new URL(window.location.href);ae.searchParams.delete("payment_intent"),ae.searchParams.delete("payment_intent_client_secret"),ae.searchParams.delete("redirect_status"),window.history.replaceState({},"",ae.toString()),(async()=>{try{if(me(!0),$e==="failed"){let W="PayPal payment was declined. Please try again.";i?.(W),v?.(It("paypal",W));return}let{paymentIntent:R,error:re}=await c.retrievePaymentIntent(te);if(re){i?.(re.message??"Failed to retrieve PayPal payment status.");return}if(R&&(R.status==="requires_capture"||R.status==="succeeded")){let W=typeof R.payment_method=="string"?R.payment_method:R.payment_method?.id;a({id:W??R.id,type:"card",threeDSecureActionResultTokenId:R.id,isPaypal:!0},ze)}else{let W="PayPal payment was not completed. Please try again.";i?.(W),v?.(It("paypal",W))}}catch(R){i?.(R instanceof Error?R.message:"Failed to complete PayPal payment.")}finally{me(!1)}})()},[c,a,i,v]);let Fe=Ce(async V=>{if(u||g){V.reject();return}let b=h?await h("paypal"):{proceed:!0};if(!b.proceed){K.current.delete(z),V.reject();return}let te=ie("paypal");K.current.set(z,{generation:te,accountPatch:b.accountPatch,sessionId:b.sessionId,nonce:b.nonce}),oe(!1),l?.("paypal"),V.resolve()},[K,u,l,h,ie,g,z]),we=Ce(async V=>{if(!c||!P)return;let b=K.current.get(z);if(b&&!Q(b.generation)){K.current.delete(z);return}if(!b&&de()||b&&!xe(b.generation))return;b||xe();let te=b??null;if(K.current.delete(z),!te&&h){let R=await h("paypal");if(!R.proceed){V.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}te={accountPatch:R.accountPatch,sessionId:R.sessionId,nonce:R.nonce}}let $e=te?.sessionId??e,ze=te?.nonce??t,ae=te?.accountPatch?.email??n;try{if(me(!0),i?.(null),!$e||!ae)throw new Error("Missing sessionId or email for PayPal payment");let R=c.createPaymentMethod,{error:re,paymentMethod:W}=await R({type:"paypal"});if(re){Te(re,"stripe_paypal_create_payment_method_failed",b?.generation),V.paymentFailed({reason:"fail"});return}let ke=await new Un(s).createSessionIntent($e,ze??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:W?.id??null,intentKind:"payment"});if(ke.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let dt=ke.clientSecret,Ge={return_url:window.location.href};if(W?.id&&(Ge.payment_method=W.id),typeof window<"u")try{localStorage.setItem(jr,JSON.stringify({clientSecret:dt,sessionId:$e,nonce:ze,accountPatch:te?.accountPatch}))}catch{}let{error:pt,paymentIntent:_}=await c.confirmPayment({clientSecret:dt,confirmParams:Ge,redirect:"if_required"});if(pt){if(typeof window<"u")try{localStorage.removeItem(jr)}catch{}if($r(pt)){let et=pt.message??"Your payment was declined.";i?.(et),v?.(It("paypal",et,{code:Tn(pt),declineCode:yr(pt)})),await bo({billingApiUrl:s,sessionId:$e,nonce:ze,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:Tn(pt)??"provider_declined"}})}else Te(pt,"stripe_paypal_confirm_failed",b?.generation);return}if(typeof window<"u")try{localStorage.removeItem(jr)}catch{}let Y=typeof _?.payment_method=="string"?_.payment_method:_?.payment_method?.id;a({id:Y??_?.id,type:"card",threeDSecureActionResultTokenId:_?.id,isPaypal:!0},{accountPatch:te?.accountPatch,sessionId:$e,nonce:ze});return}catch(R){Te(R,"stripe_paypal_failed",b?.generation)}finally{me(!1)}},[c,P,e,t,n,s,a,i,v,h,Te,xe,Q,de,z]);return Le(gr,{children:[d(Ai,{state:k,placeholderTestId:"flopay-paypal-placeholder",borderRadius:C,children:Le("div",{ref:le,tabIndex:-1,"data-testid":"flopay-paypal-focus-target","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[H&&d("button",{ref:ce,type:"button","data-testid":"flopay-paypal-retry-button",onClick:Ue,style:_i,children:"Try PayPal again"}),d(Ei,{onReady:V=>T(Mi(V,["paypal"])),onLoadError:()=>{T("load_error"),ia(At(F),"paypal","paypal")},onClick:Fe,onConfirm:we,onCancel:()=>{let V=K.current.get(z);K.current.delete(z),At(F)?.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),he(V?.generation),oe(!1),j.current=!0,ye()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:!1,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},z)]})}),g&&d(bn,{status:"processing"})]})}function Ri({sessionId:e,nonce:t,email:n,billingApiUrl:s,intentKind:a,expressMethods:i,onTokenizedBody:u,onErrorChange:l,onButtonClick:v,onDecline:N,onTechnicalFailure:h,runBeforeButtonClick:E,onLoadStateChange:C,placeholderBorderRadius:F}){let c=vn(),P=aa(),k=oa(),[T,g]=ve("loading");ct(()=>{C?.(T)},[T,C]);let[me,M]=ve(!1),le=Be(null),ce=Be(null),[z,J]=ve(0),[H,oe]=ve(!1),[j,K]=ve("google_pay"),ie=Be(!1),xe=Be("google_pay"),he=Be("google_pay"),de=Be(new Map),{startAttempt:Q,finishAttempt:ye,invalidateAttempt:Te,isAttemptInvalidated:Z,isAttemptCurrent:Ue}=Ti((ae,R,re)=>{h?.(ae,R,{...re,popupBlocked:re?.popupBlocked??On(R)}),K(ae),oe(!0),J(W=>W+1)});ct(()=>{H&&ce.current?.focus()},[H,z]);let Fe=Ce(()=>{J(ae=>ae+1)},[]),we=Ce((ae,R,re,W)=>{Te(W),h?.(ae,R,{code:re,popupBlocked:On(R)}),K(ae),oe(!0),Fe()},[Te,h,Fe]),V=Ce(()=>{window.setTimeout(()=>{(le.current?.querySelector("iframe")??le.current)?.focus()},0)},[]);ct(()=>{ie.current&&(ie.current=!1,V())},[V,z]);let b=Ce(()=>{oe(!1),l?.(null),V()},[V,l]),te=Ce(async ae=>{if(!P||!k)return;let R=de.current.get(z);if(R&&!Ue(R.generation)){de.current.delete(z);return}if(!R&&Z()||R&&!ye(R.generation))return;R||ye();let re=ae.expressPaymentType??R?.method??xe.current,W=R??null;de.current.delete(z);let ke=Ci(re);if(!W&&E){let Y=await E(ke);if(!Y.proceed){ae.paymentFailed({reason:"fail",message:"Wallet checkout was cancelled."});return}W={accountPatch:Y.accountPatch,sessionId:Y.sessionId,nonce:Y.nonce}}let dt=ke,Ge=W?.sessionId??e,pt=W?.nonce??t,_=W?.accountPatch?.email??n;try{M(!0),l?.(null);let{error:Y}=await k.submit();if(Y){we(re,Y,"stripe_wallet_submit_failed",R?.generation);return}let{error:et,paymentMethod:qe}=await P.createPaymentMethod({elements:k});if(et||!qe){we(re,et??new Error("Failed to create payment method."),"stripe_wallet_create_payment_method_failed",R?.generation);return}if(!Ge||!_)throw new Error("Missing sessionId or email for wallet payment");let mt=await new Un(s).createSessionIntent(Ge,pt??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:re??ke,paymentMethodId:qe.id,intentKind:a});if(mt.provider!=="stripe")throw new Error("Invalid provider returned for wallet intent");let Ne=mt.clientSecret,{error:He,intentId:Jt}=il(Ne)?await P.confirmCardSetup(Ne,{payment_method:qe.id}).then(Ye=>({error:Ye.error,intentId:Ye.setupIntent?.id})):await P.confirmCardPayment(Ne,{payment_method:qe.id}).then(Ye=>({error:Ye.error,intentId:Ye.paymentIntent?.id}));if(He){if($r(He)){let Ye=He.message??"Your payment was declined.";l?.(Ye),N?.(It(dt,Ye,{code:Tn(He),declineCode:yr(He)})),await bo({billingApiUrl:s,sessionId:Ge,nonce:pt,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:re??ke,providerDeclineReason:Tn(He)??"provider_declined"}})}else we(re,He,"stripe_wallet_confirm_failed",R?.generation);return}u({id:qe.id,type:"card",threeDSecureActionResultTokenId:Jt},{accountPatch:W?.accountPatch,sessionId:Ge,nonce:pt})}catch(Y){we(re,Y,"stripe_wallet_failed",R?.generation)}finally{M(!1)}},[P,k,e,t,n,s,a,u,l,N,E,we,ye,Ue,Z,z]),$e=lt(()=>{let ae=["applePay","googlePay","paypal","link","amazonPay","klarna"],R=new Set(["applePay","googlePay"]),re=new Set(i.map(Pi)),W={};for(let ke of ae)re.has(ke)?W[ke]=R.has(ke)?"always":"auto":W[ke]="never";return W},[i]),ze=lt(()=>i.map(Pi),[i]);return Le(gr,{children:[d(Ai,{state:T,placeholderTestId:"flopay-wallet-placeholder",borderRadius:F,children:Le("div",{ref:le,tabIndex:-1,"data-testid":"flopay-wallet-focus-target","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[H&&Le("button",{ref:ce,type:"button","data-testid":"flopay-wallet-retry-button",onClick:b,style:_i,children:["Try ",xi(j)," again"]}),d(Ei,{onReady:ae=>{g(Mi(ae,ze))},onLoadError:ae=>{g("load_error"),ia(At(c),"stripe","wallet")},onClick:async ae=>{xe.current=ae.expressPaymentType,he.current=Ci(ae.expressPaymentType);let R=E?await E(he.current):{proceed:!0};if(!R.proceed){de.current.delete(z),ae.reject();return}let re=Q(ae.expressPaymentType);de.current.set(z,{generation:re,method:ae.expressPaymentType,accountPatch:R.accountPatch,sessionId:R.sessionId,nonce:R.nonce}),oe(!1),v?.(he.current),ae.resolve()},onConfirm:te,onCancel:()=>{let ae=de.current.get(z);de.current.delete(z),At(c)?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet"}),Te(ae?.generation),oe(!1),ie.current=!0,Fe()},options:{buttonType:{applePay:"plain",googlePay:"plain"},paymentMethods:$e,layout:{maxColumns:1,overflow:"never"}}},z)]})}),me&&d(bn,{status:"processing"})]})}function hl({method:e,themeId:t,submitting:n=!1,disabled:s=!1,highlighted:a=!1,hasNextStep:i=!1,onClick:u,backgroundColor:l,borderColor:v,textColor:N,borderRadius:h,fontFamily:E}){let C=tl(e,t),F=ni[e],c=C?.backgroundColor??l??"#ffffff",P=C?.borderColor??v??"#d1d5db",k=C?.textColor??N??"#262833";return d("button",{type:"button","data-testid":`flopay-stripe-method-button-${e}`,"data-method":e,onClick:()=>{!n&&!s&&u()},disabled:n||s,"aria-busy":n||void 0,style:{position:"relative",width:"100%",boxSizing:"border-box",height:Po,padding:"0 1rem",backgroundColor:c,color:k,border:`1px solid ${P}`,borderRadius:h??8,fontSize:"0.95rem",fontWeight:600,fontFamily:E,cursor:n||s?"not-allowed":"pointer",opacity:s&&!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:a?"0 0 0 2px rgba(74, 73, 255, 0.15)":void 0},children:n?d("span",{style:{margin:"0 auto"},children:`Connecting to ${hr(e)}\u2026`}):Le(gr,{children:[Le("span",{style:{display:"inline-flex",alignItems:"center",gap:el(e)?8:0},children:[F?d("img",{src:F,alt:"","aria-hidden":"true",loading:"lazy",decoding:"async",width:30,height:20,style:{width:30,height:20,flexShrink:0,borderRadius:3,objectFit:"contain",display:"inline-flex"}}):C?.logoSvg?d("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:C.logoSvg}}):null,d("span",{children:hr(e)})]}),i&&d("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:k,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:d("path",{d:"M9 18l6-6-6-6"})})]})})}function ra({method:e,sessionId:t,nonce:n,email:s,billingName:a,billingApiUrl:i,onTokenizedBody:u,onErrorChange:l,onDecline:v,onCancel:N,runBeforeButtonClick:h,onButtonClick:E,isProcessing:C,submitButtonColor:F,submitButtonBorderRadius:c,submitButtonStyle:P,errorText:k}){let T=vn(),g=aa(),me=oa(),[M,le]=ve(!1),ce=Be(!1),[z,J]=ve(!1),[H,oe]=ve("loading"),j=Ce(async()=>{if(!g||!me||C||ce.current||!z)return;ce.current=!0,le(!0);let K=h?await h("card"):{proceed:!0};if(!K.proceed){ce.current=!1,le(!1);return}E?.("card");let ie=K.sessionId??t,xe=K.nonce??n,he=K.accountPatch?.email??s;try{l?.(null);let de=await me.submit();if(de.error){l?.(de.error.message??"Payment failed.");return}let Q=await g.createPaymentMethod({elements:me});if(Q.error||!Q.paymentMethod){l?.(Q.error?.message??"Failed to create payment method.");return}let ye=Q.paymentMethod;if(!ie||!he)throw new Error("Missing sessionId or email for payment.");let Te=ye.type||e,Z=await new Un(i).createSessionIntent(ie,xe??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:Te,paymentMethodId:null,intentKind:"payment"});if(Z.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let Ue=Z.clientSecret;if(typeof window<"u")try{localStorage.setItem(Sn,JSON.stringify({clientSecret:Ue,sessionId:ie,nonce:xe,accountPatch:K.accountPatch,paymentMethodId:ye.id,paymentMethodType:ye.type??e,gateway:"stripe"}))}catch{}let{error:Fe,paymentIntent:we}=await g.confirmPayment({clientSecret:Ue,confirmParams:{return_url:window.location.href,payment_method:ye.id},redirect:"if_required"});if(Fe){if(typeof window<"u")try{localStorage.removeItem(Sn)}catch{}let te=Fe.message??"Payment failed.";l?.(te),v?.(It("card",te,{code:Fe.code})),await bo({billingApiUrl:i,sessionId:ie,nonce:xe,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:Fe.code??"provider_declined"}});return}let V=we?.status;if(!mo(V)){if(typeof window<"u")try{localStorage.removeItem(Sn)}catch{}let te=V==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";l?.(te),v?.(It("card",te,{code:V??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(Sn)}catch{}let b=typeof we?.payment_method=="string"?we.payment_method:we?.payment_method?.id;u({id:b??ye.id,type:"card",threeDSecureActionResultTokenId:we?.id,gateway:"stripe",paymentMethodType:ye.type??e},{accountPatch:K.accountPatch,sessionId:ie,nonce:xe})}catch(de){l?.(de instanceof Error?de.message:"Payment failed. Please try again.")}finally{ce.current=!1,le(!1)}},[g,me,C,z,h,E,t,n,s,i,e,u,l,v]);return Le("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[d(Ks,{onReady:()=>oe("ready"),onLoadError:()=>{oe("load_error"),ia(At(T),"stripe","apm")},onChange:K=>{J(!!K.complete)},options:{layout:{type:"accordion",defaultCollapsed:!1,radios:"never"},defaultValues:{billingDetails:{name:a&&a.trim().length>=3?a.trim():"FloPay Customer",...s?{email:s}:{}}}}}),d("button",{type:"button","data-testid":`flopay-stripe-method-pay-${e}`,onClick:()=>{j()},disabled:!z||M||C||H!=="ready",style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:F,color:"white",border:"none",borderRadius:c,fontSize:"1rem",fontWeight:600,cursor:!z||M||C||H!=="ready"?"not-allowed":"pointer",opacity:!z||M||C||H!=="ready"?.5:1,transition:"opacity 120ms ease-out",...P??{}},children:M?"Processing\u2026":`Pay with ${hr(e)}`}),k&&d(ur,{margin:"0.75rem 0 0",children:k})]})}function Ii({sessionId:e,nonce:t,email:n,billingName:s,billingApiUrl:a,paymentElementMethods:i,stripeInstance:u,paymentElementBaseOptions:l,onTokenizedBody:v,onErrorChange:N,onButtonClick:h,onDecline:E,runBeforeButtonClick:C,onLoadStateChange:F,isProcessing:c=!1,submitButtonColor:P="#4A49FF",submitButtonBorderRadius:k=8,submitButtonStyle:T,buttonAppearance:g,themeId:me,onExpandApm:M,expandedApmMethod:le}){let[ce,z]=ve(null),[J,H]=ve(null),oe=Be(!1);ct(()=>{i.length>0&&u?F?.("ready"):u||F?.("loading")},[i.length,u,F]);let j=Ce(async Q=>{if(!u||oe.current||c)return;oe.current=!0,H(Q);let ye=C?await C("card"):{proceed:!0};if(!ye.proceed){oe.current=!1,H(null);return}h?.("card");let Te=ye.sessionId??e,Z=ye.nonce??t,Ue=ye.accountPatch?.email??n;try{if(N?.(null),!Te||!Ue)throw new Error("Missing sessionId or email for payment.");let Fe=await new Un(a).createSessionIntent(Te,Z??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:Q,paymentMethodId:null,intentKind:"payment"});if(Fe.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let we=Fe.clientSecret;if(typeof window<"u")try{localStorage.setItem(Sn,JSON.stringify({clientSecret:we,sessionId:Te,nonce:Z,accountPatch:ye.accountPatch,paymentMethodType:Q,gateway:"stripe"}))}catch{}let{error:V,paymentIntent:b}=await u.confirmPayment({clientSecret:we,confirmParams:{return_url:window.location.href,payment_method_data:{type:Q,billing_details:{name:s&&s.trim().length>=3?s.trim():"FloPay Customer",...Ue?{email:Ue}:{}}}},redirect:"if_required"});if(V){if(typeof window<"u")try{localStorage.removeItem(Sn)}catch{}let ze=V.message??"Payment failed.";N?.(ze),E?.(It("card",ze,{code:V.code})),await bo({billingApiUrl:a,sessionId:Te,nonce:Z,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:Q,providerDeclineReason:V.code??"provider_declined"}});return}let te=b?.status;if(!mo(te)){if(typeof window<"u")try{localStorage.removeItem(Sn)}catch{}let ze=te==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";N?.(ze),E?.(It("card",ze,{code:te??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(Sn)}catch{}let $e=typeof b?.payment_method=="string"?b.payment_method:b?.payment_method?.id;v({id:$e??b?.id,type:"card",threeDSecureActionResultTokenId:b?.id,gateway:"stripe",paymentMethodType:Q},{accountPatch:ye.accountPatch,sessionId:Te,nonce:Z})}catch(Fe){N?.(Fe instanceof Error?Fe.message:"Payment failed. Please try again.")}finally{oe.current=!1,H(null)}},[u,c,C,h,e,t,n,a,s,v,N,E]),[K,ie]=ve(null),xe=M?le??null:K,he=Ce(Q=>{oe.current||c||xe&&xe!==Q||(hi(Q)?M?M(Q):ie(Q):j(Q))},[xe,c,j,M]),de=lt(()=>K?{...l,paymentMethodTypes:[K]}:null,[K,l]);return d("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:i.map(Q=>{let ye=le===Q,Te=J===Q,Z=J!==null&&J!==Q||le!=null&&le!==Q;return Le(ol.Fragment,{children:[d(hl,{method:Q,themeId:me,submitting:Te,disabled:Z,highlighted:ye,hasNextStep:hi(Q),onClick:()=>he(Q),backgroundColor:g?.backgroundColor,borderColor:g?.borderColor,textColor:g?.textColor,borderRadius:g?.borderRadius,fontFamily:g?.fontFamily}),!M&&K===Q&&de&&u&&d(tr,{stripe:u,options:de,children:d(ra,{method:Q,sessionId:e,email:n,billingName:s,billingApiUrl:a,onTokenizedBody:v,onErrorChange:N,onDecline:E,onCancel:()=>ie(null),runBeforeButtonClick:C,onButtonClick:h,isProcessing:c,submitButtonColor:P,submitButtonBorderRadius:k,submitButtonStyle:T})},Q)]},Q)})})}function Pl({sessionId:e,nonce:t,billingApiUrl:n,email:s,userId:a,onComplete:i,onError:u,onDecline:l,onTokenizedBody:v,firstName:N,lastName:h,chv:E,className:C,isProcessing:F,error:c,onErrorChange:P,showPayPal:k=!0,showStripe:T=!0,enabledPaymentMethods:g,enabledPaymentMethodCountries:me,showApplePay:M=!0,showGooglePay:le=!0,layout:ce="default",theme:z,buttonsTheme:J,buttonsStyles:H,appearance:oe,cardButtonContent:j,cardBackButtonContent:K,cardTitleContent:ie,showSecurityFooter:xe,onButtonClick:he,onBeforeButtonClick:de,enableAVS:Q,cardFieldOrder:ye,cardPreFormSlot:Te,avsLayout:Z="row",country:Ue,zip:Fe,addressLine1:we,addressLine2:V,city:b,state:te,onCountryChange:$e,onZipChange:ze,avsCheck:ae,checkoutType:R,checkoutLayout:re,totalAmount:W=0,currency:ke="usd",initialCardOpen:dt=!1,directPaypal:Ge,isSubscription:pt=!1,session:_,dataAttachmentPending:Y=!1,debug:et=!1}){let qe=vn(),mt=Vo(),Ne=al(un),He=Y||Ne.claimPending===!0,Jt=co(),[Ye,Xt]=ve(!1),[S,fe]=ve(null),[We,Re]=ve(Ue??"US"),[vt,Ke]=ve(Fe??""),[je,tt]=ve(we??""),[Je,kn]=ve(V??""),[ot,jn]=ve(b??""),[Wt,mn]=ve(te??""),[Qt,or]=ve({}),Bt=Be(Fe??""),St=Be(Ue??"US"),Zt=Be(we??""),en=Be(V??""),Ft=Be(b??""),Dt=Be(te??""),Ct=Be({});ct(()=>{let o=(B,q,ne,$,be)=>{if(Ct.current[B])return;let _e=q?.trim();!_e||_e===ne.current||(ne.current=_e,$(_e),be?.(_e))};o("country",Ue,St,Re,$e),o("zip",Fe,Bt,Ke,ze),o("addressLine1",we,Zt,tt),o("addressLine2",V,en,kn),o("city",b,Ft,jn),o("state",te,Dt,mn)},[Ue,Fe,we,V,b,te,$e,ze]);let X=lt(()=>Gs(Q),[Q]),Kn=X!==null,A=lt(()=>Zo(_),[_]),at=!!_?.vault?.html,Lt=!!_?.gateways?.pcivault,Me=!!(_?.gateways?.stripe?.enabledPaymentMethods??g)?.includes("card"),it=at||Me||Lt,Ve=!!(T&&it&&qe&&e),[Rn,In]=ve(()=>ce!=="buttons"||dt?e??null:null),[Dn,Vn]=ve(0),En=ce!=="buttons"||dt||!!e&&Rn===e,nt=lt(()=>!qe||!Ve||!e||!En?null:qe.cardCapture({sessionId:e,captureMethod:_?.captureMethod}),[qe,Ve,e,En,_?.captureMethod]),zt=lt(()=>{let o=We,B=X?De(X.postal_code,o):!1;return fl(o,vt,B)},[X,We,vt]),{avsInvalid:sn,invalidAvsFields:gt}=lt(()=>{let o={line1:!1,city:!1,state:!1,zip:!1};if(!Ve||!X)return{avsInvalid:!1,invalidAvsFields:o};let B=We,q=(be,_e)=>De(be,B)&&!_e.trim(),ne={line1:q(X.address_line_1,je),city:q(X.city,ot),state:q(X.state,Wt),zip:zt.empty||zt.malformed};return{avsInvalid:ne.line1||ne.city||ne.state||ne.zip,invalidAvsFields:ne}},[Ve,X,We,je,ot,Wt,zt]),[xt,tn]=ve(!1),[ln,Yt]=ve(!1),[Ut,$t]=ve(()=>ea(_?.vault)),[Ie,qt]=ve(dt&&it?"card":"buttons"),[yt,yn]=ve(null),Hn=Ie==="expanding"||Ie==="card",jt=280,Kt=Be(null),Nt=Ce(o=>{Kt.current&&clearTimeout(Kt.current),Kt.current=setTimeout(()=>{Kt.current=null,o()},jt)},[jt]);ct(()=>()=>{Kt.current&&clearTimeout(Kt.current)},[]);let Ln=Ce(()=>{In(e??null),Vn(o=>o+1),qt("expanding"),Nt(()=>qt("card"))},[Nt,e]),zn=Ce(()=>{qt("collapsing"),Nt(()=>qt("buttons"))},[Nt]),nn=Ce(o=>{yn(o),qt("apm-expanding"),Nt(()=>qt("apm-form"))},[Nt]),Gt=Ce(()=>{qt("apm-collapsing"),Nt(()=>{qt("buttons"),yn(null)})},[Nt]);ct(()=>{ce==="buttons"&&dt&&it&&(In(e??null),qt("card"))},[ce,dt,it,e]);let[rn,Oe]=ve(null),w=Be(!1),D=Be(null),I=Be("idle"),[ge,Pe]=ve(null),m=Be(ge);ct(()=>{m.current=ge},[ge]);let r=n||Jt,y=c??S,x=lt(()=>sl(z),[z]),f=lt(()=>{let o=x?.buttonsLayout??Hs(J);return H?{...o,...H,cardButton:{...o.cardButton,...H.cardButton},cardFormContainer:{...o.cardFormContainer,...H.cardFormContainer},backButton:{...o.backButton,...H.backButton},backButtonIcon:{...o.backButtonIcon,...H.backButtonIcon},submitButton:{...o.submitButton,...H.submitButton},title:{...o.title,...H.title}}:o},[x,J,H]),O=oe??x?.appearance,Ae=lt(()=>Qa({appearance:O,buttonsStyles:f,layout:ce}),[O,f,ce]),Xe=Ne.inlineSessionPatchProcessing??!1,G=(F??Ye)||Xe,U=r.replace(/\/+$/,""),p=lt(()=>Yo({userId:a,email:s,firstName:N,lastName:h,country:Ue,zip:Fe},Qt),[a,s,N,h,Ue,Fe,Qt]),L=[p.firstName,p.lastName].filter(o=>!!o?.trim()).join(" "),ue=lt(()=>qe?qe.getRawProvider():null,[qe]),Se=lt(()=>mt?mt.getRawProvider():null,[mt]),Ee=W||100,fn=lt(()=>O?rl(O):null,[O]),Rr=fn?{appearance:fn}:null,_o=lt(()=>{let o=fn??{},B=o.rules??{};return{...o,rules:{...B,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...B[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...B[".AccordionItemContents"]??{}}}}},[fn]),Jr=lt(()=>{let o=li(W);return{...o,currency:ke.toLowerCase(),paymentMethodCreation:"manual",...o.mode==="payment"?{captureMethod:"manual"}:{},...Rr}},[W,ke,Rr]),wa=lt(()=>({mode:"payment",amount:Ee,currency:ke.toLowerCase(),captureMethod:"manual",setupFutureUsage:"off_session",...Rr}),[Ee,ke,Rr]),se=Ce(o=>{fe(o),P?.(o)},[P]);ct(()=>{!Ve||!nt||nt.setCardFieldOrder?.(ye??null,X==null)},[Ve,nt,ye,X]),ct(()=>{(Ie==="expanding"||Ie==="collapsing"||Ie==="apm-expanding"||Ie==="apm-collapsing")&&se(null)},[Ie,se]);let cn=Ce((o,B,q)=>{l?.(It(o,B,q))},[l]),ar=Ce((o,B,q)=>{let ne=q?.popupBlocked??On(B),$=ml(o,ne),be=Zn(q?.code)??Tn(B)??"external_payment_method_failed",_e=new Cn($,"api_error",{code:"external_payment_method_failed",param:o});Oe(null),ce==="buttons"&&(qt("buttons"),yn(null)),se($),u?.(_e),console.error("[FloPay] External payment method failed:",{method:o,code:be,popupBlocked:ne})},[ce,u,se]);ct(()=>{if(!Ve||!e){$t(null);return}let o=ea(_?.vault);if(o){$t(o);return}if(!En){$t(null);return}$t(null);let B=!0;return new Un(U).getVaultCapture(e,t).then(q=>{if(!B)return;let ne=ea(q);ne?$t(ne):se("Failed to load the secure card form.")}).catch(q=>{B&&se(q instanceof Error?q.message:"Failed to load the secure card form.")}),()=>{B=!1}},[Ve,En,Dn,e,_?.vault?.html,_?.vault?.messageToken,_?.vault?.expectedOrigin,U,t,se]);let gn=Be({onComplete:i,onError:u,updateError:se,emitDecline:cn,resolvedAccount:p,avsConfig:X,avsCheckProp:ae,sessionId:e,nonce:t,baseUrl:U,captureMethod:_?.captureMethod,paymentId:_?.paymentId,authorizationExpiresAt:_?.authorizationExpiresAt});gn.current={onComplete:i,onError:u,updateError:se,emitDecline:cn,resolvedAccount:p,avsConfig:X,avsCheckProp:ae,sessionId:e,nonce:t,baseUrl:U,captureMethod:_?.captureMethod,paymentId:_?.paymentId,authorizationExpiresAt:_?.authorizationExpiresAt};let xo=Be(!1),Qi=Ce(()=>{let{resolvedAccount:o,avsConfig:B,avsCheckProp:q}=gn.current,ne=St.current||o.country||"US",$=B?De(B.state,ne):!1,be=B?De(B.address_line_1,ne):!1,_e=B?De(B.postal_code,ne):!1,st=B?De(B.city,ne):!1,Pt=B?De(B.address_line_2,ne):!1,Qe=be&&!$&&_e?gi(ne,(Bt.current??"").trim()):null,wt=$?Dt.current:Qe;return{accountData:{userId:o.userId??"",email:o.email??"",firstName:o.firstName??"",lastName:o.lastName??"",..._e&&Bt.current?{zip:Bt.current}:{},...st&&Ft.current?{city:Ft.current}:{},...wt?{state:wt}:{},...be&&Zt.current?{addressLine1:Zt.current}:{},...Pt&&en.current?{addressLine2:en.current}:{},country:ne},...q!==void 0?{avsCheck:q}:{},...B?{avsConfig:{country:De(B.country,ne),postal_code:_e,address_line_1:be,address_line_2:Pt,city:st,state:$}}:{}}},[]),ka=Be(He);ka.current=He,ct(()=>{He||y!==vi||gn.current.updateError(null)},[He,y]),ct(()=>{!Ve||!nt||nt.setSubmitGate?.(sn||He)},[Ve,nt,sn,He]),ct(()=>{if(!Ve||!nt)return;xo.current=!1;let o=!1,B=nt.on("submitting",()=>{tn(!0),D.current&&clearTimeout(D.current),I.current="validation-window",D.current=setTimeout(()=>{D.current=null,I.current==="validation-window"&&(I.current="processing")},ll),Oe("processing");let{baseUrl:_e,sessionId:st,nonce:Pt,updateError:Qe,onError:wt}=gn.current;!st||!Pt||new Un(_e).patchAccountSnapshot(st,Pt,Qi(),{telemetryMode:"best_effort"}).catch(pe=>{if(!cl(pe))return;let Tt=pe instanceof Error?pe.message:"Please check your billing address and try again.";Qe(Tt),I.current="idle",Oe(null),wt?.(pe instanceof Cn?pe:new Cn(Tt,"api_error"))})}),q=nt.on("complete",async _e=>{if(mr(_e.sessionId??gn.current.sessionId),I.current="terminal",Oe("success"),await new Promise(Qe=>setTimeout(Qe,_n)),xo.current)return;xo.current=!0;let st=gn.current,Pt=Zo(st)||_e.outcome==="authorized";gn.current.onComplete?.(Pt?{status:"authorized",paymentIntentId:_e.intentId,paymentId:_e.paymentId??st.paymentId,sessionId:_e.sessionId??st.sessionId,authorizationExpiresAt:_e.authorizationExpiresAt??st.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",paymentIntentId:_e.intentId,checkoutMethod:"card"})}),ne=nt.on("decline",async _e=>{let{updateError:st,emitDecline:Pt}=gn.current,Qe=_e.message??"Your payment was declined. Please try another card or contact your bank.";I.current="terminal",st(Qe),Oe("error");let wt=_e.failureOutcome??Vs(_e.declineReason)??"authorization_declined";Pt("card",Qe,{code:wt,declineCode:wt}),await new Promise(pe=>setTimeout(pe,Pn)),!o&&(I.current="idle",Oe(null))}),$=nt.on("error",async _e=>{let{updateError:st,onError:Pt}=gn.current,Qe=_e.message??"There was a problem processing your payment. Please try again.";I.current="terminal",st(Qe),Oe("error"),Pt?.(new Cn(Qe,"api_error",{code:_e.failureOutcome??"capture_failed"})),await new Promise(wt=>setTimeout(wt,Pn)),!o&&(I.current="idle",Oe(null))}),be=nt.on("blocked",()=>{if(!ka.current){tn(!0);return}gn.current.updateError(vi)});return()=>{o=!0,D.current&&(clearTimeout(D.current),D.current=null),I.current="idle",B(),q(),ne(),$(),be()}},[Ve,nt]);let hn=!!Ge?.clientId,Ir=Array.isArray(g),Xr=Ir&&g.length>0,Zi=Ir&&g.includes("paypal"),{expressMethods:Qr,paymentElementMethods:Er}=lt(()=>nl(g,{excludePaypal:hn}),[g,hn]),Ra=hn||!!mt,es=lt(()=>Ra?Qr.filter(o=>o!=="paypal"):Qr,[Qr,Ra]),ts=lt(()=>{let o=[];return M&&o.push("apple_pay"),le&&o.push("google_pay"),o},[M,le]),Zr=Ir?es:ts,ns=T&&Zr.length>0,To=Kn?We:Ue,eo=lt(()=>{let o=To?.trim().toUpperCase();return o?me?Er.filter(B=>{let q=me[B];return!q||q.length===0||q.includes(o)}):Zs(Er,To):Er},[Er,To,me]),Mo=lt(()=>({mode:"payment",amount:Ee,currency:ke.toLowerCase(),paymentMethodCreation:"manual",appearance:_o}),[Ee,ke,_o]),[Ia,Ea]=ve("loading"),[_a,xa]=ve("loading"),[Ta,Ma]=ve("loading"),[rs,Ao]=ve(!1),[Aa,Bo]=ve("loading"),[to,os]=ve();ct(()=>{os(ci())},[]);let Ba=k&&(hn||(Ir?Zi:to===!1)),Fa=T&&ns,_r=!He&&Ba&&hn,Da=Aa==="retrying"||Aa==="exhausted",xr=!He&&Ba&&!!Se&&(!hn||Da),Tr=!He&&Fa&&!!ue,Mr=!He&&T&&Xr&&eo.length>0&&!!ue,as=_r&&!Da?rs:xr&&wi(Ia),is=Tr&&wi(_a),ss=Mr&&Ta!=="load_error",La=o=>o==="loading"||o==="ready",za=_r||xr&&La(Ia)||Tr&&La(_a)||Mr&&Ta!=="load_error",no=Be(!1);ct(()=>{if(!no.current){if(!T&&!k){no.current=!0;let o=new Cn("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");u?.(o),se(o.message)}else if(!T&&k&&!hn&&!Se){no.current=!0;let o=new Cn("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");u?.(o),se(o.message)}else if(to!==void 0&&!He&&!it&&!za){no.current=!0;let o=new Cn("FloPay: this checkout session has no vault card capability and no usable supported non-card payment methods. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});u?.(o),se(o.message)}}},[T,k,hn,Se,to,He,it,za,u,se]);let Na=Be(!1);ct(()=>{if(Na.current||!Xr)return;let o=[];M!==!0&&o.push("showApplePay"),le!==!0&&o.push("showGooglePay"),o.length!==0&&(Na.current=!0,console.warn(`[FloPay] ${o.join(" / ")} ${o.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.`))},[Xr,M,le]);let Oa=Ce((o,B)=>Ne.applyInlineSessionPatch?Ne.applyInlineSessionPatch(o).then(q=>({error:null,sessionId:q.sessionId||e,nonce:q.session?.clientSecret||t})).catch(q=>{let ne=Si(B,q);return se(ne.message),u?.(ne),{error:ne,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[Ne.applyInlineSessionPatch,t,u,e,se]),dn=Ce(async o=>{if(!de)return{proceed:!0};try{let B=await de({method:o,sessionId:e||void 0,createSession:Ne.inlineSessionDraft});if(B===!1)return{proceed:!1};if(B&&typeof B=="object"){B.account&&or(ne=>({...ne??{},...B.account}));let q=await Oa(B,o);return q.error?{proceed:!1,accountPatch:B.account}:{proceed:!0,accountPatch:B.account,sessionId:q.sessionId,nonce:q.nonce}}return{proceed:!0}}catch(B){let q=Si(o,B);return se(q.message),u?.(q),{proceed:!1}}},[Oa,Ne.inlineSessionDraft,de,u,e,se]),Ua=Ce(async(o,B)=>{if(w.current)return;w.current=!0,Xt(!0),Oe("processing"),se(null);let q=B?.sessionId??e,ne=B?.nonce??t,$=Yo(p,B?.accountPatch),be=B?.completionPaymentMethodId??Ur(o),_e=o.originalPaymentMethodId?{...o,originalPaymentMethodId:void 0}:o;try{let Pt=await new Un(U).processPayment($.userId??"",{sessionId:q,nonce:ne,tokenizedData:_e,accountData:{userId:$.userId??"",email:$.email??"",firstName:$.firstName??"",lastName:$.lastName??"",...X?(()=>{let pe=St.current,Tt=De(X.state,pe),Ht=De(X.address_line_1,pe),Jn=De(X.postal_code,pe),Xn=Ht&&!Tt&&Jn?gi(pe,(Bt.current??"").trim()):null,Mt=Tt?Dt.current:Xn;return{country:pe,...Jn&&Bt.current?{zip:Bt.current}:{},...De(X.city,pe)&&Ft.current?{city:Ft.current}:{},...Mt?{state:Mt}:{},...Ht&&Zt.current?{addressLine1:Zt.current}:{},...De(X.address_line_2,pe)&&en.current?{addressLine2:en.current}:{}}})():{}},chv:E,avsCheck:ae??!1,checkoutType:R,checkoutLayout:re,avsConfig:X?{country:De(X.country,St.current),postal_code:De(X.postal_code,St.current),address_line_1:De(X.address_line_1,St.current),address_line_2:De(X.address_line_2,St.current),city:De(X.city,St.current),state:De(X.state,St.current)}:void 0});if(Pt.ok){let pe=Pt.status===204?null:await Pt.json().catch(()=>null),Tt=Zo(_)||pe?.status==="authorized";mr(q),Oe("success"),Pe(null),await new Promise(Ht=>setTimeout(Ht,_n)),i?.(Tt?{status:"authorized",...typeof pe?.paymentId=="string"?{paymentId:pe.paymentId}:_?.paymentId?{paymentId:_.paymentId}:{},sessionId:typeof pe?.sessionId=="string"?pe.sessionId:q,...typeof pe?.authorizationExpiresAt=="string"?{authorizationExpiresAt:pe.authorizationExpiresAt}:_?.authorizationExpiresAt?{authorizationExpiresAt:_.authorizationExpiresAt}:{},paymentIntentId:o.threeDSecureActionResultTokenId,paymentMethodId:be,checkoutMethod:o.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:o.threeDSecureActionResultTokenId,paymentMethodId:be,checkoutMethod:o.isPaypal?"paypal":"card"});return}let Qe=await Pt.json().catch(()=>null);if(Qe?.type==="paypal_redirect_required"){let pe=Qe.threeDSecureToken,Tt=Qe.paymentMethodId||o.id||"";if(!qe||!pe){Oe("error"),se("PayPal authorization required but no token provided.");return}try{let Ht=mt?.getRawProvider();if(!Ht){se("PayPal is not available.");return}let Jn={return_url:window.location.href};Tt&&(Jn.payment_method=Tt);let{error:Xn}=await Ht.confirmPayment({clientSecret:pe,confirmParams:Jn,redirect:"if_required"});if(Xn){Oe("error");let Mt=Xn.message??"PayPal payment failed.";se(Mt),cn("paypal",Mt,{code:Xn.code})}}catch(Ht){Oe("error"),se(Ht instanceof Error?Ht.message:"PayPal authorization failed.")}return}if(Qe?.type==="paypal_direct_required"){let pe=Qe.orderId;if(!pe){Oe("error"),se("PayPal retry required but no order id provided.");return}let Tt=m.current?.attempts??0;if(Tt>=2){Oe("error"),se("PayPal payment could not be completed after multiple attempts."),cn("paypal","paypal_direct_required retry limit exceeded");return}Ao(!1),Bo("loading"),Pe({orderId:pe,attempts:Tt+1}),Oe(null);return}Oe("error");let wt=Qe?.message??"Payment failed. Please try again.";se(wt),cn(o.isPaypal?"paypal":"card",wt,{code:Qe?.code??Qe?.gatewayErrorCode,declineCode:Qe?.declineCode??Qe?.gatewayDeclineReason}),await new Promise(pe=>setTimeout(pe,Pn))}catch(st){Oe("error"),se(st instanceof Error?st.message:"An unexpected error occurred"),await new Promise(Pt=>setTimeout(Pt,Pn))}finally{Xt(!1),Oe(null),w.current=!1}},[U,e,t,p,L,E,qe,mt,_,i,u,se,cn]),on=Ce((o,B)=>{v?v(o):Ua(o,B)},[v,Ua]),$a=Be(!1);ct(()=>{if(typeof window>"u"||$a.current)return;let o=new URLSearchParams(window.location.search),B=o.get("payment_intent"),q=o.get("payment_intent_client_secret"),ne=o.get("redirect_status");if(!B||!q)return;let $=wt=>{let pe=localStorage.getItem(wt);if(!pe)return null;try{return JSON.parse(pe)}catch{return localStorage.removeItem(wt),null}},be=$(Sn)??$(bi),_e;if(be?.clientSecret){if(be.clientSecret!==q)return;_e={...be.accountPatch?{accountPatch:be.accountPatch}:{},...be.sessionId?{sessionId:be.sessionId}:{},...be.nonce?{nonce:be.nonce}:{}}}else if(be?.sessionId&&be.sessionId!==e)return;$a.current=!0,localStorage.removeItem(Sn),localStorage.removeItem(bi);let st=new URL(window.location.href);st.searchParams.delete("payment_intent"),st.searchParams.delete("payment_intent_client_secret"),st.searchParams.delete("redirect_status"),window.history.replaceState({},"",st.toString());let Pt=be?.paymentMethodType??be?.tokenType??"card",Qe="card";(async()=>{let wt=qe?.getRawProvider();if(!wt){let Mt="Payment is not available \u2014 please refresh and try again.";se(Mt),cn(Qe,Mt);return}if(ne==="failed"){let Mt="Payment was declined. Please try again.";se(Mt),cn(Qe,Mt);return}let{paymentIntent:pe,error:Tt}=await wt.retrievePaymentIntent(q);if(Tt){let Mt=Tt.message??"Failed to retrieve payment status.";se(Mt),cn(Qe,Mt,{code:Tt.code});return}let Ht=pe?.status,Jn=mo(Ht);if(!pe||!Jn){let Mt=Ht==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";se(Mt),cn(Qe,Mt,{code:Ht??"missing_payment_intent"});return}let Xn=typeof pe.payment_method=="string"?pe.payment_method:pe.payment_method?.id;on({id:Xn??be?.paymentMethodId??be?.tokenId??pe.id,type:"card",threeDSecureActionResultTokenId:pe.id,gateway:be?.gateway??"stripe",paymentMethodType:Pt},_e)})()},[e,on,qe,se,cn]);let Fo=Ce(o=>{o.preventDefault()},[]);if(!(qe!==null))return d("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let Ar=ce==="buttons",Vt=O?.variables,ls=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),Do=Vt?.colorBackground,cs=Do&&!ls.has(Do)?Do:void 0,Br=f.cardInputBorder??(Ar?"#e5e7eb":"#A4A4FF"),Lo=Vt?.colorDanger??"#dc2626",Wn=o=>xt&&o?Lo:Br,ro=(zt.malformed||zt.empty)&&(ln||xt),ds=ro?Lo:Wn(gt.zip),zo=f.cardFormContainer?.backgroundColor??cs??(Ar?"white":"#EDEDFF"),Fr=f.cardInputBackground??Vt?.colorBackground??"white",No=sr(K),qa=sr(ie),ir=f.nameInput,ja=f.cardInputFontSize??gl(ir?.fontSize)??Vt?.fontSizeBase??"16px",Ka=typeof ir?.fontFamily=="string"?ir.fontFamily:Vt?.fontFamily??"Poppins, sans-serif",Va=Xa(ir?.fontWeight)??400,us=f.cardInputColor??(typeof ir?.color=="string"?ir.color:void 0)??Vt?.colorText??"#262833",ps=f.cardInputPlaceholderColor??"#9ca3af",ht=Vt?.borderRadius??"8px",Yn=Vt?.borderRadius??f.cardButton?.borderRadius??ht,Gn=Vt?.colorPrimary??"#4A49FF",ms=Vt?.colorPrimaryHover??Lr(Gn,.12),Oo=Vt?.colorText??"#262833",Ha={fontSize:ja,fontFamily:Ka,fontWeight:Va,color:us,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},ys={"--flopay-input-placeholder-color":ps,"--flopay-input-font-size":ja,"--flopay-input-font-family":Ka,"--flopay-input-font-weight":String(Va)},Dr=f.cardFormContainer??{},Uo=Dr.padding??(Ar?"0":"1rem"),$o=Dr.borderRadius??ht,fs=nt&&Ut?d(qo,{capture:nt,html:Ut.html,messageToken:Ut.messageToken,expectedOrigin:Ut.expectedOrigin,theme:Ae,onReady:()=>{if(!X||typeof document>"u")return;let o=()=>{document.querySelector('[data-testid="flopay-avs-fields"]')?.querySelector("input:not([disabled]), select:not([disabled])")?.focus()};o();let B=0,q=window.setInterval(()=>{B+=1;let ne=document.activeElement;!!ne&&ne.tagName==="IFRAME"&&ne.id==="flopay_vault_form_iframe"?(o(),window.clearInterval(q)):B>=50&&window.clearInterval(q)},100)},onError:o=>se(o),onValidation:o=>{let B=I.current;(B==="idle"||B==="validation-window")&&(se(o),o&&I.current==="validation-window"&&(D.current&&(clearTimeout(D.current),D.current=null),I.current="idle",Oe(null)))}}):d("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"}),Wa=Le("div",{style:{backgroundColor:zo,borderRadius:$o,...Dr,padding:Uo,...ys,display:"flex",flexDirection:"column"},children:[d("style",{children:`
|
|
31
26
|
.flopay-shared-input::placeholder {
|
|
32
27
|
color: var(--flopay-input-placeholder-color);
|
|
33
28
|
opacity: 1;
|
|
@@ -35,13 +30,13 @@ ${Je.join(`
|
|
|
35
30
|
font-family: var(--flopay-input-font-family);
|
|
36
31
|
font-weight: var(--flopay-input-font-weight);
|
|
37
32
|
}
|
|
38
|
-
`}),
|
|
39
|
-
`)}):null,
|
|
40
|
-
`)}):null,si=Te==="apm-expanding"||Te==="apm-form"||Te==="apm-collapsing",mo=Te==="apm-expanding"?`flopay-card-enter ${Vt}ms cubic-bezier(0, 0, 0.2, 1) both`:Te==="apm-collapsing"?`flopay-card-exit ${Vt}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0,yo=gt?{...$o,paymentMethodTypes:[gt]}:null;if(Z==="buttons"){let s=Te==="buttons"||Te==="expanding"||Te==="apm-expanding",L=Te==="expanding"||Te==="card"||Te==="collapsing",H=N===void 0?{boxSizing:"border-box",height:Eo,padding:"0 1rem"}:{padding:"0.9rem 1rem"},se=Te==="expanding"||Te==="apm-expanding"?`flopay-buttons-exit ${Vt}ms cubic-bezier(0.4, 0, 0.2, 1) both`:Te==="collapsing"||Te==="apm-collapsing"?`flopay-buttons-enter ${Vt}ms cubic-bezier(0, 0, 0.2, 1) both`:void 0,V=Te==="expanding"?`flopay-card-enter ${Vt}ms cubic-bezier(0, 0, 0.2, 1) both`:Te==="collapsing"?`flopay-card-exit ${Vt}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0;return ze("form",{onSubmit:jo,className:v,style:{position:"relative"},children:[u(ua,{}),on&&u(cn,{status:on,errorMessage:y,authorized:D}),ze("div",{style:{display:"grid"},children:[ze("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!s&&!se?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!s&&!se?Sl:{},...se?{animation:se,pointerEvents:"none"}:{}},children:[ai("flopay-direct-paypal-gate-debug"),ii("flopay-stripe-gate-debug"),Br&&Je&&ze(vr,{children:[ve&&u("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."}),u(Ro,{sessionId:e,nonce:t,billingApiUrl:o,email:p.email,clientId:Je.clientId,environment:Je.environment,currency:_e.toUpperCase(),isSubscription:yt,onTokenizedBody:an,onComplete:i,onErrorChange:ye,onDecline:l,onTechnicalFailure:sr,onButtonClick:fe,runBeforeButtonClick:mn,isProcessing:Q,onLoadStateChange:qo,onInitializationStateChange:Vo,session:A??null,existingOrderId:ve?.orderId,debug:tt},ve?.orderId??"fresh")]}),Fr&&u(rr,{stripe:Ie,options:Fa,children:u(Fi,{sessionId:e,nonce:t,email:p.email,billingApiUrl:o,onTokenizedBody:an,onErrorChange:ye,isProcessing:Q,onButtonClick:fe,onDecline:l,onTechnicalFailure:sr,runBeforeButtonClick:mn,onLoadStateChange:Oa,placeholderBorderRadius:Jn})}),Dr?u(rr,{stripe:he,options:ro,children:u(Di,{sessionId:e,nonce:t,email:p.email,billingApiUrl:o,intentKind:J>0?"payment":"setup",expressMethods:io,onTokenizedBody:an,onErrorChange:ye,onButtonClick:fe,onDecline:l,onTechnicalFailure:sr,runBeforeButtonClick:mn,onLoadStateChange:Ua,placeholderBorderRadius:Jn})}):Ha?u("div",{style:{height:Eo,borderRadius:Jn,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,Lr&&u(Li,{sessionId:e,nonce:t,email:p.email,billingName:[p.firstName,p.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:o,paymentElementMethods:so,stripeInstance:he,paymentElementBaseOptions:$o,onTokenizedBody:an,onErrorChange:ye,onButtonClick:fe,onDecline:l,runBeforeButtonClick:mn,onLoadStateChange:qa,isProcessing:Q,submitButtonColor:Xn,submitButtonBorderRadius:bt,submitButtonStyle:P.submitButton,onExpandApm:rn,expandedApmMethod:gt,themeId:F,buttonAppearance:{backgroundColor:P.cardButton?.backgroundColor,borderColor:P.cardInputBorder,textColor:P.cardButton?.color,borderRadius:Jn}}),He&&u("button",{type:"button",onClick:async()=>{Q||!(await mn("card")).proceed||(fe?.("card"),On())},disabled:Q,style:{width:"100%",...H,...P.cardButton,...ha({themeBundle:B,resolvedPrimaryColor:Xn,resolvedBorderRadius:bt,submitButtonStyle:P.submitButton,explicitPrimaryColor:Ht?.colorPrimary}),fontSize:P.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:Q?"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:Q?.6:1},onMouseEnter:Se=>{!Q&&(B||Ht?.colorPrimary)&&(Se.currentTarget.style.backgroundColor=Rs)},onMouseLeave:Se=>{(B||Ht?.colorPrimary)&&(Se.currentTarget.style.backgroundColor=Xn)},onMouseDown:Se=>{Se.currentTarget.style.transform="scale(0.985)"},onMouseUp:Se=>{Se.currentTarget.style.transform="scale(1)"},children:u(dr,{content:N})}),y&&Te==="buttons"&&u(yr,{margin:"0.25rem 0",styleOverride:P.errorBanner,children:y})]}),He&&L&&u("div",{style:{gridArea:"1 / 1",...V?{animation:V}:{},...Te==="collapsing"?{pointerEvents:"none"}:{}},children:oi}),E&&si&>&&yo&&he&&u("div",{style:{gridArea:"1 / 1",...mo?{animation:mo}:{},...Te==="apm-collapsing"?{pointerEvents:"none"}:{}},children:ze("div",{style:{backgroundColor:Wo,borderRadius:Xo,...Ur,padding:Jo},children:[ze("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[ze("button",{type:"button","data-testid":"flopay-apm-back-button",onClick:Gt,style:{display:"inline-flex",alignItems:"center",gap:Yo?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:P.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...P.backButton},"aria-label":"Back to payment methods",children:[u("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...P.backButtonIcon},children:u("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:u("path",{d:"M15 18l-6-6 6-6"})})}),u(ur,{content:j})]}),u("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:P.titleFontSize??"1.05rem",color:Go,paddingRight:80,...P.title},children:`Pay with ${Cr(gt)}`})]}),u(rr,{stripe:he,options:yo,children:u(ma,{method:gt,sessionId:e,nonce:t,email:p.email,billingName:[p.firstName,p.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:o,onTokenizedBody:an,onErrorChange:ye,onDecline:l,onCancel:Gt,runBeforeButtonClick:mn,onButtonClick:fe,isProcessing:Q,submitButtonColor:Xn,submitButtonBorderRadius:bt,submitButtonStyle:P.submitButton,errorText:y})},gt)]})})]})]})}return si&>&&yo&&he&&E?ze("form",{onSubmit:jo,className:v,style:{position:"relative"},children:[u(ua,{}),on&&u(cn,{status:on,errorMessage:y,authorized:D}),u("div",{style:{...mo?{animation:mo}:{},...Te==="apm-collapsing"?{pointerEvents:"none"}:{}},children:ze("div",{style:{backgroundColor:Wo,borderRadius:Xo,...Ur,padding:Jo},children:[ze("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[ze("button",{type:"button","data-testid":"flopay-apm-back-button-default",onClick:Gt,style:{display:"inline-flex",alignItems:"center",gap:Yo?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:P.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...P.backButton},"aria-label":"Back to payment methods",children:[u("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...P.backButtonIcon},children:u("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:u("path",{d:"M15 18l-6-6 6-6"})})}),u(ur,{content:j})]}),u("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:P.titleFontSize??"1.05rem",color:Go,paddingRight:80,...P.title},children:`Pay with ${Cr(gt)}`})]}),u(rr,{stripe:he,options:yo,children:u(ma,{method:gt,sessionId:e,nonce:t,email:p.email,billingName:[p.firstName,p.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:o,onTokenizedBody:an,onErrorChange:ye,onDecline:l,onCancel:Gt,runBeforeButtonClick:mn,onButtonClick:fe,isProcessing:Q,submitButtonColor:Xn,submitButtonBorderRadius:bt,submitButtonStyle:P.submitButton,errorText:y})},gt)]})})]}):ze("form",{onSubmit:jo,className:v,style:{position:"relative"},children:[u(ua,{}),on&&u(cn,{status:on,errorMessage:y,authorized:D}),ze("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[ai("flopay-direct-paypal-gate-debug-default"),ii("flopay-stripe-gate-debug-default"),Br&&Je&&ze(vr,{children:[ve&&u("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."}),u(Ro,{sessionId:e,nonce:t,billingApiUrl:o,email:p.email,clientId:Je.clientId,environment:Je.environment,currency:_e.toUpperCase(),isSubscription:yt,onTokenizedBody:an,onComplete:i,onErrorChange:ye,onDecline:l,onTechnicalFailure:sr,onButtonClick:fe,runBeforeButtonClick:mn,isProcessing:Q,onLoadStateChange:qo,onInitializationStateChange:Vo,session:A??null,existingOrderId:ve?.orderId,debug:tt},ve?.orderId??"fresh")]}),Fr&&u(rr,{stripe:Ie,options:Fa,children:u(Fi,{sessionId:e,nonce:t,email:p.email,billingApiUrl:o,onTokenizedBody:an,onErrorChange:ye,isProcessing:Q,onButtonClick:fe,onDecline:l,onTechnicalFailure:sr,runBeforeButtonClick:mn,onLoadStateChange:Oa,placeholderBorderRadius:Jn})}),Dr&&u(rr,{stripe:he,options:ro,children:u(Di,{sessionId:e,nonce:t,email:p.email,billingApiUrl:o,intentKind:J>0?"payment":"setup",expressMethods:io,onTokenizedBody:an,onErrorChange:ye,onButtonClick:fe,onDecline:l,onTechnicalFailure:sr,runBeforeButtonClick:mn,onLoadStateChange:Ua,placeholderBorderRadius:Jn})}),Lr&&u(Li,{sessionId:e,nonce:t,email:p.email,billingName:[p.firstName,p.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:o,paymentElementMethods:so,stripeInstance:he,paymentElementBaseOptions:$o,onTokenizedBody:an,onErrorChange:ye,onButtonClick:fe,onDecline:l,runBeforeButtonClick:mn,onLoadStateChange:qa,isProcessing:Q,submitButtonColor:Xn,submitButtonBorderRadius:bt,submitButtonStyle:P.submitButton,themeId:F,onExpandApm:rn,expandedApmMethod:gt,buttonAppearance:{backgroundColor:P.cardButton?.backgroundColor,borderColor:P.cardInputBorder,textColor:P.cardButton?.color,borderRadius:Jn}})]}),He&&(Ps||hs||bs)&&ze("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem",margin:"0.5rem 0 0.75rem",color:"#999",fontSize:"0.85rem"},children:[u("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}}),u("span",{children:"or pay with card"}),u("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}})]}),He&&oi]})}import{loadFloPay as Vi,PaymentAPI as Hi}from"@flopay/js";import{classifyPaymentRejection as Tl,FloPayError as ot,isAuthorizationOnlySession as Ml,isSetupIntentClientSecret as Al,normalizeCheckoutFailureOutcome as ji}from"@flopay/shared";var Xr="card";async function Bl(e,t,n){if(n){if(typeof e.retrieveSetupIntent!="function")return null;let{setupIntent:i,error:c}=await e.retrieveSetupIntent(t);return{error:c,intent:i??null}}if(typeof e.retrievePaymentIntent!="function")return null;let{paymentIntent:a,error:r}=await e.retrievePaymentIntent(t);return{error:r,intent:a??null}}async function Fl(e,t,n,a){if(a){if(typeof e.confirmCardSetup!="function")return null;let{setupIntent:c,error:l}=await e.confirmCardSetup(t,n);return{error:l,intent:c??null}}if(typeof e.confirmCardPayment!="function")return null;let{paymentIntent:r,error:i}=await e.confirmCardPayment(t,n);return{error:i,intent:r??null}}function va(e,t){return Object.assign(e,{checkoutMethod:t})}function Bn(e,t){let n=e instanceof ot?e:new ot(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 Jr(e,t){try{return await e()}catch(n){throw Bn(n,t)}}function Ki(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 Dl(e){return e.status==="succeeded"||e.status==="declined"}async function Wi(e){if(typeof document>"u"||typeof window>"u")throw new ot("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});if(e.signal?.aborted)throw new ot("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"});let t=3e5,n=1e3,a=15e3,r=`${e.billingApiUrl.replace(/\/$/,"")}/v1/checkouts/sessions/${encodeURIComponent(e.sessionId)}/3ds/complete`,i=async()=>{let g=new AbortController,w=()=>g.abort();e.signal?.aborted?g.abort():e.signal?.addEventListener("abort",w);let v=window.setTimeout(()=>g.abort(),a);try{let R=await fetch(r,{method:"POST",headers:{"x-checkout-session-token":e.nonce,"content-type":"application/json"},body:"{}",signal:g.signal});if(!R.ok)return{status:"unknown"};let d=await R.json().catch(()=>null);return Ll(d)}catch{return{status:"unknown"}}finally{window.clearTimeout(v),e.signal?.removeEventListener("abort",w)}},c=document.activeElement instanceof HTMLElement?document.activeElement:null,l=document.createElement("div");l.setAttribute("data-flopay-auto-3ds-overlay","1"),l.setAttribute("role","dialog"),l.setAttribute("aria-modal","true"),l.setAttribute("aria-label","Card authentication"),l.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 b=document.createElement("iframe");b.setAttribute("title","Card authentication"),b.setAttribute("allow","payment"),b.tabIndex=0,b.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(";"),b.src=e.nextActionRedirectUrl,l.appendChild(b),document.body.appendChild(l),b.focus();let x=null;try{x=new URL(e.billingApiUrl,window.location.href).origin}catch{x=null}try{let g=await new Promise((w,v)=>{let R=!1,d=0,h=0,k=0,E=!1,f=()=>{window.clearTimeout(d),window.clearInterval(h),window.clearTimeout(k),window.removeEventListener("message",Z),b.removeEventListener("load",S),e.signal?.removeEventListener("abort",le)},de=async()=>{if(!(R||E)){E=!0;try{let F=await i();if(R||!Dl(F))return;R=!0,f(),w(F)}finally{E=!1}}},S=()=>{window.clearTimeout(k),k=window.setTimeout(()=>{de()},250)},le=()=>{R||(R=!0,f(),v(new ot("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"})))},Z=F=>{if(F.source!==b.contentWindow||x&&F.origin!==x)return;let G=F.data;!G||typeof G!="object"||G.source!=="flopay-vault-3ds-return"||R||(R=!0,f(),w(null))};d=window.setTimeout(()=>{R||(R=!0,f(),v(new ot("Card authentication timed out.","api_error",{code:"three_ds_timeout"})))},t),h=window.setInterval(()=>{de()},n),b.addEventListener("load",S),window.addEventListener("message",Z),e.signal?.addEventListener("abort",le),e.signal?.aborted&&le()});return g||await i()}finally{l.parentNode?.removeChild(l),c?.isConnected&&c.focus()}}function Ll(e){if(!e||typeof e!="object")return{status:"unknown"};let t=typeof e.status=="string"?e.status:"unknown",n=typeof e.providerIntentId=="string"?e.providerIntentId:null;switch(t){case"succeeded":return{status:"succeeded",providerIntentId:n};case"declined":return{status:"declined",providerIntentId:n,declineReason:typeof e.declineReason=="string"?e.declineReason:null,gatewayDeclineReason:typeof e.gatewayDeclineReason=="string"?e.gatewayDeclineReason:null};case"requires_action":return{status:"requires_action",providerIntentId:n,nextActionRedirectUrl:typeof e.nextActionRedirectUrl=="string"?e.nextActionRedirectUrl:null};case"pending":return{status:"pending",providerIntentId:n};case"timeout":return{status:"timeout",providerIntentId:n};case"no_attempt":return{status:"no_attempt"};default:return{status:"unknown"}}}function Vn(e,t="Payment failed. Please try again.",n){let a=n?.checkoutMethod??e?.checkoutMethod??(e?.type==="paypal_redirect_required"?"paypal":"card"),r=e?.message??t,i=Un(r)??r;return va(new ot(i,"api_error",{code:ji(e?.outcome)??ji(e?.type)??e?.gatewayErrorCode}),a)}function ba(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function _o(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}async function zl(e){try{return await e()}catch(t){let n=t instanceof Error?t.message:String(t);if(!/failed to fetch|fetch failed/i.test(n))throw t;return e()}}function Yi(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let r of n)if(typeof r=="string"&&r.length>0&&(!t?.requirePaymentIntentClientSecret||_o(r)))return r;let a=e?.data;if(a&&typeof a=="object"){let r=a,i=[r.threeDSecureToken,r.clientSecret,r.stripeClientSecret,r.id];for(let l of i)if(typeof l=="string"&&l.length>0&&(!t?.requirePaymentIntentClientSecret||_o(l)))return l;let c=r.gateways;if(c&&typeof c=="object"){let l=c.stripe;if(l&&typeof l=="object"){let b=l,x=[b.stripeClientSecret,b.clientSecret];for(let g of x)if(typeof g=="string"&&g.length>0&&(!t?.requirePaymentIntentClientSecret||_o(g)))return g}}}}async function Ol({billingApiUrl:e,sessionId:t,nonce:n,responseJson:a}){let r=Yi(a,{requirePaymentIntentClientSecret:!0});if(typeof r=="string"&&r.length>0)return{type:"3ds_required",threeDSecureToken:r};if(!t)return null;try{let l=(await new Hi(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(_o(l))return{type:"3ds_required",threeDSecureToken:l}}catch{}return null}async function Sr({billingApiUrl:e,sessionId:t,session:n,nonce:a,tokenizedData:r,returnUrl:i,telemetry:c}){let l=e.replace(/\/+$/,""),b=t??n.id,x=a??n.clientSecret,g=n.customer?.id??n.accountData?.userId??"",w=n.customer?.email??n.accountData?.email??"",v=n.customer?.firstName??n.accountData?.firstName??"",R=n.customer?.lastName??n.accountData?.lastName??"",d=n.customer?.country??n.accountData?.country??void 0,h=n.customer?.zip??n.accountData?.zip??void 0,k=new Hi(l,c===!1?{telemetry:!1}:void 0),E=await zl(()=>k.processPayment(g,{sessionId:b,nonce:x,tokenizedData:r,accountData:{userId:g,email:w,firstName:v,lastName:R,country:d,zip:h},returnUrl:i??ba(n)}));if(E.ok){let S=typeof E.json=="function"?await E.json().catch(()=>null):null;return Ml(n)||S?.status==="authorized"?{type:"success",result:{status:"authorized",paymentId:typeof S?.paymentId=="string"?S.paymentId:n.paymentId,sessionId:typeof S?.sessionId=="string"?S.sessionId:b,authorizationExpiresAt:typeof S?.authorizationExpiresAt=="string"?S.authorizationExpiresAt:n.authorizationExpiresAt,paymentMethodId:Kr(r),checkoutMethod:r?r.isPaypal?"paypal":"card":void 0}}:{type:"success",result:{status:"succeeded",paymentIntentId:r?.threeDSecureActionResultTokenId,paymentMethodId:Kr(r),checkoutMethod:r?r.isPaypal?"paypal":"card":void 0}}}let f;try{f=await E.json()}catch{throw new ot("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:E.status})}if(f?.type==="paypal_redirect_required"||f?.type==="3ds_required"){let S=Yi(f);if(!S)throw new ot("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:E.status});return{type:f.type,threeDSecureToken:S,paymentMethodId:f.paymentMethodId}}if(f?.gatewayErrorCode==="authentication_required"){let S=await Ol({billingApiUrl:l,sessionId:b,nonce:x,responseJson:f});if(S)return S;throw va(new ot("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}let de=new ot(f?.message??"Payment failed. Please try again.","api_error",{code:f?.code??f?.gatewayErrorCode,declineCode:f?.declineCode??f?.gatewayDeclineReason,statusCode:E.status});throw Object.assign(de,{telemetryOutcome:Tl(E.status,f)})}async function xo(e,{flopay:t,paypalFlopay:n,attempt3DS:a,billingApiUrl:r,sessionId:i,session:c,returnUrl:l,telemetry:b}){let x=t?.getRawProvider();if(!x)throw Bn(new ot("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!a||!e.threeDSecureToken)throw va(new ot("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let g=Al(e.threeDSecureToken),w=null,v=e.paymentMethodId,R=await Jr(()=>Bl(x,e.threeDSecureToken,g),"card");if(R){if(R.error)throw Bn(new ot(R.error.message??`Failed to retrieve 3DS ${g?"setup":"payment"} status.`,"api_error",{code:R.error.code}),"card");let h=R.intent;!v&&h?.payment_method&&(typeof h.payment_method=="string"?v=h.payment_method:"id"in h.payment_method&&(v=h.payment_method.id??void 0))}let d=v?await Jr(()=>Fl(x,e.threeDSecureToken,{payment_method:v,return_url:l??ba(c)??window.location.href},g),"card"):null;if(d){if(d.error)throw Bn(new ot(d.error.message??"3DS authentication failed.","api_error",{code:d.error.code}),"card");w=d.intent}else{let h=await Jr(()=>x.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(h.error)throw Bn(new ot(h.error.message??"3DS authentication failed.","api_error",{code:h.error.code}),"card");w=(g?h.setupIntent:h.paymentIntent)??null}if(w&&(w.status==="requires_capture"||w.status==="succeeded"||w.status==="processing")){let h=await Sr({billingApiUrl:r,sessionId:i,session:c,telemetry:b,tokenizedData:{id:w.id,type:"card",threeDSecureActionResultTokenId:w.id},returnUrl:l});return h.type==="success"?{...h.result,paymentIntentId:h.result.paymentIntentId??w.id,paymentMethodId:h.result.paymentMethodId??v}:xo(h,{flopay:t,paypalFlopay:n,attempt3DS:a,billingApiUrl:r,sessionId:i,session:c,returnUrl:l,telemetry:b})}throw Bn(new ot("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let g=(n??t)?.getRawProvider();if(!g)throw Bn(new ot("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:v}=await Jr(()=>g.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(v)throw Bn(new ot(v.message??"PayPal authorization failed.","api_error",{code:v.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:w}=await Jr(()=>g.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:l??ba(c)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(w)throw Bn(new ot(w.message??"PayPal authorization failed.","api_error",{code:w.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new ot("Unsupported payment redirect state.","api_error")}function or(e){if(e instanceof ot){let a=Un(e.message);return a&&a!==e.message?Object.assign(new ot(a,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=Un(t)??t;return new ot(n,"api_error")}function To(e){let t=e.data.stripe?.publishableKey,n=!!e.data.paypal?.publishableKey;if(!t&&!n)throw new ot("Session advertises no supported gateways (expected `gateways.stripe` and/or `gateways.paypal`).","validation_error");return t?{publishableKey:t,paypalPublishableKey:e.data.stripe?.paypalPublishableKey??t}:{}}async function Mo({publishableKey:e,paypalPublishableKey:t,billingApiUrl:n,locale:a,telemetry:r}){if(!e)return{flopay:null,paypalFlopay:null};let i=!!t&&t!==e,[c,l]=await Promise.all([Vi(e,{billingApiUrl:n,locale:a,telemetry:r}),i?Vi(t,{billingApiUrl:n,locale:a,telemetry:r}).catch(b=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",b),null)):Promise.resolve(null)]);return{flopay:c,paypalFlopay:t?i?l:c:null}}import{Fragment as En,jsx as re,jsxs as _t}from"react/jsx-runtime";var wr=44,_a="flopay_checkout_saved_payment_resume",Do=new Map,Bo=new Map;function Qi(e,t){t.settled&&t.consumers===0&&Do.get(e)===t&&Do.delete(e)}function jl(e,t,n){let a=Bo.get(e);if(a&&(!a.sdkGeneratedIdempotencyKey||!t||a.sdkGeneratedIdempotencyKey===t))return a.attempt;let r=n(),i={attempt:r,sdkGeneratedIdempotencyKey:t};Bo.set(e,i);let c=()=>{Bo.get(e)===i&&Bo.delete(e)};return r.then(c,c),r}function Qr(e){return new Promise(t=>setTimeout(t,e))}function Fo(e,t,n){let a=fo({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:ns,enabled:t!==!1});return a.beginCheckout(n),a}function Zr(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function Sa(e,t,n,a,r){let i=Fo(e,t,n);i.error({errorCode:a,stage:r,paymentMethodCategory:"unknown",...r==="session_read"?{requestCategory:"session_read"}:{}}),Zr(i)}function Hl(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 Ea(e){let t=e?.data.paypal?.publishableKey;if(t)return{clientId:t,environment:e?.data.paypal?.environment}}function wa(e){return!e||e.data.stripe?.publishableKey?!1:!!Ea(e)?.clientId}function Dn(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function Kl(){if(!Dn())return null;try{let e=window.sessionStorage.getItem(_a);return e?JSON.parse(e):null}catch{return null}}function Zi(e){if(Dn())try{window.sessionStorage.setItem(_a,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function ka(){if(Dn())try{window.sessionStorage.removeItem(_a)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}var xa=":idempotency-key";function Wl(e){if(!Dn())return null;let t=window.sessionStorage.getItem(e);if(!t)return null;try{let n=JSON.parse(t);return n&&typeof n.sid=="string"&&n.sid?{sid:n.sid,nonce:typeof n.nonce=="string"?n.nonce:void 0}:null}catch{return{sid:t}}}function es(e,t,n){if(Dn())try{window.sessionStorage.setItem(e,JSON.stringify(n?{sid:t,nonce:n}:{sid:t}))}catch(a){console.warn("[FloPayCheckout] Failed to persist checkout session cache.",a)}}function Ia(e){if(Dn())try{window.sessionStorage.removeItem(e)}catch(t){console.warn("[FloPayCheckout] Failed to clear checkout session cache.",t)}}function Yl(e){if(Dn())try{return window.sessionStorage.getItem(e+xa)??void 0}catch{return}}function Gl(e,t){if(Dn())try{window.sessionStorage.setItem(e+xa,t)}catch(n){console.warn("[FloPayCheckout] Failed to persist checkout idempotency key.",n)}}function Jl(e){if(Ia(e),!!Dn())try{window.sessionStorage.removeItem(e+xa)}catch(t){console.warn("[FloPayCheckout] Failed to clear checkout idempotency key.",t)}}function Xl(){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 a of t)e.searchParams.has(a)&&(e.searchParams.delete(a),n=!0);n&&window.history.replaceState(window.history.state,"",e.toString())}function ts(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 Ql(e){return e?!!(e.account&&Object.keys(e.account).length>0||e.couponCodes!==void 0||e.tagsData!==void 0||e.utmMetadata!==void 0):!1}function Ra(e,t){return`${e}:${t.totalAmount??""}:${t.overrideAmount??""}:${t.quantity??1}:${t.currency??""}`}function Ta({sessionId:e,nonce:t,createSession:n,billingApiUrl:a,telemetry:r,appearance:i,locale:c,loading:l,error:b,onComplete:x,onError:g,onDecline:w,onCountryChange:v,onZipChange:R,showPayPal:d=!0,showStripe:h=!0,enabledPaymentMethods:k,showApplePay:E=!0,showGooglePay:f=!0,debug:de=!1,layout:S,theme:le,buttonsTheme:Z,buttonsStyles:F,cardButtonContent:G,cardBackButtonContent:W,cardTitleContent:oe,showSecurityFooter:N,onButtonClick:j,onBeforeButtonClick:ce,enableAVS:Re,cardFieldOrder:fe,cardPreFormSlot:ae,avsLayout:ee,className:pe,initialErrorMessage:Y=null,children:K,checkoutMode:Ee,confirmLabel:ge,renderConfirmButton:te,onSessionCompleted:q}){let C=$l(a),ie=gn(()=>rs(le),[le]),$e=i??ie?.appearance,Oe=n?"embedded_checkout":"standard_checkout",me=K?"custom_layout":S==="buttons"?"buttons_layout":"default_layout",[T,ue]=Ct(null),[J,_e]=Ct(null),mt=Nt(null),[Je,yt]=Ct(null),A=Nt(null),[X,tt]=Ct(null),[qe,ft]=Ct(e??""),Ne=e??qe,We=n?"":Ne,[Xt,Ge]=Ct(!0),[Qt,I]=Ct(null),[be,Ye]=Ct("full"),[xe,St]=Ct(!1),[je,Ve]=Ct(Y),[nt,Xe]=Ct(null),[In,at]=Ct(null),[Hn,Wt]=Ct(!1),[Pn,Zt]=Ct(void 0),[ir,Bt]=Ct(""),[kt,en]=Ct(!1),[tn,Ft]=Ct(!1),Dt=Nt(0),[wt,ne]=Ct("loading"),[Kn,D]=Ct(0),it=Nt(!1),Lt=Nt(!1),Ln=Nt(!1),Be=Nt(null),st=gn(()=>({checkoutMode:Ee??be,layout:K?"unknown":S==="buttons"?"buttons":"embedded"}),[Ee,K,be,S]),He=Nt(x);He.current=x;let _n=Nt(g);_n.current=g;let xn=Nt(w);xn.current=w,Fn(()=>{At(J)?.setCheckoutContext(st),Je&&Je!==J&&At(Je)?.setCheckoutContext(st)},[J,Je,st]);let zn=Nt(q);zn.current=q;let Wn=ar(_=>{ne(_),!(_!=="exhausted"||Ln.current)&&(Ln.current=!0,_n.current?.(new It("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),Tn=ar(()=>{ne("retrying"),D(_=>_+1)},[]);Fn(()=>{ne("loading"),D(0),Ln.current=!1},[Ne]),Fn(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:ns,checkout_type:Oe,checkout_layout:me,billing_api_url:C})},[me,Oe,C]);let rt=gn(()=>n?Ut(n,!0):"",[n]),zt=gn(()=>ir===rt?Pn:void 0,[Pn,ir,rt]),dn=gn(()=>n?ra(n,zt):void 0,[n,zt]),Pt=Ee??dn?.checkoutMode??"full",xt=gn(()=>dn?{...dn,checkoutMode:Pt}:void 0,[dn,Pt]);Fn(()=>{Zt(void 0),Bt(rt)},[rt]),Fn(()=>{Ve(Y)},[Y]);let nn=ar((_,z,M)=>{Ke(()=>{xn.current?.(Et(_,z,M))})},[Ke]),un=ar(async(_,z)=>{Ve(null),at(null),Wt(!1),Xe("processing");let M=z?.sessionId??_.id,ve=mt.current??A.current,Ce=At(ve),m=ve?null:Fo(C,r,st),o={log:p=>{Ce?Ce.log(p):m?.log(p)},error:p=>{Ce?Ce.error(p):m?.error(p)},terminal:p=>{Ce?Ce.terminal(p):m?.terminal(p)},performance:p=>{Ce?Ce.performance(p):m?.performance(p)},now:()=>Ce?.now()??m?.now()??0,elapsed:p=>Ce?.elapsed(p)??Math.max(0,(m?.now()??p)-p)},y=o.now(),B=!!(z?.initialAutoProcessingError||z?.initialAutoProcessingPending),P=!1,U,Fe=()=>{P||(P=!0,B=!0,U=o.now(),o.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),o.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},Qe=!1,Q=()=>{Qe||(Qe=!0,o.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),o.performance({stage:"processing",durationMs:o.elapsed(y),durationMode:"machine",paymentMethodCategory:"saved"}),U!==void 0&&o.performance({stage:"recovery",durationMs:o.elapsed(U),durationMode:"machine",paymentMethodCategory:"saved"}))};o.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),o.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"}),B&&Fe();let $;try{let p=Ki(z?.initialAutoProcessingError),O;if(p)Fe(),p.type==="paypal_redirect_required"&&Be.current?.publishableKey&&Zi({sessionId:M,publishableKey:Be.current.publishableKey,paypalPublishableKey:Be.current.paypalPublishableKey}),O=await xo(p,{flopay:mt.current,paypalFlopay:A.current,attempt3DS:z?.attempt3DS,billingApiUrl:C,sessionId:M,session:_,telemetry:!1}),p.type==="paypal_redirect_required"&&ka();else if(z?.initialAutoProcessingPending){let Me=(await new Ao(C,{telemetry:!1}).waitForCheckoutSessionCompletion(z.initialAutoProcessingPending.sessionId,{initialDelayMs:z.initialAutoProcessingPending.retryAfterMs})).data.session;if(!gr(Me))throw vo(Me);O=er(Me,M)}else{if(z?.initialAutoProcessingError)throw Vn(z.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:z.initialAutoProcessingError.checkoutMethod});if(z?.fromCreateSession)return z?.fallbackToFull&&(Ye("full"),ts("full")),!1;{let he=await Sr({billingApiUrl:C,sessionId:M,session:_,telemetry:!1});he.type==="success"?O=he.result:(Fe(),he.type==="paypal_redirect_required"&&Be.current?.publishableKey&&Zi({sessionId:M,publishableKey:Be.current.publishableKey,paypalPublishableKey:Be.current.paypalPublishableKey}),O=await xo(he,{flopay:mt.current,paypalFlopay:A.current,attempt3DS:z?.attempt3DS,billingApiUrl:C,sessionId:M,session:_,telemetry:!1}),he.type==="paypal_redirect_required"&&ka())}}M&&hr(M),Q(),B&&(o.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),o.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),o.terminal({outcome:O.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),Wt(O.status==="authorized"),Xe("success"),await Qr(fn),$=()=>He.current?.(O)}catch(p){let O=or(p),he=O.checkoutMethod??Xr;Ve(O.message),at(O.message),Wt(!1),z?.fallbackToFull&&(o.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),Ye("full"),ts("full")),Q();let Ie=O.statusCode!==void 0?Vl(O.statusCode,"unknown"):void 0,Me=Ie==="4xx"?{requestCategory:"process_payment",statusClass:Ie}:{},vn=Ie===void 0||Ie==="4xx";if(vn&&(O.telemetryOutcome==="payment_declined"||!!(O.declineCode||O.code?.toLowerCase().includes("declin"))))o.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...Me});else if(vn&&(O.telemetryOutcome==="validation_rejected"||O.type==="validation_error"))o.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...Me});else{let ro=Gi(p,B?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown");o.error({...ro,...O.telemetryFailureCategory?{failureCategory:O.telemetryFailureCategory}:{},stage:B?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:O.telemetryRequestCategory??"process_payment"})}return Ke(()=>_n.current?.(O)),nn(he,O,{code:O.code,declineCode:O.declineCode}),Xe("error"),await Promise.allSettled([Qr(Jt),z?.ensureProvidersReady?z.ensureProvidersReady():Promise.resolve()]),B&&(o.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),o.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{Q(),m&&Zr(m),Xe(null),at(null)}return Ke($),!0},[nn,Ke,or,C,r,st]);Fn(()=>{if(typeof window>"u"||Lt.current)return;let _=new URLSearchParams(window.location.search),z=_.get("payment_intent_client_secret");if(!z)return;let M=Kl();M&&(Lt.current=!0,(async()=>{let ve,Ce=0;Ve(null),at(null),Xe("processing"),St(!0);try{if(_.get("redirect_status")==="failed")throw Object.assign(new It("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:m,paypalFlopay:o}=await Mo({publishableKey:M.publishableKey,paypalPublishableKey:M.paypalPublishableKey,billingApiUrl:C,locale:c,telemetry:r});ve=At(o??m),Ce=ve?.now()??0,ve?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),ve?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let y=(o??m)?.getRawProvider();if(!y)throw Object.assign(new It("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:B,error:P}=await y.retrievePaymentIntent(z);if(P)throw Object.assign(new It(P.message??"Failed to retrieve PayPal payment status.","api_error",{code:P.code}),{checkoutMethod:"paypal"});let U=hi(B?.status);if(!B||U==="failed")throw Object.assign(new It("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let Fe=typeof B.payment_method=="string"?B.payment_method:B.payment_method?.id,Qe=U;if(M.sessionId){let p=(await new Ao(C,{telemetry:!1}).getUnifiedCheckoutSession(M.sessionId)).data.session;if(p&&p.status!=="complete"){let O=await Sr({billingApiUrl:C,sessionId:M.sessionId,session:p,telemetry:!1,tokenizedData:{id:Fe??B.id,type:"card",threeDSecureActionResultTokenId:B.id,isPaypal:!0}});if(O.type!=="success")throw Object.assign(new It("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});Qe=O.result.status}}M.sessionId&&hr(M.sessionId),ve?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),ve?.performance({stage:"redirect_resume",durationMs:ve.elapsed(Ce),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),ve?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),Xe("success"),await Qr(fn),Ke(()=>He.current?.({status:Qe,paymentIntentId:B.id,paymentMethodId:Fe,checkoutMethod:"paypal"}))}catch(m){let o=or(m),y=o.checkoutMethod??"paypal",B=!!(o.declineCode||o.code?.toLowerCase().includes("declin"));if(ve)ve.performance({stage:"redirect_resume",durationMs:ve.elapsed(Ce),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),B?ve.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):ve.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(B){let P=Fo(C,r,st);P.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),Zr(P)}else Sa(C,r,st,"REDIRECT_RESUME_FAILED","redirect_resume");Ve(o.message),at(o.message),Ke(()=>_n.current?.(o)),nn(y,o,{code:o.code,declineCode:o.declineCode}),Xe("error"),await Qr(Jt)}finally{ka(),Xl(),Xe(null),at(null),St(!1)}})())},[nn,Ke,c,or,C,r]);let Yt=Nt(null);function Ut(_,z=!1){let M=_?.account?.email?.trim().toLowerCase()??"",ve={c:_?.clientId,cur:_?.currency??"",captureMethod:_?.captureMethod??"",a:{e:M,u:M?"":_?.account?.userId??"",country:_?.account?.country??""},successUrl:_?.successUrl,cancelUrl:_?.cancelUrl,p:_?.products?.map(o=>Ra(`${o.type??""}:${o.code??o.providerItemId??o.providerPlanId??""}`,o)).sort(),i:_?.items?.map(o=>Ra(o.code??o.providerItemId??"",o)).sort(),s:_?.subscriptions?.map(o=>Ra(o.code??o.providerPlanId??"",o)).sort(),couponCodes:_?.couponCodes?[..._.couponCodes].sort():void 0,...z?{tagsData:_?.tagsData,utmMetadata:_?.utmMetadata,tokenizedData:_?.tokenizedData,checkoutMode:_?.checkoutMode??"full"}:{}},Ce=JSON.stringify(ve),m=0;for(let o=0;o<Ce.length;o++)m=(m<<5)-m+Ce.charCodeAt(o)|0;return`flopay_session_${Math.abs(m).toString(36)}`}let $t=gn(()=>xt?Ut(xt):"",[xt]),Te=Nt(xt);Te.current=xt,Fn(()=>{ft(e??"")},[e]),Fn(()=>{it.current=!1,Ve(Y),at(null),Wt(!1),Xe(null)},[$t,Y,e]);async function qt(_,z){let M=Fo(C,r,st),ve=new Ao(C,{telemetry:!1}),Ce=!1;try{let m=_.idempotencyKey!==void 0?Xi(_.idempotencyKey):void 0,o=m??Yl(z),y,B=!1,P=Wl(z);M.log({name:P?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let U=P?.sid??null,Fe=null,Qe;if(U)try{if(Fe=await ve.getUnifiedCheckoutSession(U,P?.nonce),Fe.data.session?.status==="complete"){if(aa(U))return{sid:U,result:Fe};Jl(z),U=null,Fe=null,B=!0}}catch{M.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),Ia(z),U=null}if(!U){!m&&(B||!o)&&(o=Xi(),y=o),o&&Gl(z,o);let Q=M.now(),$=0;M.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let p={..._,idempotencyKey:o,avsCheck:!!Re,avsConfig:typeof Re=="object"?Re:void 0,checkoutType:"embedded_checkout",checkoutLayout:K?"custom_layout":S==="buttons"?"buttons_layout":"default_layout"};Object.defineProperty(p,Nl,{configurable:!1,enumerable:!1,value:{onAttempt:Ie=>{$=Math.max($,Ie)}}});let O=()=>{M.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:"2xx"}),M.performance({stage:"session_create",durationMs:M.now()-Q,durationMode:"machine",requestCategory:"session_create",attempt:$,statusClass:"2xx"})},he=Ie=>{let Me=Gi(Ie,"CHECKOUT_SESSION_CREATE_FAILED","unknown");M.performance({stage:"session_create",durationMs:M.now()-Q,durationMode:"machine",requestCategory:"session_create",attempt:$,statusClass:Me.statusClass}),Ie instanceof It&&Ie.type==="validation_error"?M.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown"}):Me.statusClass==="4xx"?M.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create",statusClass:"4xx"}):M.error({...Me,stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create"})};try{if(Ul(p)){let Ie=await ve.createDetachedSession(p);Ie.claimed.catch(()=>{}),Fe=Ie.shell,U=Ie.sessionId,Qe=Ie.claimed.then(Me=>{let vn=Me.data.session?.id??Ie.sessionId;return vn&&es(z,vn,Me.data.session?.clientSecret??Ie.nonce),O(),Me},Me=>{throw Ia(z),he(Me),Me}).finally(()=>Zr(M)),Qe.catch(()=>{}),Ce=!0,M.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),M.performance({stage:"session_shell",durationMs:M.now()-Q,durationMode:"machine",requestCategory:"session_create",attempt:$,statusClass:"2xx",paymentMethodCategory:"card"})}else Fe=await ve.createAndFetchSession(p),O()}catch(Ie){throw he(Ie),Ie}U=Fe.data.session?.id??U??"",U&&!Qe&&es(z,U,Fe.data.session?.clientSecret)}return{sid:U??"",result:Fe,sdkGeneratedIdempotencyKey:y,...Qe?{claimed:Qe}:{}}}finally{Ce||Zr(M)}}let gt=ar(async(_,z)=>{let M=Te.current;if(!M)throw new It("createSession is required to bootstrap checkout.","validation_error");let ve=ra(M,_),Ce=Ut(ve),m=Do.get(Ce);if(!m){let B={promise:qt(ve,Ce),consumers:0,settled:!1};m=B,Do.set(Ce,B);let P=()=>{B.settled=!0,Qi(Ce,B)};B.promise.then(P,P)}m.consumers+=1;let o=!1,y=()=>{o||(o=!0,m.consumers-=1,Qi(Ce,m))};z?.(y);try{let B=await m.promise;Yt.current=Ce,_&&(Bt(rt),Zt(O=>yi(O,_)));let{sid:P,result:U,claimed:Fe}=B;if(ue(U),U.data.session&&tt(U.data.session),P&&ft(P),Fe){let O=Dt.current+=1;Ft(!0),Fe.then(he=>{Dt.current===O&&(ue(he),he.data.session&&tt(he.data.session),Ft(!1))},he=>{Dt.current===O&&(Ft(!1),I(he instanceof It?he:new It(he instanceof Error?he.message:"Failed to create session","api_error")))})}else Dt.current+=1,Ft(!1);let{publishableKey:Qe,paypalPublishableKey:Q}=To(U),{flopay:$,paypalFlopay:p}=await Mo({publishableKey:Qe,paypalPublishableKey:Q,billingApiUrl:C,locale:c,telemetry:r});return mt.current=$,_e($),A.current=p,yt(p),Ge(!1),B}catch(B){throw Yt.current===Ce&&(Yt.current=null),B}finally{z||y()}},[c,C,r,st]),bn=Nt(un);bn.current=un;let Yn=Nt(gt);Yn.current=gt;let Vt=ar(async _=>{if(!Ql(_)||kt)return{sessionId:qe,session:X};en(!0);try{let z=await gt(_);return{sessionId:z.sid,session:z.result.data.session??null}}finally{en(!1)}},[gt,kt,qe,X]);Fn(()=>{let _=!1,z;if(I(null),$t){let Ce=Te.current;return Ye(Pt),Ge(!1),Yt.current===$t?()=>{_=!0}:(tt(fi(Ce,Ee)),(async()=>{let m=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),o=Pt==="auto"&&!it.current&&!m;o&&(Ve(null),at(null),Xe("processing"));try{let y=await Yn.current(void 0,Fe=>{z=Fe}),B=y.result.data.session??null;Be.current=To(y.result);let P=wa(y.result),U=aa(y.sid||B?.id);if(!_&&o&&B&&!P&&!U){it.current=!0,await jl($t,y.sdkGeneratedIdempotencyKey,()=>bn.current(B,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:y.result.autoProcessingError,initialAutoProcessingPending:y.result.autoProcessingPending,autoProcessingAttempted:y.result.autoProcessingAttempted,sessionId:y.sid||B.id}));return}!_&&o&&((P||U)&&(it.current=!0),Xe(null),at(null))}catch(y){if(_)return;let B=y instanceof It||typeof y=="object"&&y!==null&&"code"in y?y.code:void 0;if(o&&B==="session_auto_completed"){it.current=!0,Xe("success"),await Qr(fn),_||(Ke(()=>{He.current?.({status:"succeeded"})}),Xe(null),at(null));return}o&&(Xe(null),at(null));let P=y instanceof It?y:new It(y instanceof Error?y.message:"Failed to create session","api_error");I(P)}finally{z?.(),z=void 0}})(),()=>{_=!0,z?.()})}Ge(!0);async function M(){let Ce=!1;try{let o=await new Ao(C,{telemetry:!1}).getUnifiedCheckoutSession(Ne,t);if(_)return;ue(o);let y=o.data.session??null;if(tt(y),!y)throw new It("No session data returned","api_error");let B=y.checkoutMode;if(B==="setup")throw new It("This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.","validation_error",{code:"InvalidCardSetupSurface",param:"sessionId"});if(y.status==="authorized"){Ge(!1),Ke(()=>{He.current?.(er(y,Ne)),zn.current?.(y.successUrl??"")});return}if(y.status==="complete"){Ge(!1),Ke(()=>{zn.current?.(y.successUrl??"")});return}if(y.status==="expired")throw bo(y);Ce=!0;let P=Ee??B??"full";Ye(P);let U=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),Fe=wa(o);if(P==="auto"&&!it.current&&!U&&!Fe){it.current=!0;let Qe=ve(o);try{if(await bn.current(y,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>Qe,sessionId:Ne||y.id}),_)return;await Qe,_||Ge(!1);return}catch{if(_)return;await Qe,_||Ge(!1);return}}await ve(o),_||Ge(!1)}catch(m){if(_)return;m instanceof It?!Ce&&!Hl(m)&&Sa(C,r,st,"NETWORK_REQUEST_FAILED","session_read"):Sa(C,r,st,"INTERNAL_SDK_ERROR","checkout_mount");let o=m instanceof It?m:new It(m instanceof Error?m.message:"Failed to initialize checkout","api_error");I(o),Ge(!1)}}async function ve(Ce){let{publishableKey:m,paypalPublishableKey:o}=To(Ce);Be.current={publishableKey:m,paypalPublishableKey:o};let{flopay:y,paypalFlopay:B}=await Mo({publishableKey:m,paypalPublishableKey:o,billingApiUrl:C,locale:c,telemetry:r});mt.current=y,_e(y),A.current=B,yt(B)}return M(),()=>{_=!0}},[Ee,$t,Pt,We,Ke,t]);let jt=ar(async()=>{if(!(xe||!X)){St(!0),Ve(null);try{await un(X,{attempt3DS:!0,fallbackToFull:!0,sessionId:Ne||X.id})}finally{St(!1)}}},[Ne,xe,un,X]),Ot=Ea(T),On=wa(T),Nn=gn(()=>{if(!T||!X||!T.data.stripe?.publishableKey)return;let _={appearance:$e,paymentMethodCreation:"manual",billingApiUrl:C};if(T.data.stripe?.clientSecret)_.clientSecret=T.data.stripe.clientSecret;else{let z=Ji(X).total;_.amount=Math.round(z*100)||X.amount,_.currency=X.currency?.toLowerCase()}return _},[T,X,$e,C]),rn=!!(n&&!K&&S==="buttons"&&ce&&Pt==="full"),Gt=gn(()=>({session:X,loading:Xt,error:Qt,checkoutMode:be,inlineSessionDraft:xt,applyInlineSessionPatch:rn?Vt:void 0,inlineSessionPatchProcessing:kt,claimPending:tn}),[X,Xt,Qt,be,xt,rn,Vt,kt,tn]),on=!!n&&S==="buttons"&&!On&&(!J||!Nn),Ue=nt?re(cn,{status:nt,errorMessage:In,authorized:Hn}):null;if(Xt){if(l)return _t(En,{children:[l,Ue]});if(S==="buttons"){let _=ie?.buttonsLayout?.cardButton?.borderRadius??ie?.appearance.variables?.borderRadius??8,z=M=>re("div",{style:{height:M,borderRadius:_,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return _t(En,{children:[_t("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[d&&z(wr),h&&(E||f)&&z(wr),h&&z(wr),re("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),Ue]})}return _t(En,{children:[_t("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[re("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),re("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),Ue]})}return Qt?b?re(yn.Provider,{value:Gt,children:b(Qt)}):re(yn.Provider,{value:Gt,children:re("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:Qt.message})}):on?_t(En,{children:[re(yn.Provider,{value:Gt,children:re(ec,{onButtonClick:j,showPayPal:d,showStripe:h,showApplePay:E,showGooglePay:f,theme:le,buttonsTheme:Z,buttonsStyles:F,cardButtonContent:G,cardBackButtonContent:W,cardTitleContent:oe})}),Ue]}):On&&X&&Ot?_t(En,{children:[re(yn.Provider,{value:Gt,children:_t("div",{className:pe,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[je&&re(yr,{icon:!1,children:je}),wt==="retrying"&&re("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),wt==="exhausted"&&_t("div",{role:"alert",children:[re("div",{children:"PayPal is temporarily unavailable. Please try again."}),re("button",{type:"button",onClick:Tn,children:"Retry PayPal"})]}),wt!=="exhausted"&&re("div",{"aria-hidden":wt==="retrying"?!0:void 0,style:wt==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:re(ki,{sessionId:Ne,nonce:X.clientSecret||void 0,billingApiUrl:C,email:X.customer?.email,clientId:Ot.clientId,environment:Ot.environment,currency:(X.currency??"usd").toUpperCase(),isSubscription:X.mode==="subscription",onComplete:x,onErrorChange:Ve,onDecline:w,onButtonClick:j,onInitializationStateChange:Wn,allowAutomaticRetry:Kn===0,session:X,telemetry:r,telemetryContext:st,debug:de},`paypal-init-${Kn}`)})]})}),Ue]}):!J||!Nn?re(En,{children:Ue}):be==="confirm"?_t(En,{children:[re(yn.Provider,{value:Gt,children:re(go,{flopay:J,paypalFlopay:Je,options:Nn,children:_t("div",{className:pe,children:[je&&re("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:je}),te?te({onConfirm:jt,isProcessing:xe}):re("button",{type:"button",onClick:jt,disabled:xe,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:xe?"not-allowed":"pointer",opacity:xe?.6:1},children:xe?"Processing...":ge??"Confirm Purchase"})]})})}),Ue]}):_t(En,{children:[re(yn.Provider,{value:Gt,children:re(go,{flopay:J,paypalFlopay:Je,options:Nn,children:K?_t(En,{children:[je&&re("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:je}),re(Zl,{sessionId:Ne,nonce:X?.clientSecret||void 0,billingApiUrl:C,session:X,children:K})]}):re(Pa,{sessionId:Ne,nonce:X?.clientSecret||void 0,email:X?.customer?.email,userId:X?.customer?.id,firstName:X?.customer?.firstName,lastName:X?.customer?.lastName,totalAmount:X?Math.round(Ji(X).total*100):0,currency:X?.currency?.toLowerCase()??"usd",onComplete:x,onError:g,onDecline:w,error:je,onErrorChange:Ve,showPayPal:d,showStripe:h,enabledPaymentMethods:k??T?.data.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:T?.data.stripe?.enabledPaymentMethodCountries,showApplePay:E,showGooglePay:f,layout:S,theme:le,buttonsTheme:Z,buttonsStyles:F,appearance:$e,cardButtonContent:G,cardBackButtonContent:W,cardTitleContent:oe,onButtonClick:j,onBeforeButtonClick:ce,enableAVS:Re,...fe?{cardFieldOrder:fe}:{},...ae?{cardPreFormSlot:ae}:{},avsLayout:ee,country:X?.customer?.country,city:X?.customer?.city,state:X?.customer?.state,onCountryChange:v,onZipChange:R,avsCheck:!!Re,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:K?"custom_layout":S==="buttons"?"buttons_layout":"default_layout",className:pe,directPaypal:Ea(T),isSubscription:X?.mode==="subscription",session:X,dataAttachmentPending:tn,debug:de})})}),Ue]})}function Zl({sessionId:e,nonce:t,billingApiUrl:n,session:a,children:r}){return re(En,{children:Ca.Children.map(r,i=>{if(!Ca.isValidElement(i))return i;let c=i.props,l={};return c.sessionId||(l.sessionId=e),!c.nonce&&t&&(l.nonce=t),c.billingApiUrl||(l.billingApiUrl=n),a?.customer&&(c.email||(l.email=a.customer.email),c.userId||(l.userId=a.customer.id),c.firstName||(l.firstName=a.customer.firstName),c.lastName||(l.lastName=a.customer.lastName)),Object.keys(l).length===0?i:Ca.cloneElement(i,l)})})}function ec({onButtonClick:e,showPayPal:t,showStripe:n=!0,showApplePay:a,showGooglePay:r,theme:i,buttonsTheme:c,buttonsStyles:l,cardButtonContent:b,cardBackButtonContent:x,cardTitleContent:g}){let[w,v]=Ct(!1),R=gn(()=>rs(i),[i]),d=gn(()=>{let f=R?.buttonsLayout??ql(c);return l?{...f,...l,cardButton:{...f.cardButton,...l.cardButton},cardFormContainer:{...f.cardFormContainer,...l.cardFormContainer},backButton:{...f.backButton,...l.backButton},backButtonIcon:{...f.backButtonIcon,...l.backButtonIcon},submitButton:{...f.submitButton,...l.submitButton},title:{...f.title,...l.title}}:f},[R,c,l]),h=R?.buttonsLayout?.cardButton?.borderRadius??R?.appearance.variables?.borderRadius??8,k=f=>re("div",{style:{height:f,borderRadius:h,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),E=b===void 0?{boxSizing:"border-box",height:wr,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(w){let f=d.cardInputBorder??"#e5e7eb",de=d.cardInputBackground??"white",S=cr(x),le=cr(g);return _t("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:[_t("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[_t("button",{type:"button",onClick:()=>v(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:S?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:[re("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...d.backButtonIcon},children:re("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:re("path",{d:"M15 18l-6-6 6-6"})})}),re(ur,{content:x})]}),le?re("div",{style:{flex:1}}):re("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...d.title},children:re(qr,{content:g})})]}),re("div",{style:{backgroundColor:de,border:`1px solid ${f}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:re("div",{style:{width:"60%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),_t("div",{style:{display:"flex"},children:[re("div",{style:{flex:1,backgroundColor:de,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${f}`,borderLeft:`1px solid ${f}`,borderBottomLeftRadius:8,padding:12,height:45},children:re("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),re("div",{style:{flex:1,backgroundColor:de,borderTop:"none",borderRight:`1px solid ${f}`,borderBottom:`1px solid ${f}`,borderLeft:`1px solid ${f}`,borderBottomRightRadius:8,padding:12,height:45},children:re("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),re("div",{style:{backgroundColor:de,border:`1px solid ${f}`,borderRadius:8,marginTop:8,padding:12,height:45},children:re("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),re("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",...d.submitButton,opacity:.5}}),re("style",{children:`
|
|
33
|
+
`}),Ar&&Hn&&Le("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:Ve?-2:0},children:[Le("button",{type:"button",onClick:zn,style:{display:"inline-flex",alignItems:"center",gap:No?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:[d("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:d("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:d("path",{d:"M15 18l-6-6 6-6"})})}),d(cr,{content:K})]}),qa?d("div",{style:{flex:1}}):d("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:f.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...f.title},children:d(Nr,{content:ie})})]}),!Ar&&!qa&&d("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:Oo,order:Ve?-3:0,...f.title},children:d(Nr,{content:ie})}),X&&d("div",{style:{order:Ve?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let o=We,B=($=!1)=>({backgroundColor:Fr,border:`1px solid ${Wn($)}`,borderRadius:ht,marginTop:"0.5rem",padding:"10px"}),q=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...Ha}),ne=Ws(o);return Le(gr,{children:[De(X.address_line_1,o)&&d("div",{style:B(gt.line1),children:d("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:je,onChange:$=>{Ct.current.addressLine1=!0,Zt.current=$.target.value,tt($.target.value)},disabled:G,required:!0,"data-testid":"flopay-address-line1",style:q()})}),De(X.address_line_2,o)&&d("div",{style:B(),children:d("input",{className:"flopay-shared-input",id:"flopay-billing-address-line2",name:"billing-address-line2",placeholder:"Apt, Suite, Unit (optional)",autoComplete:"billing address-line2",value:Je,onChange:$=>{Ct.current.addressLine2=!0,en.current=$.target.value,kn($.target.value)},disabled:G,"data-testid":"flopay-address-line2",style:q()})}),(De(X.city,o)||De(X.state,o))&&Le("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[De(X.city,o)&&d("div",{style:{flex:1,backgroundColor:Fr,borderTop:`1px solid ${Wn(gt.city)}`,borderRight:`1px solid ${Wn(gt.city)}`,borderBottom:`1px solid ${Wn(gt.city)}`,borderLeft:`1px solid ${Wn(gt.city)}`,padding:"10px",borderTopLeftRadius:ht,borderBottomLeftRadius:ht,...De(X.state,o)?{borderRight:"none",borderTopRightRadius:0,borderBottomRightRadius:0}:{borderRadius:ht}},children:d("input",{className:"flopay-shared-input",id:"flopay-billing-city",name:"billing-city",placeholder:"City",autoComplete:"billing address-level2",value:ot,onChange:$=>{Ct.current.city=!0,Ft.current=$.target.value,jn($.target.value)},disabled:G,required:!0,"data-testid":"flopay-city",style:q()})}),De(X.state,o)&&d("div",{style:{flex:1,backgroundColor:Fr,border:`1px solid ${Wn(gt.state)}`,padding:"10px",borderTopRightRadius:ht,borderBottomRightRadius:ht,...De(X.city,o)?{borderTopLeftRadius:0,borderBottomLeftRadius:0}:{borderRadius:ht}},children:ne?Le("select",{id:"flopay-billing-state",name:"billing-state",value:Wt,onChange:$=>{Ct.current.state=!0,Dt.current=$.target.value,mn($.target.value)},disabled:G,autoComplete:"billing address-level1",required:!0,"data-testid":"flopay-state",style:{...q(),cursor:"pointer"},children:[d("option",{value:"",children:fi(o)}),ne.map($=>d("option",{value:$.code,children:$.name},$.code))]}):d("input",{className:"flopay-shared-input",id:"flopay-billing-state",name:"billing-state",placeholder:fi(o),autoComplete:"billing address-level1",value:Wt,onChange:$=>{Ct.current.state=!0,Dt.current=$.target.value,mn($.target.value)},disabled:G,required:!0,"data-testid":"flopay-state",style:q()})})]}),(De(X.country,o)||De(X.postal_code,o))&&Le("div",{style:{display:"flex",flexDirection:Z==="column"?"column":"row",gap:Z==="column"?"0.5rem":"0",marginTop:"0.5rem"},children:[De(X.country,o)&&d("div",{style:{flex:Z==="row"?1:void 0,backgroundColor:Fr,borderTop:`1px solid ${Br}`,borderRight:`1px solid ${Br}`,borderBottom:`1px solid ${Br}`,borderLeft:`1px solid ${Br}`,padding:"10px",...Z==="row"&&De(X.postal_code,o)?{borderRadius:"0",borderTopLeftRadius:ht,borderBottomLeftRadius:ht,borderRight:"none"}:{borderRadius:ht}},children:d("select",{id:"flopay-billing-country",name:"billing-country",value:We,onChange:$=>{Ct.current.country=!0,St.current=$.target.value,Re($.target.value),$e?.($.target.value),Dt.current="",mn("")},disabled:G,autoComplete:"billing country","data-testid":"flopay-country",style:{...q(),cursor:"pointer"},children:Ys.map($=>Le("option",{value:$.code,children:[$.flag," ",$.name]},$.code))})}),De(X.postal_code,o)&&d("div",{style:{flex:Z==="row"?1:void 0,backgroundColor:Fr,border:`1px solid ${ds}`,padding:"10px",...Z==="row"&&De(X.country,o)?{borderRadius:"0",borderTopRightRadius:ht,borderBottomRightRadius:ht}:{borderRadius:ht}},children:d("input",{className:"flopay-shared-input",id:"flopay-billing-postal-code",name:"billing-postal-code",placeholder:na(We),autoComplete:"billing postal-code",value:vt,onChange:$=>{Ct.current.zip=!0,Bt.current=$.target.value,Ke($.target.value),ze?.($.target.value)},onBlur:()=>Yt(!0),disabled:G,required:zt.required,"aria-invalid":ro||void 0,"aria-describedby":ro?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:q()})})]}),ro&&d("div",{id:"flopay-billing-postal-code-error",role:"alert","data-testid":"flopay-zip-error",style:{marginTop:"0.375rem",color:Lo,...Ha,fontSize:"0.75rem"},children:zt.empty?`${na(o)} is required`:yl(o)})]})})()}),Ve&&Te&&d("div",{style:{order:-2,width:"100%"},children:Te}),Ve&&fs,y&&d(ur,{margin:"0.75rem 0",styleOverride:f.errorBanner,children:y})]}),oo={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"},Ya=o=>et?!k||!hn?d("pre",{"data-testid":o,style:oo,children:"FloPay/DirectPayPal-debug - not enabled"}):d("pre",{"data-testid":o,style:oo,children:["FloPay/DirectPayPal-debug (parent gate)",` showPayPal=${k}`,` directPaypalConfigured=${hn}`,` inAppBrowserDetected=${String(to)}`,` shouldRenderDirectPayPal=${_r}`,` shouldRenderStripePayPal=${xr}`,` hasPaypalStripeInstance=${!!Se}`].join(`
|
|
34
|
+
`)}):null,Ga=o=>et?!T||!ue?d("pre",{"data-testid":o,style:oo,children:"FloPay/Stripe-debug - not enabled"}):d("pre",{"data-testid":o,style:oo,children:["FloPay/Stripe-debug (parent gate)",` showStripe=${T}`,` currency=${ke}`,` amountInCents=${Ee}`,` enabledPaymentMethods: ${JSON.stringify(g??[])}`,` enabledPaymentMethodsProvided=${Ir}`,` hasEnabledMethods=${Xr}`,` expressMethods: ${JSON.stringify(Qr)}`,` walletExpressMethods: ${JSON.stringify(Zr)}`,` paymentElementMethods: ${JSON.stringify(Er)}`,` paymentElementMethodsForCurrency: ${JSON.stringify(eo)}`,` hasStripeInstance=${!!ue}`,` shouldRenderWallets=${Tr}`,` shouldRenderPaymentElement=${Mr}`].join(`
|
|
35
|
+
`)}):null,Ja=Ie==="apm-expanding"||Ie==="apm-form"||Ie==="apm-collapsing",ao=Ie==="apm-expanding"?`flopay-card-enter ${jt}ms cubic-bezier(0, 0, 0.2, 1) both`:Ie==="apm-collapsing"?`flopay-card-exit ${jt}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0,io=yt?{...Mo,paymentMethodTypes:[yt]}:null;if(ce==="buttons"){let o=Ie==="buttons"||Ie==="expanding"||Ie==="apm-expanding",B=Ie==="expanding"||Ie==="card"||Ie==="collapsing",q=j===void 0?{boxSizing:"border-box",height:Po,padding:"0 1rem"}:{padding:"0.9rem 1rem"},ne=Ie==="expanding"||Ie==="apm-expanding"?`flopay-buttons-exit ${jt}ms cubic-bezier(0.4, 0, 0.2, 1) both`:Ie==="collapsing"||Ie==="apm-collapsing"?`flopay-buttons-enter ${jt}ms cubic-bezier(0, 0, 0.2, 1) both`:void 0,$=Ie==="expanding"?`flopay-card-enter ${jt}ms cubic-bezier(0, 0, 0.2, 1) both`:Ie==="collapsing"?`flopay-card-exit ${jt}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0;return Le("form",{onSubmit:Fo,className:C,style:{position:"relative"},children:[d(ta,{}),rn&&d(bn,{status:rn,errorMessage:y,authorized:A}),Le("div",{style:{display:"grid"},children:[Le("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!o&&!ne?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!o&&!ne?ul:{},...ne?{animation:ne,pointerEvents:"none"}:{}},children:[Ya("flopay-direct-paypal-gate-debug"),Ga("flopay-stripe-gate-debug"),_r&&Ge&&Le(gr,{children:[ge&&d("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."}),d(ho,{sessionId:e,nonce:t,billingApiUrl:r,email:p.email,clientId:Ge.clientId,environment:Ge.environment,currency:ke.toUpperCase(),isSubscription:pt,onTokenizedBody:on,onComplete:i,onErrorChange:se,onDecline:l,onTechnicalFailure:ar,onButtonClick:he,runBeforeButtonClick:dn,isProcessing:G,onLoadStateChange:Ao,onInitializationStateChange:Bo,session:_??null,existingOrderId:ge?.orderId,debug:et},ge?.orderId??"fresh")]}),xr&&d(tr,{stripe:Se,options:wa,children:d(ki,{sessionId:e,nonce:t,email:p.email,billingApiUrl:r,onTokenizedBody:on,onErrorChange:se,isProcessing:G,onButtonClick:he,onDecline:l,onTechnicalFailure:ar,runBeforeButtonClick:dn,onLoadStateChange:Ea,placeholderBorderRadius:Yn})}),Tr?d(tr,{stripe:ue,options:Jr,children:d(Ri,{sessionId:e,nonce:t,email:p.email,billingApiUrl:r,intentKind:W>0?"payment":"setup",expressMethods:Zr,onTokenizedBody:on,onErrorChange:se,onButtonClick:he,onDecline:l,onTechnicalFailure:ar,runBeforeButtonClick:dn,onLoadStateChange:xa,placeholderBorderRadius:Yn})}):Fa?d("div",{style:{height:Po,borderRadius:Yn,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,Mr&&d(Ii,{sessionId:e,nonce:t,email:p.email,billingName:[p.firstName,p.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:r,paymentElementMethods:eo,stripeInstance:ue,paymentElementBaseOptions:Mo,onTokenizedBody:on,onErrorChange:se,onButtonClick:he,onDecline:l,runBeforeButtonClick:dn,onLoadStateChange:Ma,isProcessing:G,submitButtonColor:Gn,submitButtonBorderRadius:ht,submitButtonStyle:f.submitButton,onExpandApm:nn,expandedApmMethod:yt,themeId:z,buttonAppearance:{backgroundColor:f.cardButton?.backgroundColor,borderColor:f.cardInputBorder,textColor:f.cardButton?.color,borderRadius:Yn}}),Ve&&d("button",{type:"button",onClick:async()=>{G||!(await dn("card")).proceed||(he?.("card"),Ln())},disabled:G,style:{width:"100%",...q,...f.cardButton,...sa({themeBundle:x,resolvedPrimaryColor:Gn,resolvedBorderRadius:ht,submitButtonStyle:f.submitButton,explicitPrimaryColor:Vt?.colorPrimary}),fontSize:f.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:G?"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:G?.6:1},onMouseEnter:be=>{!G&&(x||Vt?.colorPrimary)&&(be.currentTarget.style.backgroundColor=ms)},onMouseLeave:be=>{(x||Vt?.colorPrimary)&&(be.currentTarget.style.backgroundColor=Gn)},onMouseDown:be=>{be.currentTarget.style.transform="scale(0.985)"},onMouseUp:be=>{be.currentTarget.style.transform="scale(1)"},children:d(lr,{content:j})}),y&&Ie==="buttons"&&d(ur,{margin:"0.25rem 0",styleOverride:f.errorBanner,children:y})]}),Ve&&B&&d("div",{style:{gridArea:"1 / 1",...$?{animation:$}:{},...Ie==="collapsing"?{pointerEvents:"none"}:{}},children:Wa}),T&&Ja&&yt&&io&&ue&&d("div",{style:{gridArea:"1 / 1",...ao?{animation:ao}:{},...Ie==="apm-collapsing"?{pointerEvents:"none"}:{}},children:Le("div",{style:{backgroundColor:zo,borderRadius:$o,...Dr,padding:Uo},children:[Le("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[Le("button",{type:"button","data-testid":"flopay-apm-back-button",onClick:Gt,style:{display:"inline-flex",alignItems:"center",gap:No?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:[d("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:d("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:d("path",{d:"M15 18l-6-6 6-6"})})}),d(cr,{content:K})]}),d("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:f.titleFontSize??"1.05rem",color:Oo,paddingRight:80,...f.title},children:`Pay with ${hr(yt)}`})]}),d(tr,{stripe:ue,options:io,children:d(ra,{method:yt,sessionId:e,nonce:t,email:p.email,billingName:[p.firstName,p.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:r,onTokenizedBody:on,onErrorChange:se,onDecline:l,onCancel:Gt,runBeforeButtonClick:dn,onButtonClick:he,isProcessing:G,submitButtonColor:Gn,submitButtonBorderRadius:ht,submitButtonStyle:f.submitButton,errorText:y})},yt)]})})]})]})}return Ja&&yt&&io&&ue&&T?Le("form",{onSubmit:Fo,className:C,style:{position:"relative"},children:[d(ta,{}),rn&&d(bn,{status:rn,errorMessage:y,authorized:A}),d("div",{style:{...ao?{animation:ao}:{},...Ie==="apm-collapsing"?{pointerEvents:"none"}:{}},children:Le("div",{style:{backgroundColor:zo,borderRadius:$o,...Dr,padding:Uo},children:[Le("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[Le("button",{type:"button","data-testid":"flopay-apm-back-button-default",onClick:Gt,style:{display:"inline-flex",alignItems:"center",gap:No?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:[d("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:d("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:d("path",{d:"M15 18l-6-6 6-6"})})}),d(cr,{content:K})]}),d("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:f.titleFontSize??"1.05rem",color:Oo,paddingRight:80,...f.title},children:`Pay with ${hr(yt)}`})]}),d(tr,{stripe:ue,options:io,children:d(ra,{method:yt,sessionId:e,nonce:t,email:p.email,billingName:[p.firstName,p.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:r,onTokenizedBody:on,onErrorChange:se,onDecline:l,onCancel:Gt,runBeforeButtonClick:dn,onButtonClick:he,isProcessing:G,submitButtonColor:Gn,submitButtonBorderRadius:ht,submitButtonStyle:f.submitButton,errorText:y})},yt)]})})]}):Le("form",{onSubmit:Fo,className:C,style:{position:"relative"},children:[d(ta,{}),rn&&d(bn,{status:rn,errorMessage:y,authorized:A}),Le("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Ya("flopay-direct-paypal-gate-debug-default"),Ga("flopay-stripe-gate-debug-default"),_r&&Ge&&Le(gr,{children:[ge&&d("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."}),d(ho,{sessionId:e,nonce:t,billingApiUrl:r,email:p.email,clientId:Ge.clientId,environment:Ge.environment,currency:ke.toUpperCase(),isSubscription:pt,onTokenizedBody:on,onComplete:i,onErrorChange:se,onDecline:l,onTechnicalFailure:ar,onButtonClick:he,runBeforeButtonClick:dn,isProcessing:G,onLoadStateChange:Ao,onInitializationStateChange:Bo,session:_??null,existingOrderId:ge?.orderId,debug:et},ge?.orderId??"fresh")]}),xr&&d(tr,{stripe:Se,options:wa,children:d(ki,{sessionId:e,nonce:t,email:p.email,billingApiUrl:r,onTokenizedBody:on,onErrorChange:se,isProcessing:G,onButtonClick:he,onDecline:l,onTechnicalFailure:ar,runBeforeButtonClick:dn,onLoadStateChange:Ea,placeholderBorderRadius:Yn})}),Tr&&d(tr,{stripe:ue,options:Jr,children:d(Ri,{sessionId:e,nonce:t,email:p.email,billingApiUrl:r,intentKind:W>0?"payment":"setup",expressMethods:Zr,onTokenizedBody:on,onErrorChange:se,onButtonClick:he,onDecline:l,onTechnicalFailure:ar,runBeforeButtonClick:dn,onLoadStateChange:xa,placeholderBorderRadius:Yn})}),Mr&&d(Ii,{sessionId:e,nonce:t,email:p.email,billingName:[p.firstName,p.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:r,paymentElementMethods:eo,stripeInstance:ue,paymentElementBaseOptions:Mo,onTokenizedBody:on,onErrorChange:se,onButtonClick:he,onDecline:l,runBeforeButtonClick:dn,onLoadStateChange:Ma,isProcessing:G,submitButtonColor:Gn,submitButtonBorderRadius:ht,submitButtonStyle:f.submitButton,themeId:z,onExpandApm:nn,expandedApmMethod:yt,buttonAppearance:{backgroundColor:f.cardButton?.backgroundColor,borderColor:f.cardInputBorder,textColor:f.cardButton?.color,borderRadius:Yn}})]}),Ve&&(is||as||ss)&&Le("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem",margin:"0.5rem 0 0.75rem",color:"#999",fontSize:"0.85rem"},children:[d("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}}),d("span",{children:"or pay with card"}),d("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}})]}),Ve&&Wa]})}import{loadFloPay as Bi,PaymentAPI as Di}from"@flopay/js";import{classifyPaymentRejection as bl,FloPayError as rt,isAuthorizationOnlySession as vl,isSetupIntentClientSecret as Cl,normalizeCheckoutFailureOutcome as Fi}from"@flopay/shared";var Vr="card";async function Sl(e,t,n){if(n){if(typeof e.retrieveSetupIntent!="function")return null;let{setupIntent:i,error:u}=await e.retrieveSetupIntent(t);return{error:u,intent:i??null}}if(typeof e.retrievePaymentIntent!="function")return null;let{paymentIntent:s,error:a}=await e.retrievePaymentIntent(t);return{error:a,intent:s??null}}async function wl(e,t,n,s){if(s){if(typeof e.confirmCardSetup!="function")return null;let{setupIntent:u,error:l}=await e.confirmCardSetup(t,n);return{error:l,intent:u??null}}if(typeof e.confirmCardPayment!="function")return null;let{paymentIntent:a,error:i}=await e.confirmCardPayment(t,n);return{error:i,intent:a??null}}function da(e,t){return Object.assign(e,{checkoutMethod:t})}function Mn(e,t){let n=e instanceof rt?e:new rt(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 Kr(e,t){try{return await e()}catch(n){throw Mn(n,t)}}function Li(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 kl(e){return e.status==="succeeded"||e.status==="declined"}async function zi(e){if(typeof document>"u"||typeof window>"u")throw new rt("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});if(e.signal?.aborted)throw new rt("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"});let t=3e5,n=1e3,s=15e3,a=`${e.billingApiUrl.replace(/\/$/,"")}/v1/checkouts/sessions/${encodeURIComponent(e.sessionId)}/3ds/complete`,i=async()=>{let h=new AbortController,E=()=>h.abort();e.signal?.aborted?h.abort():e.signal?.addEventListener("abort",E);let C=window.setTimeout(()=>h.abort(),s);try{let F=await fetch(a,{method:"POST",headers:{"x-checkout-session-token":e.nonce,"content-type":"application/json"},body:"{}",signal:h.signal});if(!F.ok)return{status:"unknown"};let c=await F.json().catch(()=>null);return Rl(c)}catch{return{status:"unknown"}}finally{window.clearTimeout(C),e.signal?.removeEventListener("abort",E)}},u=document.activeElement instanceof HTMLElement?document.activeElement:null,l=document.createElement("div");l.setAttribute("data-flopay-auto-3ds-overlay","1"),l.setAttribute("role","dialog"),l.setAttribute("aria-modal","true"),l.setAttribute("aria-label","Card authentication"),l.style.cssText=["position:fixed","inset:0","z-index:2147483647","background:rgba(15,23,42,0.6)","display:flex","align-items:center","justify-content:center","padding:16px"].join(";");let v=document.createElement("iframe");v.setAttribute("title","Card authentication"),v.setAttribute("allow","payment"),v.tabIndex=0,v.style.cssText=["width:min(100%,460px)","height:min(100%,640px)","border:0","border-radius:12px","background:#fff","box-shadow:0 12px 30px rgba(0,0,0,0.35)"].join(";"),v.src=e.nextActionRedirectUrl,l.appendChild(v),document.body.appendChild(l),v.focus();let N=null;try{N=new URL(e.billingApiUrl,window.location.href).origin}catch{N=null}try{let h=await new Promise((E,C)=>{let F=!1,c=0,P=0,k=0,T=!1,g=()=>{window.clearTimeout(c),window.clearInterval(P),window.clearTimeout(k),window.removeEventListener("message",ce),v.removeEventListener("load",M),e.signal?.removeEventListener("abort",le)},me=async()=>{if(!(F||T)){T=!0;try{let z=await i();if(F||!kl(z))return;F=!0,g(),E(z)}finally{T=!1}}},M=()=>{window.clearTimeout(k),k=window.setTimeout(()=>{me()},250)},le=()=>{F||(F=!0,g(),C(new rt("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"})))},ce=z=>{if(z.source!==v.contentWindow||N&&z.origin!==N)return;let J=z.data;!J||typeof J!="object"||J.source!=="flopay-vault-3ds-return"||F||(F=!0,g(),E(null))};c=window.setTimeout(()=>{F||(F=!0,g(),C(new rt("Card authentication timed out.","api_error",{code:"three_ds_timeout"})))},t),P=window.setInterval(()=>{me()},n),v.addEventListener("load",M),window.addEventListener("message",ce),e.signal?.addEventListener("abort",le),e.signal?.aborted&&le()});return h||await i()}finally{l.parentNode?.removeChild(l),u?.isConnected&&u.focus()}}function Rl(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 $n(e,t="Payment failed. Please try again.",n){let s=n?.checkoutMethod??e?.checkoutMethod??(e?.type==="paypal_redirect_required"?"paypal":"card"),a=e?.message??t,i=Nn(a)??a;return da(new rt(i,"api_error",{code:Fi(e?.outcome)??Fi(e?.type)??e?.gatewayErrorCode}),s)}function ca(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function vo(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}async function Il(e){try{return await e()}catch(t){let n=t instanceof Error?t.message:String(t);if(!/failed to fetch|fetch failed/i.test(n))throw t;return e()}}function Ni(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let a of n)if(typeof a=="string"&&a.length>0&&(!t?.requirePaymentIntentClientSecret||vo(a)))return a;let s=e?.data;if(s&&typeof s=="object"){let a=s,i=[a.threeDSecureToken,a.clientSecret,a.stripeClientSecret,a.id];for(let l of i)if(typeof l=="string"&&l.length>0&&(!t?.requirePaymentIntentClientSecret||vo(l)))return l;let u=a.gateways;if(u&&typeof u=="object"){let l=u.stripe;if(l&&typeof l=="object"){let v=l,N=[v.stripeClientSecret,v.clientSecret];for(let h of N)if(typeof h=="string"&&h.length>0&&(!t?.requirePaymentIntentClientSecret||vo(h)))return h}}}}async function El({billingApiUrl:e,sessionId:t,nonce:n,responseJson:s}){let a=Ni(s,{requirePaymentIntentClientSecret:!0});if(typeof a=="string"&&a.length>0)return{type:"3ds_required",threeDSecureToken:a};if(!t)return null;try{let l=(await new Di(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(vo(l))return{type:"3ds_required",threeDSecureToken:l}}catch{}return null}async function Pr({billingApiUrl:e,sessionId:t,session:n,nonce:s,tokenizedData:a,returnUrl:i,telemetry:u}){let l=e.replace(/\/+$/,""),v=t??n.id,N=s??n.clientSecret,h=n.customer?.id??n.accountData?.userId??"",E=n.customer?.email??n.accountData?.email??"",C=n.customer?.firstName??n.accountData?.firstName??"",F=n.customer?.lastName??n.accountData?.lastName??"",c=n.customer?.country??n.accountData?.country??void 0,P=n.customer?.zip??n.accountData?.zip??void 0,k=new Di(l,u===!1?{telemetry:!1}:void 0),T=await Il(()=>k.processPayment(h,{sessionId:v,nonce:N,tokenizedData:a,accountData:{userId:h,email:E,firstName:C,lastName:F,country:c,zip:P},returnUrl:i??ca(n)}));if(T.ok){let M=typeof T.json=="function"?await T.json().catch(()=>null):null;return vl(n)||M?.status==="authorized"?{type:"success",result:{status:"authorized",paymentId:typeof M?.paymentId=="string"?M.paymentId:n.paymentId,sessionId:typeof M?.sessionId=="string"?M.sessionId:v,authorizationExpiresAt:typeof M?.authorizationExpiresAt=="string"?M.authorizationExpiresAt:n.authorizationExpiresAt,paymentMethodId:Ur(a),checkoutMethod:a?a.isPaypal?"paypal":"card":void 0}}:{type:"success",result:{status:"succeeded",paymentIntentId:a?.threeDSecureActionResultTokenId,paymentMethodId:Ur(a),checkoutMethod:a?a.isPaypal?"paypal":"card":void 0}}}let g;try{g=await T.json()}catch{throw new rt("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:T.status})}if(g?.type==="paypal_redirect_required"||g?.type==="3ds_required"){let M=Ni(g);if(!M)throw new rt("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:T.status});return{type:g.type,threeDSecureToken:M,paymentMethodId:g.paymentMethodId}}if(g?.gatewayErrorCode==="authentication_required"){let M=await El({billingApiUrl:l,sessionId:v,nonce:N,responseJson:g});if(M)return M;throw da(new rt("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}let me=new rt(g?.message??"Payment failed. Please try again.","api_error",{code:g?.code??g?.gatewayErrorCode,declineCode:g?.declineCode??g?.gatewayDeclineReason,statusCode:T.status});throw Object.assign(me,{telemetryOutcome:bl(T.status,g)})}async function Co(e,{flopay:t,paypalFlopay:n,attempt3DS:s,billingApiUrl:a,sessionId:i,session:u,returnUrl:l,telemetry:v}){let N=t?.getRawProvider();if(!N)throw Mn(new rt("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!s||!e.threeDSecureToken)throw da(new rt("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let h=Cl(e.threeDSecureToken),E=null,C=e.paymentMethodId,F=await Kr(()=>Sl(N,e.threeDSecureToken,h),"card");if(F){if(F.error)throw Mn(new rt(F.error.message??`Failed to retrieve 3DS ${h?"setup":"payment"} status.`,"api_error",{code:F.error.code}),"card");let P=F.intent;!C&&P?.payment_method&&(typeof P.payment_method=="string"?C=P.payment_method:"id"in P.payment_method&&(C=P.payment_method.id??void 0))}let c=C?await Kr(()=>wl(N,e.threeDSecureToken,{payment_method:C,return_url:l??ca(u)??window.location.href},h),"card"):null;if(c){if(c.error)throw Mn(new rt(c.error.message??"3DS authentication failed.","api_error",{code:c.error.code}),"card");E=c.intent}else{let P=await Kr(()=>N.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(P.error)throw Mn(new rt(P.error.message??"3DS authentication failed.","api_error",{code:P.error.code}),"card");E=(h?P.setupIntent:P.paymentIntent)??null}if(E&&(E.status==="requires_capture"||E.status==="succeeded"||E.status==="processing")){let P=await Pr({billingApiUrl:a,sessionId:i,session:u,telemetry:v,tokenizedData:{id:E.id,type:"card",threeDSecureActionResultTokenId:E.id},returnUrl:l});return P.type==="success"?{...P.result,paymentIntentId:P.result.paymentIntentId??E.id,paymentMethodId:P.result.paymentMethodId??C}:Co(P,{flopay:t,paypalFlopay:n,attempt3DS:s,billingApiUrl:a,sessionId:i,session:u,returnUrl:l,telemetry:v})}throw Mn(new rt("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let h=(n??t)?.getRawProvider();if(!h)throw Mn(new rt("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:C}=await Kr(()=>h.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(C)throw Mn(new rt(C.message??"PayPal authorization failed.","api_error",{code:C.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:E}=await Kr(()=>h.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:l??ca(u)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(E)throw Mn(new rt(E.message??"PayPal authorization failed.","api_error",{code:E.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new rt("Unsupported payment redirect state.","api_error")}function nr(e){if(e instanceof rt){let s=Nn(e.message);return s&&s!==e.message?Object.assign(new rt(s,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=Nn(t)??t;return new rt(n,"api_error")}function So(e){let t=e.data.stripe?.publishableKey,n=!!e.data.paypal?.publishableKey;if(!t&&!n)throw new rt("Session advertises no supported gateways (expected `gateways.stripe` and/or `gateways.paypal`).","validation_error");return t?{publishableKey:t,paypalPublishableKey:e.data.stripe?.paypalPublishableKey??t}:{}}async function wo({publishableKey:e,paypalPublishableKey:t,billingApiUrl:n,locale:s,telemetry:a}){if(!e)return{flopay:null,paypalFlopay:null};let i=!!t&&t!==e,[u,l]=await Promise.all([Bi(e,{billingApiUrl:n,locale:s,telemetry:a}),i?Bi(t,{billingApiUrl:n,locale:s,telemetry:a}).catch(v=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",v),null)):Promise.resolve(null)]);return{flopay:u,paypalFlopay:t?i?l:u:null}}import{Fragment as wn,jsx as ee,jsxs as _t}from"react/jsx-runtime";var br=44,Pa="flopay_checkout_saved_payment_resume",Eo=new Map,Ro=new Map;function qi(e,t){t.settled&&t.consumers===0&&Eo.get(e)===t&&Eo.delete(e)}function Bl(e,t,n){let s=Ro.get(e);if(s&&(!s.sdkGeneratedIdempotencyKey||!t||s.sdkGeneratedIdempotencyKey===t))return s.attempt;let a=n(),i={attempt:a,sdkGeneratedIdempotencyKey:t};Ro.set(e,i);let u=()=>{Ro.get(e)===i&&Ro.delete(e)};return a.then(u,u),a}function Hr(e){return new Promise(t=>setTimeout(t,e))}function Io(e,t,n){let s=so({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:Hi,enabled:t!==!1});return s.beginCheckout(n),s}function Wr(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function pa(e,t,n,s,a){let i=Io(e,t,n);i.error({errorCode:s,stage:a,paymentMethodCategory:"unknown",...a==="session_read"?{requestCategory:"session_read"}:{}}),Wr(i)}function Fl(e){return e.type==="validation_error"||e.code==="checkout_session_not_found"||e.code==="checkout_session_expired"||e.code==="checkout_session_completed"||e.code==="session_auto_completed"}function ga(e){let t=e?.data.paypal?.publishableKey;if(t)return{clientId:t,environment:e?.data.paypal?.environment}}function ma(e){return!e||e.data.stripe?.publishableKey?!1:!!ga(e)?.clientId}function Bn(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function Dl(){if(!Bn())return null;try{let e=window.sessionStorage.getItem(Pa);return e?JSON.parse(e):null}catch{return null}}function ji(e){if(Bn())try{window.sessionStorage.setItem(Pa,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function ya(){if(Bn())try{window.sessionStorage.removeItem(Pa)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}var ba=":idempotency-key";function Ll(e){if(!Bn())return null;let t=window.sessionStorage.getItem(e);if(!t)return null;try{let n=JSON.parse(t);return n&&typeof n.sid=="string"&&n.sid?{sid:n.sid,nonce:typeof n.nonce=="string"?n.nonce:void 0}:null}catch{return{sid:t}}}function Ki(e,t,n){if(Bn())try{window.sessionStorage.setItem(e,JSON.stringify(n?{sid:t,nonce:n}:{sid:t}))}catch(s){console.warn("[FloPayCheckout] Failed to persist checkout session cache.",s)}}function ha(e){if(Bn())try{window.sessionStorage.removeItem(e)}catch(t){console.warn("[FloPayCheckout] Failed to clear checkout session cache.",t)}}function zl(e){if(Bn())try{return window.sessionStorage.getItem(e+ba)??void 0}catch{return}}function Nl(e,t){if(Bn())try{window.sessionStorage.setItem(e+ba,t)}catch(n){console.warn("[FloPayCheckout] Failed to persist checkout idempotency key.",n)}}function Ol(e){if(ha(e),!!Bn())try{window.sessionStorage.removeItem(e+ba)}catch(t){console.warn("[FloPayCheckout] Failed to clear checkout idempotency key.",t)}}function Ul(){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 s of t)e.searchParams.has(s)&&(e.searchParams.delete(s),n=!0);n&&window.history.replaceState(window.history.state,"",e.toString())}function Vi(e){if(typeof window>"u")return;let t=new URL(window.location.href);t.searchParams.set("mode",e),window.history.replaceState(window.history.state,"",t.toString())}function $l(e){return e?!!(e.account&&Object.keys(e.account).length>0||e.couponCodes!==void 0||e.tagsData!==void 0||e.utmMetadata!==void 0):!1}function fa(e,t){return`${e}:${t.totalAmount??""}:${t.overrideAmount??""}:${t.quantity??1}:${t.currency??""}`}function va({sessionId:e,nonce:t,createSession:n,billingApiUrl:s,telemetry:a,appearance:i,locale:u,loading:l,error:v,onComplete:N,onError:h,onDecline:E,onCountryChange:C,onZipChange:F,showPayPal:c=!0,showStripe:P=!0,enabledPaymentMethods:k,showApplePay:T=!0,showGooglePay:g=!0,debug:me=!1,layout:M,theme:le,buttonsTheme:ce,buttonsStyles:z,cardButtonContent:J,cardBackButtonContent:H,cardTitleContent:oe,showSecurityFooter:j,onButtonClick:K,onBeforeButtonClick:ie,enableAVS:xe,cardFieldOrder:he,cardPreFormSlot:de,avsLayout:Q,className:ye,initialErrorMessage:Te=null,children:Z,checkoutMode:Ue,confirmLabel:Fe,renderConfirmButton:we,onSessionCompleted:V}){let b=Tl(s),te=pn(()=>Wi(le),[le]),$e=i??te?.appearance,ze=n?"embedded_checkout":"standard_checkout",ae=Z?"custom_layout":M==="buttons"?"buttons_layout":"default_layout",[R,re]=bt(null),[W,ke]=bt(null),dt=Ot(null),[Ge,pt]=bt(null),_=Ot(null),[Y,et]=bt(null),[qe,mt]=bt(e??""),Ne=e??qe,He=n?"":Ne,[Jt,Ye]=bt(!0),[Xt,S]=bt(null),[fe,We]=bt("full"),[Re,vt]=bt(!1),[Ke,je]=bt(Te),[tt,Je]=bt(null),[kn,ot]=bt(null),[jn,Wt]=bt(!1),[mn,Qt]=bt(void 0),[or,Bt]=bt(""),[St,Zt]=bt(!1),[en,Ft]=bt(!1),Dt=Ot(0),[Ct,X]=bt("loading"),[Kn,A]=bt(0),at=Ot(!1),Lt=Ot(!1),Fn=Ot(!1),Me=Ot(null),it=pn(()=>({checkoutMode:Ue??fe,layout:Z?"unknown":M==="buttons"?"buttons":"embedded"}),[Ue,Z,fe,M]),Ve=Ot(N);Ve.current=N;let Rn=Ot(h);Rn.current=h;let In=Ot(E);In.current=E,An(()=>{At(W)?.setCheckoutContext(it),Ge&&Ge!==W&&At(Ge)?.setCheckoutContext(it)},[W,Ge,it]);let Dn=Ot(V);Dn.current=V;let Vn=rr(w=>{X(w),!(w!=="exhausted"||Fn.current)&&(Fn.current=!0,Rn.current?.(new Et("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),En=rr(()=>{X("retrying"),A(w=>w+1)},[]);An(()=>{X("loading"),A(0),Fn.current=!1},[Ne]),An(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:Hi,checkout_type:ze,checkout_layout:ae,billing_api_url:b})},[ae,ze,b]);let nt=pn(()=>n?Ut(n,!0):"",[n]),zt=pn(()=>or===nt?mn:void 0,[mn,or,nt]),sn=pn(()=>n?Wo(n,zt):void 0,[n,zt]),gt=Ue??sn?.checkoutMode??"full",xt=pn(()=>sn?{...sn,checkoutMode:gt}:void 0,[sn,gt]);An(()=>{Qt(void 0),Bt(nt)},[nt]),An(()=>{je(Te)},[Te]);let tn=rr((w,D,I)=>{ut(()=>{In.current?.(It(w,D,I))})},[ut]),ln=rr(async(w,D)=>{je(null),ot(null),Wt(!1),Je("processing");let I=D?.sessionId??w.id,ge=dt.current??_.current,Pe=At(ge),m=ge?null:Io(b,a,it),r={log:p=>{Pe?Pe.log(p):m?.log(p)},error:p=>{Pe?Pe.error(p):m?.error(p)},terminal:p=>{Pe?Pe.terminal(p):m?.terminal(p)},performance:p=>{Pe?Pe.performance(p):m?.performance(p)},now:()=>Pe?.now()??m?.now()??0,elapsed:p=>Pe?.elapsed(p)??Math.max(0,(m?.now()??p)-p)},y=r.now(),x=!!(D?.initialAutoProcessingError||D?.initialAutoProcessingPending),f=!1,O,Ae=()=>{f||(f=!0,x=!0,O=r.now(),r.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),r.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},Xe=!1,G=()=>{Xe||(Xe=!0,r.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),r.performance({stage:"processing",durationMs:r.elapsed(y),durationMode:"machine",paymentMethodCategory:"saved"}),O!==void 0&&r.performance({stage:"recovery",durationMs:r.elapsed(O),durationMode:"machine",paymentMethodCategory:"saved"}))};r.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),r.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"}),x&&Ae();let U;try{let p=Li(D?.initialAutoProcessingError),L;if(p)Ae(),p.type==="paypal_redirect_required"&&Me.current?.publishableKey&&ji({sessionId:I,publishableKey:Me.current.publishableKey,paypalPublishableKey:Me.current.paypalPublishableKey}),L=await Co(p,{flopay:dt.current,paypalFlopay:_.current,attempt3DS:D?.attempt3DS,billingApiUrl:b,sessionId:I,session:w,telemetry:!1}),p.type==="paypal_redirect_required"&&ya();else if(D?.initialAutoProcessingPending){let Ee=(await new ko(b,{telemetry:!1}).waitForCheckoutSessionCompletion(D.initialAutoProcessingPending.sessionId,{initialDelayMs:D.initialAutoProcessingPending.retryAfterMs})).data.session;if(!pr(Ee))throw po(Ee);L=Qn(Ee,I)}else{if(D?.initialAutoProcessingError)throw $n(D.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:D.initialAutoProcessingError.checkoutMethod});if(D?.fromCreateSession)return D?.fallbackToFull&&(We("full"),Vi("full")),!1;{let ue=await Pr({billingApiUrl:b,sessionId:I,session:w,telemetry:!1});ue.type==="success"?L=ue.result:(Ae(),ue.type==="paypal_redirect_required"&&Me.current?.publishableKey&&ji({sessionId:I,publishableKey:Me.current.publishableKey,paypalPublishableKey:Me.current.paypalPublishableKey}),L=await Co(ue,{flopay:dt.current,paypalFlopay:_.current,attempt3DS:D?.attempt3DS,billingApiUrl:b,sessionId:I,session:w,telemetry:!1}),ue.type==="paypal_redirect_required"&&ya())}}I&&mr(I),G(),x&&(r.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),r.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),r.terminal({outcome:L.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),Wt(L.status==="authorized"),Je("success"),await Hr(_n),U=()=>Ve.current?.(L)}catch(p){let L=nr(p),ue=L.checkoutMethod??Vr;je(L.message),ot(L.message),Wt(!1),D?.fallbackToFull&&(r.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),We("full"),Vi("full")),G();let Se=L.statusCode!==void 0?Al(L.statusCode,"unknown"):void 0,Ee=Se==="4xx"?{requestCategory:"process_payment",statusClass:Se}:{},fn=Se===void 0||Se==="4xx";if(fn&&(L.telemetryOutcome==="payment_declined"||!!(L.declineCode||L.code?.toLowerCase().includes("declin"))))r.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...Ee});else if(fn&&(L.telemetryOutcome==="validation_rejected"||L.type==="validation_error"))r.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...Ee});else{let Jr=Oi(p,x?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown");r.error({...Jr,...L.telemetryFailureCategory?{failureCategory:L.telemetryFailureCategory}:{},stage:x?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:L.telemetryRequestCategory??"process_payment"})}return ut(()=>Rn.current?.(L)),tn(ue,L,{code:L.code,declineCode:L.declineCode}),Je("error"),await Promise.allSettled([Hr(Pn),D?.ensureProvidersReady?D.ensureProvidersReady():Promise.resolve()]),x&&(r.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),r.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{G(),m&&Wr(m),Je(null),ot(null)}return ut(U),!0},[tn,ut,nr,b,a,it]);An(()=>{if(typeof window>"u"||Lt.current)return;let w=new URLSearchParams(window.location.search),D=w.get("payment_intent_client_secret");if(!D)return;let I=Dl();I&&(Lt.current=!0,(async()=>{let ge,Pe=0;je(null),ot(null),Je("processing"),vt(!0);try{if(w.get("redirect_status")==="failed")throw Object.assign(new Et("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:m,paypalFlopay:r}=await wo({publishableKey:I.publishableKey,paypalPublishableKey:I.paypalPublishableKey,billingApiUrl:b,locale:u,telemetry:a});ge=At(r??m),Pe=ge?.now()??0,ge?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),ge?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let y=(r??m)?.getRawProvider();if(!y)throw Object.assign(new Et("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:x,error:f}=await y.retrievePaymentIntent(D);if(f)throw Object.assign(new Et(f.message??"Failed to retrieve PayPal payment status.","api_error",{code:f.code}),{checkoutMethod:"paypal"});let O=si(x?.status);if(!x||O==="failed")throw Object.assign(new Et("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let Ae=typeof x.payment_method=="string"?x.payment_method:x.payment_method?.id,Xe=O;if(I.sessionId){let p=(await new ko(b,{telemetry:!1}).getUnifiedCheckoutSession(I.sessionId)).data.session;if(p&&p.status!=="complete"){let L=await Pr({billingApiUrl:b,sessionId:I.sessionId,session:p,telemetry:!1,tokenizedData:{id:Ae??x.id,type:"card",threeDSecureActionResultTokenId:x.id,isPaypal:!0}});if(L.type!=="success")throw Object.assign(new Et("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});Xe=L.result.status}}I.sessionId&&mr(I.sessionId),ge?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),ge?.performance({stage:"redirect_resume",durationMs:ge.elapsed(Pe),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),ge?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),Je("success"),await Hr(_n),ut(()=>Ve.current?.({status:Xe,paymentIntentId:x.id,paymentMethodId:Ae,checkoutMethod:"paypal"}))}catch(m){let r=nr(m),y=r.checkoutMethod??"paypal",x=!!(r.declineCode||r.code?.toLowerCase().includes("declin"));if(ge)ge.performance({stage:"redirect_resume",durationMs:ge.elapsed(Pe),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),x?ge.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):ge.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(x){let f=Io(b,a,it);f.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),Wr(f)}else pa(b,a,it,"REDIRECT_RESUME_FAILED","redirect_resume");je(r.message),ot(r.message),ut(()=>Rn.current?.(r)),tn(y,r,{code:r.code,declineCode:r.declineCode}),Je("error"),await Hr(Pn)}finally{ya(),Ul(),Je(null),ot(null),vt(!1)}})())},[tn,ut,u,nr,b,a]);let Yt=Ot(null);function Ut(w,D=!1){let I=w?.account?.email?.trim().toLowerCase()??"",ge={c:w?.clientId,cur:w?.currency??"",captureMethod:w?.captureMethod??"",a:{e:I,u:I?"":w?.account?.userId??"",country:w?.account?.country??""},successUrl:w?.successUrl,cancelUrl:w?.cancelUrl,p:w?.products?.map(r=>fa(`${r.type??""}:${r.code??r.providerItemId??r.providerPlanId??""}`,r)).sort(),i:w?.items?.map(r=>fa(r.code??r.providerItemId??"",r)).sort(),s:w?.subscriptions?.map(r=>fa(r.code??r.providerPlanId??"",r)).sort(),couponCodes:w?.couponCodes?[...w.couponCodes].sort():void 0,...D?{tagsData:w?.tagsData,utmMetadata:w?.utmMetadata,tokenizedData:w?.tokenizedData,checkoutMode:w?.checkoutMode??"full"}:{}},Pe=JSON.stringify(ge),m=0;for(let r=0;r<Pe.length;r++)m=(m<<5)-m+Pe.charCodeAt(r)|0;return`flopay_session_${Math.abs(m).toString(36)}`}let $t=pn(()=>xt?Ut(xt):"",[xt]),Ie=Ot(xt);Ie.current=xt,An(()=>{mt(e??"")},[e]),An(()=>{at.current=!1,je(Te),ot(null),Wt(!1),Je(null)},[$t,Te,e]);async function qt(w,D){let I=Io(b,a,it),ge=new ko(b,{telemetry:!1}),Pe=!1;try{let m=w.idempotencyKey!==void 0?$i(w.idempotencyKey):void 0,r=m??zl(D),y,x=!1,f=Ll(D);I.log({name:f?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let O=f?.sid??null,Ae=null,Xe;if(O)try{if(Ae=await ge.getUnifiedCheckoutSession(O,f?.nonce),Ae.data.session?.status==="complete"){if(Go(O))return{sid:O,result:Ae};Ol(D),O=null,Ae=null,x=!0}}catch{I.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),ha(D),O=null}if(!O){!m&&(x||!r)&&(r=$i(),y=r),r&&Nl(D,r);let G=I.now(),U=0;I.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let p={...w,idempotencyKey:r,avsCheck:!!xe,avsConfig:typeof xe=="object"?xe:void 0,checkoutType:"embedded_checkout",checkoutLayout:Z?"custom_layout":M==="buttons"?"buttons_layout":"default_layout"};Object.defineProperty(p,_l,{configurable:!1,enumerable:!1,value:{onAttempt:Se=>{U=Math.max(U,Se)}}});let L=()=>{I.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:"2xx"}),I.performance({stage:"session_create",durationMs:I.now()-G,durationMode:"machine",requestCategory:"session_create",attempt:U,statusClass:"2xx"})},ue=Se=>{let Ee=Oi(Se,"CHECKOUT_SESSION_CREATE_FAILED","unknown");I.performance({stage:"session_create",durationMs:I.now()-G,durationMode:"machine",requestCategory:"session_create",attempt:U,statusClass:Ee.statusClass}),Se instanceof Et&&Se.type==="validation_error"?I.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown"}):Ee.statusClass==="4xx"?I.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create",statusClass:"4xx"}):I.error({...Ee,stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create"})};try{if(xl(p)){let Se=await ge.createDetachedSession(p);Se.claimed.catch(()=>{}),Ae=Se.shell,O=Se.sessionId,Xe=Se.claimed.then(Ee=>{let fn=Ee.data.session?.id??Se.sessionId;return fn&&Ki(D,fn,Ee.data.session?.clientSecret??Se.nonce),L(),Ee},Ee=>{throw ha(D),ue(Ee),Ee}).finally(()=>Wr(I)),Xe.catch(()=>{}),Pe=!0,I.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),I.performance({stage:"session_shell",durationMs:I.now()-G,durationMode:"machine",requestCategory:"session_create",attempt:U,statusClass:"2xx",paymentMethodCategory:"card"})}else Ae=await ge.createAndFetchSession(p),L()}catch(Se){throw ue(Se),Se}O=Ae.data.session?.id??O??"",O&&!Xe&&Ki(D,O,Ae.data.session?.clientSecret)}return{sid:O??"",result:Ae,sdkGeneratedIdempotencyKey:y,...Xe?{claimed:Xe}:{}}}finally{Pe||Wr(I)}}let yt=rr(async(w,D)=>{let I=Ie.current;if(!I)throw new Et("createSession is required to bootstrap checkout.","validation_error");let ge=Wo(I,w),Pe=Ut(ge),m=Eo.get(Pe);if(!m){let x={promise:qt(ge,Pe),consumers:0,settled:!1};m=x,Eo.set(Pe,x);let f=()=>{x.settled=!0,qi(Pe,x)};x.promise.then(f,f)}m.consumers+=1;let r=!1,y=()=>{r||(r=!0,m.consumers-=1,qi(Pe,m))};D?.(y);try{let x=await m.promise;Yt.current=Pe,w&&(Bt(nt),Qt(L=>oi(L,w)));let{sid:f,result:O,claimed:Ae}=x;if(re(O),O.data.session&&et(O.data.session),f&&mt(f),Ae){let L=Dt.current+=1;Ft(!0),Ae.then(ue=>{Dt.current===L&&(re(ue),ue.data.session&&et(ue.data.session),Ft(!1))},ue=>{Dt.current===L&&(Ft(!1),S(ue instanceof Et?ue:new Et(ue instanceof Error?ue.message:"Failed to create session","api_error")))})}else Dt.current+=1,Ft(!1);let{publishableKey:Xe,paypalPublishableKey:G}=So(O),{flopay:U,paypalFlopay:p}=await wo({publishableKey:Xe,paypalPublishableKey:G,billingApiUrl:b,locale:u,telemetry:a});return dt.current=U,ke(U),_.current=p,pt(p),Ye(!1),x}catch(x){throw Yt.current===Pe&&(Yt.current=null),x}finally{D||y()}},[u,b,a,it]),yn=Ot(ln);yn.current=ln;let Hn=Ot(yt);Hn.current=yt;let jt=rr(async w=>{if(!$l(w)||St)return{sessionId:qe,session:Y};Zt(!0);try{let D=await yt(w);return{sessionId:D.sid,session:D.result.data.session??null}}finally{Zt(!1)}},[yt,St,qe,Y]);An(()=>{let w=!1,D;if(S(null),$t){let Pe=Ie.current;return We(gt),Ye(!1),Yt.current===$t?()=>{w=!0}:(et(ai(Pe,Ue)),(async()=>{let m=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),r=gt==="auto"&&!at.current&&!m;r&&(je(null),ot(null),Je("processing"));try{let y=await Hn.current(void 0,Ae=>{D=Ae}),x=y.result.data.session??null;Me.current=So(y.result);let f=ma(y.result),O=Go(y.sid||x?.id);if(!w&&r&&x&&!f&&!O){at.current=!0,await Bl($t,y.sdkGeneratedIdempotencyKey,()=>yn.current(x,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:y.result.autoProcessingError,initialAutoProcessingPending:y.result.autoProcessingPending,autoProcessingAttempted:y.result.autoProcessingAttempted,sessionId:y.sid||x.id}));return}!w&&r&&((f||O)&&(at.current=!0),Je(null),ot(null))}catch(y){if(w)return;let x=y instanceof Et||typeof y=="object"&&y!==null&&"code"in y?y.code:void 0;if(r&&x==="session_auto_completed"){at.current=!0,Je("success"),await Hr(_n),w||(ut(()=>{Ve.current?.({status:"succeeded"})}),Je(null),ot(null));return}r&&(Je(null),ot(null));let f=y instanceof Et?y:new Et(y instanceof Error?y.message:"Failed to create session","api_error");S(f)}finally{D?.(),D=void 0}})(),()=>{w=!0,D?.()})}Ye(!0);async function I(){let Pe=!1;try{let r=await new ko(b,{telemetry:!1}).getUnifiedCheckoutSession(Ne,t);if(w)return;re(r);let y=r.data.session??null;if(et(y),!y)throw new Et("No session data returned","api_error");let x=y.checkoutMode;if(x==="setup")throw new Et("This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.","validation_error",{code:"InvalidCardSetupSurface",param:"sessionId"});if(y.status==="authorized"){Ye(!1),ut(()=>{Ve.current?.(Qn(y,Ne)),Dn.current?.(y.successUrl??"")});return}if(y.status==="complete"){Ye(!1),ut(()=>{Dn.current?.(y.successUrl??"")});return}if(y.status==="expired")throw uo(y);Pe=!0;let f=Ue??x??"full";We(f);let O=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),Ae=ma(r);if(f==="auto"&&!at.current&&!O&&!Ae){at.current=!0;let Xe=ge(r);try{if(await yn.current(y,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>Xe,sessionId:Ne||y.id}),w)return;await Xe,w||Ye(!1);return}catch{if(w)return;await Xe,w||Ye(!1);return}}await ge(r),w||Ye(!1)}catch(m){if(w)return;m instanceof Et?!Pe&&!Fl(m)&&pa(b,a,it,"NETWORK_REQUEST_FAILED","session_read"):pa(b,a,it,"INTERNAL_SDK_ERROR","checkout_mount");let r=m instanceof Et?m:new Et(m instanceof Error?m.message:"Failed to initialize checkout","api_error");S(r),Ye(!1)}}async function ge(Pe){let{publishableKey:m,paypalPublishableKey:r}=So(Pe);Me.current={publishableKey:m,paypalPublishableKey:r};let{flopay:y,paypalFlopay:x}=await wo({publishableKey:m,paypalPublishableKey:r,billingApiUrl:b,locale:u,telemetry:a});dt.current=y,ke(y),_.current=x,pt(x)}return I(),()=>{w=!0}},[Ue,$t,gt,He,ut,t]);let Kt=rr(async()=>{if(!(Re||!Y)){vt(!0),je(null);try{await ln(Y,{attempt3DS:!0,fallbackToFull:!0,sessionId:Ne||Y.id})}finally{vt(!1)}}},[Ne,Re,ln,Y]),Nt=ga(R),Ln=ma(R),zn=pn(()=>{if(!R||!Y||!R.data.stripe?.publishableKey)return;let w={appearance:$e,paymentMethodCreation:"manual",billingApiUrl:b};if(R.data.stripe?.clientSecret)w.clientSecret=R.data.stripe.clientSecret;else{let D=Ui(Y).total;w.amount=Math.round(D*100)||Y.amount,w.currency=Y.currency?.toLowerCase()}return w},[R,Y,$e,b]),nn=!!(n&&!Z&&M==="buttons"&&ie&>==="full"),Gt=pn(()=>({session:Y,loading:Jt,error:Xt,checkoutMode:fe,inlineSessionDraft:xt,applyInlineSessionPatch:nn?jt:void 0,inlineSessionPatchProcessing:St,claimPending:en}),[Y,Jt,Xt,fe,xt,nn,jt,St,en]),rn=!!n&&M==="buttons"&&!Ln&&(!W||!zn),Oe=tt?ee(bn,{status:tt,errorMessage:kn,authorized:jn}):null;if(Jt){if(l)return _t(wn,{children:[l,Oe]});if(M==="buttons"){let w=te?.buttonsLayout?.cardButton?.borderRadius??te?.appearance.variables?.borderRadius??8,D=I=>ee("div",{style:{height:I,borderRadius:w,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return _t(wn,{children:[_t("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[c&&D(br),P&&(T||g)&&D(br),P&&D(br),ee("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),Oe]})}return _t(wn,{children:[_t("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[ee("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),ee("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),Oe]})}return Xt?v?ee(un.Provider,{value:Gt,children:v(Xt)}):ee(un.Provider,{value:Gt,children:ee("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:Xt.message})}):rn?_t(wn,{children:[ee(un.Provider,{value:Gt,children:ee(jl,{onButtonClick:K,showPayPal:c,showStripe:P,showApplePay:T,showGooglePay:g,theme:le,buttonsTheme:ce,buttonsStyles:z,cardButtonContent:J,cardBackButtonContent:H,cardTitleContent:oe})}),Oe]}):Ln&&Y&&Nt?_t(wn,{children:[ee(un.Provider,{value:Gt,children:_t("div",{className:ye,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Ke&&ee(ur,{icon:!1,children:Ke}),Ct==="retrying"&&ee("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),Ct==="exhausted"&&_t("div",{role:"alert",children:[ee("div",{children:"PayPal is temporarily unavailable. Please try again."}),ee("button",{type:"button",onClick:En,children:"Retry PayPal"})]}),Ct!=="exhausted"&&ee("div",{"aria-hidden":Ct==="retrying"?!0:void 0,style:Ct==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:ee(yi,{sessionId:Ne,nonce:Y.clientSecret||void 0,billingApiUrl:b,email:Y.customer?.email,clientId:Nt.clientId,environment:Nt.environment,currency:(Y.currency??"usd").toUpperCase(),isSubscription:Y.mode==="subscription",onComplete:N,onErrorChange:je,onDecline:E,onButtonClick:K,onInitializationStateChange:Vn,allowAutomaticRetry:Kn===0,session:Y,telemetry:a,telemetryContext:it,debug:me},`paypal-init-${Kn}`)})]})}),Oe]}):!W||!zn?ee(wn,{children:Oe}):fe==="confirm"?_t(wn,{children:[ee(un.Provider,{value:Gt,children:ee(lo,{flopay:W,paypalFlopay:Ge,options:zn,children:_t("div",{className:ye,children:[Ke&&ee("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:Ke}),we?we({onConfirm:Kt,isProcessing:Re}):ee("button",{type:"button",onClick:Kt,disabled:Re,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:Re?"not-allowed":"pointer",opacity:Re?.6:1},children:Re?"Processing...":Fe??"Confirm Purchase"})]})})}),Oe]}):_t(wn,{children:[ee(un.Provider,{value:Gt,children:ee(lo,{flopay:W,paypalFlopay:Ge,options:zn,children:Z?_t(wn,{children:[Ke&&ee("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:Ke}),ee(ql,{sessionId:Ne,nonce:Y?.clientSecret||void 0,billingApiUrl:b,session:Y,children:Z})]}):ee(la,{sessionId:Ne,nonce:Y?.clientSecret||void 0,email:Y?.customer?.email,userId:Y?.customer?.id,firstName:Y?.customer?.firstName,lastName:Y?.customer?.lastName,totalAmount:Y?Math.round(Ui(Y).total*100):0,currency:Y?.currency?.toLowerCase()??"usd",onComplete:N,onError:h,onDecline:E,error:Ke,onErrorChange:je,showPayPal:c,showStripe:P,enabledPaymentMethods:k??R?.data.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:R?.data.stripe?.enabledPaymentMethodCountries,showApplePay:T,showGooglePay:g,layout:M,theme:le,buttonsTheme:ce,buttonsStyles:z,appearance:$e,cardButtonContent:J,cardBackButtonContent:H,cardTitleContent:oe,onButtonClick:K,onBeforeButtonClick:ie,enableAVS:xe,...he?{cardFieldOrder:he}:{},...de?{cardPreFormSlot:de}:{},avsLayout:Q,country:Y?.customer?.country,city:Y?.customer?.city,state:Y?.customer?.state,onCountryChange:C,onZipChange:F,avsCheck:!!xe,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:Z?"custom_layout":M==="buttons"?"buttons_layout":"default_layout",className:ye,directPaypal:ga(R),isSubscription:Y?.mode==="subscription",session:Y,dataAttachmentPending:en,debug:me})})}),Oe]})}function ql({sessionId:e,nonce:t,billingApiUrl:n,session:s,children:a}){return ee(wn,{children:ua.Children.map(a,i=>{if(!ua.isValidElement(i))return i;let u=i.props,l={};return u.sessionId||(l.sessionId=e),!u.nonce&&t&&(l.nonce=t),u.billingApiUrl||(l.billingApiUrl=n),s?.customer&&(u.email||(l.email=s.customer.email),u.userId||(l.userId=s.customer.id),u.firstName||(l.firstName=s.customer.firstName),u.lastName||(l.lastName=s.customer.lastName)),Object.keys(l).length===0?i:ua.cloneElement(i,l)})})}function jl({onButtonClick:e,showPayPal:t,showStripe:n=!0,showApplePay:s,showGooglePay:a,theme:i,buttonsTheme:u,buttonsStyles:l,cardButtonContent:v,cardBackButtonContent:N,cardTitleContent:h}){let[E,C]=bt(!1),F=pn(()=>Wi(i),[i]),c=pn(()=>{let g=F?.buttonsLayout??Ml(u);return l?{...g,...l,cardButton:{...g.cardButton,...l.cardButton},cardFormContainer:{...g.cardFormContainer,...l.cardFormContainer},backButton:{...g.backButton,...l.backButton},backButtonIcon:{...g.backButtonIcon,...l.backButtonIcon},submitButton:{...g.submitButton,...l.submitButton},title:{...g.title,...l.title}}:g},[F,u,l]),P=F?.buttonsLayout?.cardButton?.borderRadius??F?.appearance.variables?.borderRadius??8,k=g=>ee("div",{style:{height:g,borderRadius:P,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),T=v===void 0?{boxSizing:"border-box",height:br,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(E){let g=c.cardInputBorder??"#e5e7eb",me=c.cardInputBackground??"white",M=sr(N),le=sr(h);return _t("div",{style:{backgroundColor:c.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",...c.cardFormContainer},children:[_t("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[_t("button",{type:"button",onClick:()=>C(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:M?0:"0.5rem",background:"none",border:"none",color:"#4b5563",fontSize:"0.85rem",fontWeight:500,padding:0,flexShrink:0,opacity:1,cursor:"pointer",...c.backButton},children:[ee("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...c.backButtonIcon},children:ee("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:ee("path",{d:"M15 18l-6-6 6-6"})})}),ee(cr,{content:N})]}),le?ee("div",{style:{flex:1}}):ee("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...c.title},children:ee(Nr,{content:h})})]}),ee("div",{style:{backgroundColor:me,border:`1px solid ${g}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:ee("div",{style:{width:"60%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),_t("div",{style:{display:"flex"},children:[ee("div",{style:{flex:1,backgroundColor:me,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${g}`,borderLeft:`1px solid ${g}`,borderBottomLeftRadius:8,padding:12,height:45},children:ee("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),ee("div",{style:{flex:1,backgroundColor:me,borderTop:"none",borderRight:`1px solid ${g}`,borderBottom:`1px solid ${g}`,borderLeft:`1px solid ${g}`,borderBottomRightRadius:8,padding:12,height:45},children:ee("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),ee("div",{style:{backgroundColor:me,border:`1px solid ${g}`,borderRadius:8,marginTop:8,padding:12,height:45},children:ee("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),ee("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",...c.submitButton,opacity:.5}}),ee("style",{children:`
|
|
41
36
|
@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }
|
|
42
37
|
@keyframes flopay-interim-expand {
|
|
43
38
|
0% { opacity: 0; max-height: 0; transform: translateY(-12px); }
|
|
44
39
|
40% { opacity: 1; }
|
|
45
40
|
100% { opacity: 1; max-height: 600px; transform: translateY(0); }
|
|
46
41
|
}
|
|
47
|
-
`})]})}return _t("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&k(wr),n&&(a||r)&&k(wr),n&&re("button",{type:"button",onClick:()=>{e?.("card"),v(!0)},style:{width:"100%",...E,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:f=>{f.currentTarget.style.transform="scale(0.985)"},onMouseUp:f=>{f.currentTarget.style.transform="scale(1)"},children:re(dr,{content:b})}),re("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}import{dropThirdPartyOnlyError as _p}from"@flopay/shared";import{useEffect as tc,useRef as os,useContext as nc}from"react";import{jsx as ac}from"react/jsx-runtime";function as(e,t){function n({className:a,id:r,style:i,options:c,onChange:l,onReady:b,onFocus:x,onBlur:g,onEscape:w}){let v=os(null),R=os(null),{elements:d,reportInteractive:h}=nc(Mn);return tc(()=>{if(!d||!v.current)return;let k=!0;return(async()=>{let E=d.getElement(e);E||(E=await d.create(e,c)),!(!k||!v.current)&&(E.mount(v.current),R.current=E,l&&E.on("change",l),E.on("ready",()=>{h?.(),b?.()}),x&&E.on("focus",x),g&&E.on("blur",g),w&&E.on("escape",w))})(),()=>{if(k=!1,R.current){try{R.current.unmount()}catch{}R.current=null}}},[d,h]),ac("div",{ref:v,className:a,id:r,style:i})}return n.displayName=t,n}var rc=as("payment","PaymentElement"),oc=as("address","AddressElement");import{useEffect as Ma,useMemo as ic,useRef as hn,useState as eo}from"react";import{PaymentAPI as sc,PciVaultCardCapture as lc}from"@flopay/js";import{FloPayError as kr,isCardSetupCheckoutSession as cc,resolveBillingApiUrl as dc,resolveTheme as uc}from"@flopay/shared";import{Fragment as ss,jsx as Lo,jsxs as mc}from"react/jsx-runtime";var zo=class extends kr{constructor(t,n,a){super(t,n,a),this.name="FloPayCardSetupError",this.retryable=a.retryable}};function is(e,t={}){let n=e instanceof kr?e:void 0,a=n?.statusCode,r=t.retryable??(n?.type==="network_error"||n?.type==="rate_limit_error"||typeof a=="number"&&a>=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:r,...n?.param?{param:n.param}:{},...a!==void 0?{statusCode:a}:{}})}function pc({sessionId:e,nonce:t,billingApiUrl:n,telemetry:a,theme:r="modern-light",containerStyle:i,loading:c=null,onReady:l,onComplete:b,onDecline:x,onCancel:g,onValidation:w,onError:v}){let[R,d]=eo(null),[h,k]=eo(null),[E,f]=eo(null),[de,S]=eo(null),[le,Z]=eo(null),F=hn(!1),G=hn(!1),W=ic(()=>{if(typeof r=="object")return r;let Y=uc(r);if(Y)return ho({appearance:Y.appearance,buttonsStyles:Y.buttonsLayout,layout:"default"})},[r]),oe=hn(l),N=hn(v),j=hn(b),ce=hn(x),Re=hn(g),fe=hn(w),ae=hn(!1),ee=hn(!1),pe=hn(0);return oe.current=l,N.current=v,j.current=b,ce.current=x,Re.current=g,fe.current=w,Ma(()=>{let Y=pe.current+1;return pe.current=Y,()=>{queueMicrotask(()=>{pe.current===Y&&(ae.current||ee.current||(ee.current=!0,Ke(()=>{Re.current?.({status:"cancelled",sessionId:e})})))})}},[e]),Ma(()=>{let Y=!0,K=new sc(dc(n),{telemetry:a});return d(null),k(null),f(null),ae.current=!1,ee.current=!1,(async()=>{try{if(!e.trim())throw new kr("FloPayCardSetup requires a sessionId.","validation_error",{code:"MissingCheckoutSessionId",param:"sessionId"});if(!t.trim())throw new kr("FloPayCardSetup requires a session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let Ee=await K.getUnifiedCheckoutSession(e,t);if(!Y)return;let ge=Ee.data.session;if(!ge||!cc(ge))throw new kr("FloPayCardSetup only accepts a zero-amount, productless setup session.","validation_error",{code:"InvalidCardSetupSession",param:"sessionId"});let te=ge.vault;if(te?.html?.trim()||(te=await K.getVaultCapture(e,t)),!te.html?.trim())throw new kr("FloPay: this setup session has no vault card capability. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});if(!Y)return;k(te),d(new lc({sessionId:e,operation:"card_setup",telemetry:a}))}catch(Ee){if(!Y)return;let ge=is(Ee);ae.current=!0,f(ge),Ke(()=>N.current?.(ge))}})(),()=>{Y=!1,K.destroy()}},[n,t,e,a]),Ma(()=>{if(!R)return;let Y=!1;G.current=!1,F.current=!1;let K=R.on("submitting",()=>{F.current=!0,Z(null),S("processing")}),Ee=R.on("complete",te=>{ae.current=!0,F.current=!1,S("success"),(async()=>(await new Promise(q=>setTimeout(q,fn)),!G.current&&(G.current=!0,Ke(()=>{j.current?.({status:"succeeded",sessionId:e,...te.paymentMethod?{paymentMethod:te.paymentMethod}:{}})}),Y||S(null))))()}),ge=R.on("decline",te=>{ae.current=!0,F.current=!1,Z(te.message??null),S("error"),Ke(()=>{ce.current?.({status:"declined",sessionId:e,...te.declineReason?{reason:te.declineReason}:{},...te.message?{message:te.message}:{}})}),(async()=>(await new Promise(q=>setTimeout(q,Jt)),Y||S(null)))()});return()=>{Y=!0,K(),Ee(),ge()}},[R,e]),E?Lo("div",{role:"alert",children:E.message}):!R||!h?.html?Lo(ss,{children:c}):mc(ss,{children:[de&&Lo(cn,{status:de,errorMessage:le,processingLabel:"SAVING CARD...",successLabel:"CARD SAVED",errorLabel:"CARD NOT SAVED",successNote:null}),Lo(jr,{capture:R,html:h.html,messageToken:h.messageToken,expectedOrigin:h.expectedOrigin,theme:W,containerStyle:i,onReady:()=>{Ke(()=>oe.current?.())},onValidation:Y=>{Ke(()=>fe.current?.(Y))},onError:Y=>{if(!Y)return;F.current&&(F.current=!1,Z(Y),S("error"),setTimeout(()=>S(null),Jt));let K=is(new Error(Y),{code:"card_setup_widget_failed",retryable:!0});Ke(()=>N.current?.(K))}})]})}import{PaymentAPI as yc}from"@flopay/js";import{FloPayError as fc}from"@flopay/shared";import{useCallback as Aa,useEffect as gc,useRef as hc,useState as ls}from"react";import{Fragment as bc,jsx as Rr,jsxs as vc}from"react/jsx-runtime";function Pc({sessionId:e,nonce:t,billingApiUrl:n,email:a,userId:r,firstName:i,lastName:c,chv:l,onTokenizedBody:b,onComplete:x,onErrorChange:g,isProcessing:w=!1}){let v=wn(),R=na(),d=Po(),[h,k]=ls(!1),[E,f]=ls(!1),de=hc(!1),S=(n||d).replace(/\/+$/,""),le=Aa(async G=>{try{let oe=await new yc(S).processPayment(r??"",{sessionId:e,nonce:t,tokenizedData:G,accountData:{userId:r??"",email:a??"",firstName:i??"",lastName:c??""},chv:l});if(oe.ok){x?.();return}let N=await oe.json().catch(()=>null);g?.(N?.message??"Payment failed. Please try again.")}catch(W){g?.(W instanceof Error?W.message:"An unexpected error occurred")}},[S,e,t,r,a,i,c,l,x,g]),Z=Aa(G=>{b?b(G):le(G)},[b,le]);gc(()=>{if(!v||de.current)return;let G=new URLSearchParams(window.location.search),W=G.get("payment_intent"),oe=G.get("payment_intent_client_secret"),N=G.get("redirect_status");!W||!oe||(de.current=!0,(async()=>{try{if(f(!0),N==="failed"){g?.("PayPal payment was declined. Please try again.");return}let j=v.getRawProvider();if(!j?.retrievePaymentIntent){g?.("Cannot retrieve PayPal payment status.");return}let{paymentIntent:ce,error:Re}=await j.retrievePaymentIntent(oe);if(Re){g?.(Re.message??"Failed to retrieve PayPal payment status.");return}if(ce&&(ce.status==="requires_capture"||ce.status==="succeeded")){let fe=typeof ce.payment_method=="string"?ce.payment_method:ce.payment_method?.id;Z({id:fe??ce.id,type:"card",threeDSecureActionResultTokenId:ce.id,isPaypal:!0});let ae=new URL(window.location.href);ae.searchParams.delete("payment_intent"),ae.searchParams.delete("payment_intent_client_secret"),ae.searchParams.delete("redirect_status"),window.history.replaceState({},"",ae.toString())}else g?.("PayPal payment was not completed. Please try again.")}catch(j){g?.(j instanceof Error?j.message:"Failed to complete PayPal payment.")}finally{f(!1)}})())},[v,Z,g]);let F=Aa(async()=>{if(!(!v||!R))try{if(f(!0),g?.(null),!e||!a)throw new fc("Missing sessionId or email for PayPal payment","validation_error");let G=await v.confirmPayPalPayment({billingApiUrl:S,sessionId:e,nonce:t,email:a,returnUrl:window.location.href});if(G.error){g?.(G.error.message);return}G.paymentIntentId&&(G.status==="succeeded"||G.status==="processing"||G.status==="requires_capture")&&Z({id:G.paymentMethodId??G.paymentIntentId,type:"card",threeDSecureActionResultTokenId:G.paymentIntentId,isPaypal:!0})}catch(G){g?.(G instanceof Error?G.message:"PayPal payment failed. Please try again.")}finally{f(!1)}},[v,R,e,t,a,S,Z,g]);return!v||!R?Rr("div",{style:{height:45,background:"#f0f0f0",borderRadius:6,animation:"pulse 1.5s infinite"}}):vc(bc,{children:[!h&&Rr("div",{style:{height:45,background:"#f0f0f0",borderRadius:6}}),Rr("div",{style:h?{}:{display:"none"},children:Rr("button",{type:"button",onClick:F,disabled:E||w,style:{width:"100%",height:45,backgroundColor:"#ffc439",color:"#003087",border:"none",borderRadius:6,fontSize:"1rem",fontWeight:700,cursor:E||w?"not-allowed":"pointer",opacity:E||w?.6:1},ref:()=>k(!0),children:E?"Processing...":"PayPal"})}),(E||w)&&Rr("div",{style:{position:"fixed",inset:0,background:"rgba(0,0,0,0.4)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3},children:Rr("div",{style:{background:"white",borderRadius:8,padding:"1.5rem",textAlign:"center",boxShadow:"0 4px 24px rgba(0,0,0,0.15)",width:280},children:"Processing PayPal payment..."})})]})}import{useCallback as jn,useEffect as Er,useMemo as to,useRef as Ir,useState as no}from"react";import{PaymentAPI as Ba}from"@flopay/js";import{FloPayError as xr,resolveBillingApiUrl as Cc,resolveButtonsLayoutTheme as Sc,resolveTheme as wc}from"@flopay/shared";import{Fragment as xc,jsx as _r,jsxs as Tc}from"react/jsx-runtime";var kc=44;function cs(e){return new Promise(t=>setTimeout(t,e))}function Rc(e,t){return e instanceof xr?e:new xr(e instanceof Error?e.message:t,"api_error")}function Ec(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function Ic(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 _c({sessionId:e,nonce:t,createSession:n,paymentMethodId:a,checkoutMethod:r,clientId:i,products:c,items:l,subscriptions:b,account:x,successUrl:g,cancelUrl:w,couponCodes:v,tagsData:R,utmMetadata:d,billingApiUrl:h,locale:k,theme:E,appearance:f,buttonsTheme:de,buttonsStyles:S,onSuccess:le,onError:Z,onDecline:F,children:G,disabled:W=!1,type:oe="button",style:N,...j}){let ce=to(()=>Cc(h),[h]),Re=to(()=>Ic({createSession:n,clientId:i,products:c,items:l,subscriptions:b,account:x,successUrl:g,cancelUrl:w,couponCodes:v,tagsData:R,utmMetadata:d}),[x,w,i,v,n,c,l,b,g,R,d]),[fe,ae]=no(!1),[ee,pe]=no(null),[Y,K]=no(null),[Ee,ge]=no(!1),[te,q]=no(null),C=Ir(!0),ie=Ir(null),$e=Ir(te),Oe=Ir(le),me=Ir(Z),T=Ir(F);Er(()=>{$e.current=te},[te]),Er(()=>{Oe.current=le},[le]),Er(()=>{me.current=Z},[Z]),Er(()=>{T.current=F},[F]),Er(()=>(C.current=!0,()=>{C.current=!1,ie.current?.abort()}),[]),Er(()=>{if(typeof window>"u")return;let I=be=>{be.key==="Escape"&&q(null)};return window.addEventListener("keydown",I),()=>{window.removeEventListener("keydown",I)}},[]);let ue=jn((I,be=Xr)=>{T.current?.(Et(be,I,{code:I.code,declineCode:I.declineCode}))},[]),J=jn(async I=>{C.current&&(K(null),ge(I.result.status==="authorized"),pe("success"),await cs(fn),C.current&&Oe.current?.(I))},[]),_e=jn(async(I,be)=>{C.current&&(me.current?.(I),be?.emitDecline&&ue(I,be.method),K(I.message),ge(!1),pe("error"),await cs(Jt))},[ue]),mt=jn(async(I,be,Ye)=>{let xe=I.data.session??null;if(!xe)throw new xr("No session data returned","api_error");let St=xe.clientSecret||t;if(gr(xe)){await J({result:er(xe,be),session:xe,sessionId:xe.id||be,autoCompleted:!1});return}if(xe.status==="expired")throw bo(xe);try{if(I.autoProcessingPending){let Xe=(await new Ba(ce).waitForCheckoutSessionCompletion(I.autoProcessingPending.sessionId,{initialDelayMs:I.autoProcessingPending.retryAfterMs})).data.session;if(!gr(Xe))throw vo(Xe);await J({result:er(Xe,be),session:Xe,sessionId:Xe.id||be,autoCompleted:!1});return}if(I.autoProcessingError){if(I.autoProcessingError.type==="3ds_required"&&I.autoProcessingError.nextActionRedirectUrl&&be&&St){let Ve=new AbortController;ie.current=Ve;let nt;try{nt=await Wi({billingApiUrl:ce,sessionId:be,nonce:St,nextActionRedirectUrl:I.autoProcessingError.nextActionRedirectUrl,signal:Ve.signal})}finally{ie.current===Ve&&(ie.current=null)}if(nt.status==="declined")throw Vn({type:nt.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:nt.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:I.autoProcessingError.checkoutMethod});let at=(await new Ba(ce).waitForCheckoutSessionCompletion(be,{initialDelayMs:0,nonce:St})).data.session;if(!gr(at))throw Vn({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:I.autoProcessingError.checkoutMethod});await J({result:er(at,be),session:at,sessionId:at.id||be,autoCompleted:!1});return}throw Vn(I.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:I.autoProcessingError.checkoutMethod})}if(Ye?.fromCreateSession&&I.autoProcessingAttempted===!0)throw Vn({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let je=await Sr({billingApiUrl:ce,sessionId:be??xe.id,session:xe,nonce:St});if(je.type!=="success")throw Vn({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await J({result:je.result,session:xe,sessionId:xe.id||be,autoCompleted:!1})}catch(je){let Ve=or(je),nt=xe.id||be;await _e(Ve,{emitDecline:!0,method:Ve.checkoutMethod??Xr}),Ec(Ve,nt)&&nt&&C.current&&q({sessionId:nt,errorMessage:Ve.message,nonce:St||void 0})}},[t,ce,_e,J]),Je=jn(async I=>{if(j.onClick?.(I),!(I.defaultPrevented||W||fe)){if(q(null),e&&Re){let be=new xr("Provide either sessionId or create-session props, not both.","validation_error");await _e(be),C.current&&(pe(null),K(null));return}if(!e&&!Re){let be=new xr("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await _e(be),C.current&&(pe(null),K(null));return}ae(!0),K(null),ge(!1),pe("processing");try{let be=new Ba(ce);if(e){let Ye=await be.getUnifiedCheckoutSession(e,t);await mt(Ye,e);return}try{let Ye=await be.createAndFetchSession({...Re});await mt(Ye,Ye.data.session?.id??null,{fromCreateSession:!0})}catch(Ye){if(Ye instanceof xr&&Ye.code==="session_auto_completed"){await J({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw Ye}}catch(be){await _e(Rc(be,"Automatic payment failed. Please try again."))}finally{C.current&&(pe(null),K(null),ae(!1))}}},[j,Re,W,fe,t,mt,ce,e,_e,J]),yt=jn(I=>{let be=$e.current;q(null),Oe.current?.({result:I,session:null,sessionId:be?.sessionId??null,autoCompleted:!1})},[]),A=jn(I=>{me.current?.(I)},[]),X=jn(I=>{T.current?.(I)},[]),tt=to(()=>wc(E),[E]),qe=to(()=>{let I=tt?.buttonsLayout??Sc(de);return S?{...I,...S,cardButton:{...I.cardButton,...S.cardButton}}:I},[tt,de,S]),ft=to(()=>{let I=tt?.appearance;return f?I?{...I,...f,variables:{...I.variables,...f.variables}}:f:I},[f,tt]),Ne=ft?.variables,We=Ne?.colorPrimary??"#4A49FF",Xt=Ne?.colorPrimaryHover??mr(We,.12),Ge=Ne?.borderRadius??"8px";return Tc(xc,{children:[_r("button",{...j,type:oe,onClick:Je,disabled:W||fe,"aria-busy":fe,style:{width:"100%",...G===void 0?{boxSizing:"border-box",height:kc,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...qe.cardButton,...ha({themeBundle:tt,resolvedPrimaryColor:We,resolvedBorderRadius:Ge,submitButtonStyle:qe.submitButton,explicitPrimaryColor:Ne?.colorPrimary}),fontSize:qe.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:W||fe?"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:W||fe?.6:1,...N},onMouseEnter:I=>{j.onMouseEnter?.(I),!I.defaultPrevented&&!W&&!fe&&(tt||Ne?.colorPrimary)&&(I.currentTarget.style.backgroundColor=Xt)},onMouseLeave:I=>{j.onMouseLeave?.(I),!I.defaultPrevented&&(tt||Ne?.colorPrimary)&&(I.currentTarget.style.backgroundColor=We)},onMouseDown:I=>{j.onMouseDown?.(I),I.defaultPrevented||(I.currentTarget.style.transform="scale(0.985)")},onMouseUp:I=>{j.onMouseUp?.(I),I.defaultPrevented||(I.currentTarget.style.transform="scale(1)")},children:_r(dr,{content:G})}),ee&&_r(cn,{status:ee,errorMessage:Y,authorized:Ee}),te&&_r("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:I=>{I.target===I.currentTarget&&q(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:_r("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:_r(Ta,{sessionId:te.sessionId,nonce:te.nonce,checkoutMode:"full",billingApiUrl:ce,locale:k,theme:E,...ft?{appearance:ft}:{},buttonsTheme:de,buttonsStyles:S,initialErrorMessage:te.errorMessage,cardTitleContent:null,onComplete:yt,onError:A,onDecline:X})})})]})}export{oc as AddressElement,Ro as DirectPayPalButton,_c as FloPayAutomaticPaymentButton,pc as FloPayCardSetup,zo as FloPayCardSetupError,Ta as FloPayCheckout,go as FloPayProvider,Pc as PayPalButton,rc as PaymentElement,Pa as SplitCardForm,jr as VaultCardFields,_p as dropThirdPartyOnlyError,qs as useCheckout,na as useElements,wn as useFloPay,ta as usePayPalFloPay};
|
|
42
|
+
`})]})}return _t("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&k(br),n&&(s||a)&&k(br),n&&ee("button",{type:"button",onClick:()=>{e?.("card"),C(!0)},style:{width:"100%",...T,backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:"8px",fontSize:c.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,...c.cardButton},onMouseDown:g=>{g.currentTarget.style.transform="scale(0.985)"},onMouseUp:g=>{g.currentTarget.style.transform="scale(1)"},children:ee(lr,{content:v})}),ee("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}import{dropThirdPartyOnlyError as Nu}from"@flopay/shared";import{useEffect as Kl,useRef as Yi,useContext as Vl}from"react";import{jsx as Yl}from"react/jsx-runtime";function Gi(e,t){function n({className:s,id:a,style:i,options:u,onChange:l,onReady:v,onFocus:N,onBlur:h,onEscape:E}){let C=Yi(null),F=Yi(null),{elements:c,reportInteractive:P}=Vl(xn);return Kl(()=>{if(!c||!C.current)return;let k=!0;return(async()=>{let T=c.getElement(e);T||(T=await c.create(e,u)),!(!k||!C.current)&&(T.mount(C.current),F.current=T,l&&T.on("change",l),T.on("ready",()=>{P?.(),v?.()}),N&&T.on("focus",N),h&&T.on("blur",h),E&&T.on("escape",E))})(),()=>{if(k=!1,F.current){try{F.current.unmount()}catch{}F.current=null}}},[c,P]),Yl("div",{ref:C,className:s,id:a,style:i})}return n.displayName=t,n}var Hl=Gi("payment","PaymentElement"),Wl=Gi("address","AddressElement");import{PaymentAPI as Gl}from"@flopay/js";import{FloPayError as Jl}from"@flopay/shared";import{useCallback as Ca,useEffect as Xl,useRef as Ql,useState as Ji}from"react";import{Fragment as ec,jsx as vr,jsxs as tc}from"react/jsx-runtime";function Zl({sessionId:e,nonce:t,billingApiUrl:n,email:s,userId:a,firstName:i,lastName:u,chv:l,onTokenizedBody:v,onComplete:N,onErrorChange:h,isProcessing:E=!1}){let C=vn(),F=Ho(),c=co(),[P,k]=Ji(!1),[T,g]=Ji(!1),me=Ql(!1),M=(n||c).replace(/\/+$/,""),le=Ca(async J=>{try{let oe=await new Gl(M).processPayment(a??"",{sessionId:e,nonce:t,tokenizedData:J,accountData:{userId:a??"",email:s??"",firstName:i??"",lastName:u??""},chv:l});if(oe.ok){N?.();return}let j=await oe.json().catch(()=>null);h?.(j?.message??"Payment failed. Please try again.")}catch(H){h?.(H instanceof Error?H.message:"An unexpected error occurred")}},[M,e,t,a,s,i,u,l,N,h]),ce=Ca(J=>{v?v(J):le(J)},[v,le]);Xl(()=>{if(!C||me.current)return;let J=new URLSearchParams(window.location.search),H=J.get("payment_intent"),oe=J.get("payment_intent_client_secret"),j=J.get("redirect_status");!H||!oe||(me.current=!0,(async()=>{try{if(g(!0),j==="failed"){h?.("PayPal payment was declined. Please try again.");return}let K=C.getRawProvider();if(!K?.retrievePaymentIntent){h?.("Cannot retrieve PayPal payment status.");return}let{paymentIntent:ie,error:xe}=await K.retrievePaymentIntent(oe);if(xe){h?.(xe.message??"Failed to retrieve PayPal payment status.");return}if(ie&&(ie.status==="requires_capture"||ie.status==="succeeded")){let he=typeof ie.payment_method=="string"?ie.payment_method:ie.payment_method?.id;ce({id:he??ie.id,type:"card",threeDSecureActionResultTokenId:ie.id,isPaypal:!0});let de=new URL(window.location.href);de.searchParams.delete("payment_intent"),de.searchParams.delete("payment_intent_client_secret"),de.searchParams.delete("redirect_status"),window.history.replaceState({},"",de.toString())}else h?.("PayPal payment was not completed. Please try again.")}catch(K){h?.(K instanceof Error?K.message:"Failed to complete PayPal payment.")}finally{g(!1)}})())},[C,ce,h]);let z=Ca(async()=>{if(!(!C||!F))try{if(g(!0),h?.(null),!e||!s)throw new Jl("Missing sessionId or email for PayPal payment","validation_error");let J=await C.confirmPayPalPayment({billingApiUrl:M,sessionId:e,nonce:t,email:s,returnUrl:window.location.href});if(J.error){h?.(J.error.message);return}J.paymentIntentId&&(J.status==="succeeded"||J.status==="processing"||J.status==="requires_capture")&&ce({id:J.paymentMethodId??J.paymentIntentId,type:"card",threeDSecureActionResultTokenId:J.paymentIntentId,isPaypal:!0})}catch(J){h?.(J instanceof Error?J.message:"PayPal payment failed. Please try again.")}finally{g(!1)}},[C,F,e,t,s,M,ce,h]);return!C||!F?vr("div",{style:{height:45,background:"#f0f0f0",borderRadius:6,animation:"pulse 1.5s infinite"}}):tc(ec,{children:[!P&&vr("div",{style:{height:45,background:"#f0f0f0",borderRadius:6}}),vr("div",{style:P?{}:{display:"none"},children:vr("button",{type:"button",onClick:z,disabled:T||E,style:{width:"100%",height:45,backgroundColor:"#ffc439",color:"#003087",border:"none",borderRadius:6,fontSize:"1rem",fontWeight:700,cursor:T||E?"not-allowed":"pointer",opacity:T||E?.6:1},ref:()=>k(!0),children:T?"Processing...":"PayPal"})}),(T||E)&&vr("div",{style:{position:"fixed",inset:0,background:"rgba(0,0,0,0.4)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3},children:vr("div",{style:{background:"white",borderRadius:8,padding:"1.5rem",textAlign:"center",boxShadow:"0 4px 24px rgba(0,0,0,0.15)",width:280},children:"Processing PayPal payment..."})})]})}import{useCallback as qn,useEffect as Cr,useMemo as Yr,useRef as Sr,useState as Gr}from"react";import{PaymentAPI as Sa}from"@flopay/js";import{FloPayError as kr,resolveBillingApiUrl as nc,resolveButtonsLayoutTheme as rc,resolveTheme as oc}from"@flopay/shared";import{Fragment as dc,jsx as wr,jsxs as uc}from"react/jsx-runtime";var ac=44;function Xi(e){return new Promise(t=>setTimeout(t,e))}function ic(e,t){return e instanceof kr?e:new kr(e instanceof Error?e.message:t,"api_error")}function sc(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function lc(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 cc({sessionId:e,nonce:t,createSession:n,paymentMethodId:s,checkoutMethod:a,clientId:i,products:u,items:l,subscriptions:v,account:N,successUrl:h,cancelUrl:E,couponCodes:C,tagsData:F,utmMetadata:c,billingApiUrl:P,locale:k,theme:T,appearance:g,buttonsTheme:me,buttonsStyles:M,onSuccess:le,onError:ce,onDecline:z,children:J,disabled:H=!1,type:oe="button",style:j,...K}){let ie=Yr(()=>nc(P),[P]),xe=Yr(()=>lc({createSession:n,clientId:i,products:u,items:l,subscriptions:v,account:N,successUrl:h,cancelUrl:E,couponCodes:C,tagsData:F,utmMetadata:c}),[N,E,i,C,n,u,l,v,h,F,c]),[he,de]=Gr(!1),[Q,ye]=Gr(null),[Te,Z]=Gr(null),[Ue,Fe]=Gr(!1),[we,V]=Gr(null),b=Sr(!0),te=Sr(null),$e=Sr(we),ze=Sr(le),ae=Sr(ce),R=Sr(z);Cr(()=>{$e.current=we},[we]),Cr(()=>{ze.current=le},[le]),Cr(()=>{ae.current=ce},[ce]),Cr(()=>{R.current=z},[z]),Cr(()=>(b.current=!0,()=>{b.current=!1,te.current?.abort()}),[]),Cr(()=>{if(typeof window>"u")return;let S=fe=>{fe.key==="Escape"&&V(null)};return window.addEventListener("keydown",S),()=>{window.removeEventListener("keydown",S)}},[]);let re=qn((S,fe=Vr)=>{R.current?.(It(fe,S,{code:S.code,declineCode:S.declineCode}))},[]),W=qn(async S=>{b.current&&(Z(null),Fe(S.result.status==="authorized"),ye("success"),await Xi(_n),b.current&&ze.current?.(S))},[]),ke=qn(async(S,fe)=>{b.current&&(ae.current?.(S),fe?.emitDecline&&re(S,fe.method),Z(S.message),Fe(!1),ye("error"),await Xi(Pn))},[re]),dt=qn(async(S,fe,We)=>{let Re=S.data.session??null;if(!Re)throw new kr("No session data returned","api_error");let vt=Re.clientSecret||t;if(pr(Re)){await W({result:Qn(Re,fe),session:Re,sessionId:Re.id||fe,autoCompleted:!1});return}if(Re.status==="expired")throw uo(Re);try{if(S.autoProcessingPending){let Je=(await new Sa(ie).waitForCheckoutSessionCompletion(S.autoProcessingPending.sessionId,{initialDelayMs:S.autoProcessingPending.retryAfterMs})).data.session;if(!pr(Je))throw po(Je);await W({result:Qn(Je,fe),session:Je,sessionId:Je.id||fe,autoCompleted:!1});return}if(S.autoProcessingError){if(S.autoProcessingError.type==="3ds_required"&&S.autoProcessingError.nextActionRedirectUrl&&fe&&vt){let je=new AbortController;te.current=je;let tt;try{tt=await zi({billingApiUrl:ie,sessionId:fe,nonce:vt,nextActionRedirectUrl:S.autoProcessingError.nextActionRedirectUrl,signal:je.signal})}finally{te.current===je&&(te.current=null)}if(tt.status==="declined")throw $n({type:tt.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:tt.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:S.autoProcessingError.checkoutMethod});let ot=(await new Sa(ie).waitForCheckoutSessionCompletion(fe,{initialDelayMs:0,nonce:vt})).data.session;if(!pr(ot))throw $n({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:S.autoProcessingError.checkoutMethod});await W({result:Qn(ot,fe),session:ot,sessionId:ot.id||fe,autoCompleted:!1});return}throw $n(S.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:S.autoProcessingError.checkoutMethod})}if(We?.fromCreateSession&&S.autoProcessingAttempted===!0)throw $n({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let Ke=await Pr({billingApiUrl:ie,sessionId:fe??Re.id,session:Re,nonce:vt});if(Ke.type!=="success")throw $n({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await W({result:Ke.result,session:Re,sessionId:Re.id||fe,autoCompleted:!1})}catch(Ke){let je=nr(Ke),tt=Re.id||fe;await ke(je,{emitDecline:!0,method:je.checkoutMethod??Vr}),sc(je,tt)&&tt&&b.current&&V({sessionId:tt,errorMessage:je.message,nonce:vt||void 0})}},[t,ie,ke,W]),Ge=qn(async S=>{if(K.onClick?.(S),!(S.defaultPrevented||H||he)){if(V(null),e&&xe){let fe=new kr("Provide either sessionId or create-session props, not both.","validation_error");await ke(fe),b.current&&(ye(null),Z(null));return}if(!e&&!xe){let fe=new kr("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await ke(fe),b.current&&(ye(null),Z(null));return}de(!0),Z(null),Fe(!1),ye("processing");try{let fe=new Sa(ie);if(e){let We=await fe.getUnifiedCheckoutSession(e,t);await dt(We,e);return}try{let We=await fe.createAndFetchSession({...xe});await dt(We,We.data.session?.id??null,{fromCreateSession:!0})}catch(We){if(We instanceof kr&&We.code==="session_auto_completed"){await W({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw We}}catch(fe){await ke(ic(fe,"Automatic payment failed. Please try again."))}finally{b.current&&(ye(null),Z(null),de(!1))}}},[K,xe,H,he,t,dt,ie,e,ke,W]),pt=qn(S=>{let fe=$e.current;V(null),ze.current?.({result:S,session:null,sessionId:fe?.sessionId??null,autoCompleted:!1})},[]),_=qn(S=>{ae.current?.(S)},[]),Y=qn(S=>{R.current?.(S)},[]),et=Yr(()=>oc(T),[T]),qe=Yr(()=>{let S=et?.buttonsLayout??rc(me);return M?{...S,...M,cardButton:{...S.cardButton,...M.cardButton}}:S},[et,me,M]),mt=Yr(()=>{let S=et?.appearance;return g?S?{...S,...g,variables:{...S.variables,...g.variables}}:g:S},[g,et]),Ne=mt?.variables,He=Ne?.colorPrimary??"#4A49FF",Jt=Ne?.colorPrimaryHover??Lr(He,.12),Ye=Ne?.borderRadius??"8px";return uc(dc,{children:[wr("button",{...K,type:oe,onClick:Ge,disabled:H||he,"aria-busy":he,style:{width:"100%",...J===void 0?{boxSizing:"border-box",height:ac,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...qe.cardButton,...sa({themeBundle:et,resolvedPrimaryColor:He,resolvedBorderRadius:Ye,submitButtonStyle:qe.submitButton,explicitPrimaryColor:Ne?.colorPrimary}),fontSize:qe.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:H||he?"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:H||he?.6:1,...j},onMouseEnter:S=>{K.onMouseEnter?.(S),!S.defaultPrevented&&!H&&!he&&(et||Ne?.colorPrimary)&&(S.currentTarget.style.backgroundColor=Jt)},onMouseLeave:S=>{K.onMouseLeave?.(S),!S.defaultPrevented&&(et||Ne?.colorPrimary)&&(S.currentTarget.style.backgroundColor=He)},onMouseDown:S=>{K.onMouseDown?.(S),S.defaultPrevented||(S.currentTarget.style.transform="scale(0.985)")},onMouseUp:S=>{K.onMouseUp?.(S),S.defaultPrevented||(S.currentTarget.style.transform="scale(1)")},children:wr(lr,{content:J})}),Q&&wr(bn,{status:Q,errorMessage:Te,authorized:Ue}),we&&wr("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:S=>{S.target===S.currentTarget&&V(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:wr("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:wr(va,{sessionId:we.sessionId,nonce:we.nonce,checkoutMode:"full",billingApiUrl:ie,locale:k,theme:T,...mt?{appearance:mt}:{},buttonsTheme:me,buttonsStyles:M,initialErrorMessage:we.errorMessage,cardTitleContent:null,onComplete:pt,onError:_,onDecline:Y})})})]})}export{Wl as AddressElement,ho as DirectPayPalButton,cc as FloPayAutomaticPaymentButton,hs as FloPayCardSetup,gs as FloPayCardSetupError,va as FloPayCheckout,lo as FloPayProvider,Zl as PayPalButton,Hl as PaymentElement,la as SplitCardForm,qo as VaultCardFields,Nu as dropThirdPartyOnlyError,Ms as useCheckout,Ho as useElements,vn as useFloPay,Vo as usePayPalFloPay};
|