@flopay/react 1.8.10 → 1.8.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +7 -7
- package/dist/index.mjs +6 -6
- package/package.json +3 -3
package/dist/index.cjs
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
"use strict";var Ks=Object.create;var $o=Object.defineProperty;var Hs=Object.getOwnPropertyDescriptor;var Ys=Object.getOwnPropertyNames;var Ws=Object.getPrototypeOf,Gs=Object.prototype.hasOwnProperty;var Js=(e,t)=>{for(var n in t)$o(e,n,{get:t[n],enumerable:!0})},Ai=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Ys(t))!Gs.call(e,o)&&o!==n&&$o(e,o,{get:()=>t[o],enumerable:!(r=Hs(t,o))||r.enumerable});return e};var Bi=(e,t,n)=>(n=e!=null?Ks(Ws(e)):{},Ai(t||!e||!e.__esModule?$o(n,"default",{value:e,enumerable:!0}):n,e)),Xs=e=>Ai($o({},"__esModule",{value:!0}),e);var Gl={};Js(Gl,{DirectPayPalButton:()=>bo,FloPayAutomaticPaymentButton:()=>ws,FloPayCardSetup:()=>Is,FloPayCardSetupError:()=>_o,FloPayCheckout:()=>da,FloPayProvider:()=>Po,SplitCardForm:()=>ia,VaultCardFields:()=>Xr,dropThirdPartyOnlyError:()=>Rs.dropThirdPartyOnlyError,useCheckout:()=>qi,useFloPay:()=>sr,usePayPalFloPay:()=>Ho});module.exports=Xs(Gl);var Rs=require("@flopay/shared");var ua=require("@flopay/js"),bn=require("@flopay/shared"),qe=require("react");var St=require("react/jsx-runtime");function Zs(){return(0,St.jsxs)(St.Fragment,{children:[(0,St.jsxs)("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,St.jsx)("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),(0,St.jsx)("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",(0,St.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"#9ca3af",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{position:"absolute",right:"1rem"},"aria-hidden":"true",children:(0,St.jsx)("path",{d:"M9 18l6-6-6-6"})})]})}function Qs(){return(0,St.jsx)(St.Fragment,{children:"Go back"})}function el(){return(0,St.jsx)(St.Fragment,{children:"Secure card checkout"})}function Or(e){return e!==void 0&&(e===""||e===null||e===!1)}function zr({content:e}){return(0,St.jsx)(St.Fragment,{children:e===void 0?(0,St.jsx)(Zs,{}):e})}function Ur({content:e}){return(0,St.jsx)(St.Fragment,{children:e===void 0?(0,St.jsx)(Qs,{}):e})}function mo({content:e}){return(0,St.jsx)(St.Fragment,{children:e===void 0?(0,St.jsx)(el,{}):e})}var or=require("@flopay/shared");function qr(e,t,n,r={}){let o;return(i={})=>{if(o)return o;let d={...r,...i,email:i.email?.trim()||r.email?.trim()};if(!(0,or.isValidEmail)(d.email))return Promise.reject(new or.FloPayError("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}));let c={};for(let[P,y]of Object.entries(d)){if(typeof y!="string")continue;let h=y.trim();h&&(c[P]=h)}return o=e.claimCheckoutSession(t,n,{accountData:c}),o.catch(()=>{}),o}}function Fi(e,t){return t?e?{account:{...e.account??{},...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,..."checkoutMetadata"in t?{checkoutMetadata:t.checkoutMetadata}:"checkoutMetadata"in e?{checkoutMetadata:e.checkoutMetadata}:{},tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}:t:e}function _a(e,t){return t?{...e,account:{...e.account,...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,..."checkoutMetadata"in t?{checkoutMetadata:t.checkoutMetadata}:{},tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}:e}function Di(e,t){let n=e.products??[...(e.subscriptions??[]).map(i=>({type:"subscription",code:i.code??i.providerPlanId,name:i.subscriptionName??i.providerPlanName??i.code??i.providerPlanId??null,quantity:i.quantity??1,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount,currency:i.currency,metadata:i.metadata})),...(e.items??[]).map(i=>({type:"item",code:i.code??i.providerItemId,name:i.itemName??i.providerItemName??i.code??i.providerItemId??null,quantity:i.quantity??1,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount,currency:i.currency,metadata:i.metadata}))],r=n.reduce((i,d)=>i+(d.overrideAmount??d.totalAmount??0),0),o=e.currency??n.find(i=>i.currency)?.currency??"USD";return{id:"",clientSecret:"",mode:n.some(i=>i.type==="subscription")?"subscription":"payment",amount:Math.round(r*100),currency:o,status:"open",captureMethod:e.captureMethod,customer:{id:e.account.userId,email:e.account.email??"",firstName:e.account.firstName,lastName:e.account.lastName,gender:e.account.gender??void 0,city:e.account.city??void 0,state:e.account.state??void 0,country:e.account.country??void 0,zip:e.account.zip??void 0},successUrl:e.successUrl,cancelUrl:e.cancelUrl,checkoutMode:t??e.checkoutMode??"full",products:n.map((i,d)=>({uuid:`synthetic-${i.type??"item"}-${d}`,checkoutSessionId:"",type:i.type??"item",code:i.code,name:i.name??null,quantity:i.quantity??1,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount??null,currency:i.currency??o,metadata:i.metadata??null}))}}function Rr(e){let t=e?.trim().split(/\s+/).filter(Boolean)??[];return t.length===0?{}:{firstName:t[0],lastName:t.length>1?t.slice(1).join(" "):void 0}}function xa(e,t){return t?{...e,...t}:e}function jt(e,t,n){let r=typeof t=="string"?t:t.message,o=typeof t=="string"?n?.code:n?.code??t.code,i=typeof t=="string"?n?.declineCode:n?.declineCode??t.declineCode;return{method:e,message:r,...o?{code:o}:{},...i?{declineCode:i}:{}}}var tl=[{match:/^paypal authorization required\.?$/i,replacement:"For your additional security, please re-authenticate this payment via PayPal."}];function br(e){if(typeof e!="string")return e??void 0;let t=e.trim();if(!t)return e;for(let{match:n,replacement:r}of tl)if(n.test(t))return r;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 $r(e){return e?.status==="authorized"||e?.status==="complete"}function Li(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function jo(e){let t=Li(e);return new or.FloPayError(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function Vo(e){let t=Li(e);return new or.FloPayError(t?"Authorization has expired.":"Automatic payment failed. Please try again.","api_error",{code:t?"authorization_expired":e?.status==="expired"?"checkout_session_expired":"checkout_processing_timeout"})}function Ko(e,t){return e==="processing"||(0,or.isMoneySettledOutcome)(e,t)}function Ni(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}function Oi(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?{mode:"setup"}:{mode:"payment",amount:e}}function yo(e){let t=[e?.id,e?.originalPaymentMethodId];for(let n of t)if(typeof n=="string"&&n.startsWith("pm_"))return n}var Mr=require("@flopay/js"),be=require("@flopay/shared"),k=Bi(require("react"),1);var Ta=require("react"),_n=(0,Ta.createContext)({flopay:null,paypalFlopay:null,billingApiUrl:""}),Kn=(0,Ta.createContext)({session:null,loading:!1,error:null});var Go=require("@flopay/js"),xt=require("@flopay/shared"),Hi=require("@paypal/paypal-js"),_=require("react");var zi=require("@flopay/shared"),Hn=require("react"),ar=require("react/jsx-runtime");function pn(e){let{firstName:t,lastName:n,...r}=e,o=t?.trim(),i=n?.trim();return{...r,...o?{firstName:o}:{},...i?{lastName:i}:{}}}function jr(){let[e,t]=(0,Hn.useState)(null),n=(0,Hn.useRef)(null),r=(0,Hn.useRef)(0),o=(0,Hn.useCallback)((d,c)=>(n.current?.(null),r.current+=1,t({id:r.current,methodLabel:d,identity:c}),new Promise(P=>{n.current=P})),[]),i=(0,Hn.useCallback)(d=>{let c=n.current;n.current=null,t(null),c?.(d)},[]);return(0,Hn.useEffect)(()=>()=>{n.current?.(null),n.current=null},[]),{request:e,collect:o,finish:i}}function Vr({identity:e,methodLabel:t,onComplete:n,onCancel:r,submitting:o=!1,testId:i="flopay-buyer-identity-pane"}){let[d,c]=(0,Hn.useState)(e.email?.trim()??""),P=(0,zi.isValidEmail)(d.trim());return(0,ar.jsxs)("div",{"data-testid":i,style:{display:"flex",flexDirection:"column",gap:"0.75rem",padding:"0.875rem",border:"1px solid #d1d5db",borderRadius:8,background:"#fff",color:"#262833"},children:[(0,ar.jsxs)("div",{style:{fontWeight:700},children:["Continue with ",t]}),(0,ar.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",(0,ar.jsx)("input",{type:"email",autoComplete:"email","data-testid":"flopay-email",required:!0,value:d,onChange:y=>c(y.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]}),(0,ar.jsxs)("div",{style:{display:"flex",gap:"0.5rem"},children:[r&&(0,ar.jsx)("button",{type:"button",onClick:r,style:{flex:1,minHeight:42},children:"Cancel"}),(0,ar.jsxs)("button",{type:"button",disabled:!P||o,onClick:()=>{n(pn({...e,email:d.trim()}))},style:{flex:2,minHeight:42},children:["Continue with ",t]})]})]})}function nl(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 _r(e){if(typeof e!="string")return;let t=e.trim();return/^[a-z0-9_.-]{1,64}$/i.test(t)?t:void 0}function ir(e){if(typeof e!="object"||e===null)return;let t=e;return _r(t.code)??_r(t.type)??_r(t.name)}function Kr(e){if(!(typeof e!="object"||e===null))return _r(e.decline_code)}function fo(e){return typeof e!="object"||e===null?!1:_r(e.type)?.toLowerCase()==="card_error"||Kr(e)!==void 0}function vr(e){let t=nl(e)?.toLowerCase()??"",r=`${ir(e)?.toLowerCase()??""} ${t}`;return r.includes("popup")&&r.includes("block")}var Ui=require("@flopay/shared"),go=require("react");function sr(){return(0,go.useContext)(_n).flopay}function Ho(){return(0,go.useContext)(_n).paypalFlopay??null}function qi(){return(0,go.useContext)(Kn)}function $i(){return(0,go.useContext)(_n).billingApiUrl||(0,Ui.resolveBillingApiUrl)()}var ji=require("@flopay/shared"),xr=require("react");function et(e){if(!e)return;let t=n=>{console.error("[FloPay] Merchant callback failed; checkout continued.",n)};try{Promise.resolve(e()).catch(t)}catch(n){t(n)}}var Yo=require("react"),ho=typeof window>"u"?Yo.useEffect:Yo.useLayoutEffect;var rl={"checkout.mount":"checkout_mount","sdk.initialize.ready":"sdk_loaded","provider.ready":"sdk_loaded","checkout.rendered":"form_rendered","vault.widget.ready":"form_rendered","vault.submission.started":"tokenize","payment.tokenization.started":"tokenize","payment.processing.started":"process_attempt","payment.intent.started":"process_attempt","vault.action.required":"3ds_challenge","payment.three_ds.handoff":"3ds_challenge"};function ol(e){return e==="stripe"||e==="paypal"?e:void 0}function al(e){let t=ol(e.provider),n={schemaVersion:ji.FLO_INSTRUMENT_SCHEMA_VERSION,...t?{gateway:t}:{}};if(e.class==="lifecycle"){let r=rl[e.name];return r?{...n,name:r}:null}return e.class==="card_surface"?{...n,name:"card_expanded"}:e.errorCode==="CHECKOUT_SESSION_CREATE_FAILED"?{...n,name:"checkout_error",phase:"session_create"}:e.errorCode==="SDK_INITIALIZATION_FAILED"||e.errorCode==="PROVIDER_LOAD_FAILED"?{...n,name:"checkout_error",phase:"sdk_load"}:e.errorCode==="PAYMENT_PROCESSING_FAILED"?{...n,name:"checkout_error",phase:e.requestCategory==="intent_create"?"wallets":"process"}:null}var Ma=new Set(["checkout_mount","sdk_loaded","form_rendered","card_expanded"]);function Hr(e,t){let n=(0,xr.useRef)(e);n.current=e;let r=(0,xr.useRef)(new Set),o=(0,xr.useRef)(t),i=(0,xr.useRef)(t);return ho(()=>{i.current=t,o.current!==t&&(o.current=t,r.current.clear())},[t]),(0,xr.useCallback)(d=>{if(i.current!==t)return;let c=al(d);if(c){if(Ma.has(c.name)){if(r.current.has(c.name))return;r.current.add(c.name)}et(()=>n.current?.(c))}},[t])}var il=Symbol.for("@flopay/js.telemetry.bridge.v1"),sl=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function ll(){return{error:()=>{},log:()=>{},performance:()=>{},terminal:()=>{},now:()=>globalThis.performance?.now()??0,elapsed:e=>Math.max(0,(globalThis.performance?.now()??e)-e),setCheckoutContext:()=>{},beginCheckout:()=>globalThis.performance?.now()??0,disable:()=>{},subscribe:()=>()=>{},flush:async()=>{},destroy:()=>{}}}function cl(e){let t=ll(),n=(o,i)=>o?o.bind(e):i,r=n(e.now,t.now);return{error:n(e.error,t.error),log:n(e.log,t.log),performance:n(e.performance,t.performance),terminal:n(e.terminal,t.terminal),now:r,elapsed:e.elapsed?e.elapsed.bind(e):o=>Math.max(0,r()-o),setCheckoutContext:n(e.setCheckoutContext,t.setCheckoutContext),beginCheckout:n(e.beginCheckout,t.beginCheckout),disable:n(e.disable,t.disable),subscribe:n(e.subscribe,t.subscribe),flush:n(e.flush,t.flush),destroy:n(e.destroy,t.destroy)}}function Wo(e){let t=globalThis[sl];return cl(t?.(e)??{})}function Vt(e){if(e)return e[il]}var xn=require("react/jsx-runtime"),Jo=45,dl=1e3,ul=11e3,pl=["https://www.paypal.com","https://www.sandbox.paypal.com"],Vi="We couldn't open PayPal. Try again or choose another payment method.",ml={width:"100%",minHeight:Jo,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 Ki(e){return e.includes("No ack for postMessage init()")&&pl.some(t=>e.includes(t))&&e.includes("10000ms")}function yl(e){return e?`${Vi} Allow pop-ups for this site, then try again.`:Vi}function fl(e){let t=e,n=t?.payer??t?.payment_source?.paypal;return{email:n?.email_address?.trim()||void 0,firstName:n?.name?.given_name?.trim()||void 0,lastName:n?.name?.surname?.trim()||void 0}}function Yi({sessionId:e,nonce:t,billingApiUrl:n,email:r,billingName:o,onBuyerIdentityReady:i,clientId:d,environment:c,currency:P,isSubscription:y,providerObjectType:h,onTokenizedBody:v,onComplete:B,onErrorChange:M,onDecline:m,onTechnicalFailure:S,isProcessing:fe=!1,onLoadStateChange:U,onInitializationStateChange:w,allowAutomaticRetry:ue=!0,onButtonClick:q,runBeforeButtonClick:ce,session:H,existingOrderId:ge,telemetry:$e,telemetryContext:Se,onInstrument:Pt,debug:ze=!1}){let Ie=sr(),Re=Hr(Pt,e),ne=(0,_.useMemo)(()=>{if(Ie)return null;let E=Wo({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:xt.SDK_VERSION,enabled:$e!==!1});return E.setCheckoutContext(Se??{}),E.beginCheckout(Se??{}),E},[n,Ie,$e,Se?.checkoutMode,Se?.layout]),re=(0,_.useMemo)(()=>Vt(Ie),[Ie]);(0,_.useEffect)(()=>()=>{ne&&ne.flush().catch(()=>{}).finally(()=>ne.destroy())},[ne]);let L=(0,_.useMemo)(()=>({error:E=>{re?re.error(E):ne?.error(E),Re({class:"technical_error",errorCode:E.requestCategory==="intent_create"?"PAYMENT_PROCESSING_FAILED":E.errorCode,requestCategory:E.requestCategory,provider:E.provider})},log:E=>{re?re.log(E):ne?.log(E),Re({class:"lifecycle",name:E.name,provider:E.provider})},performance:E=>{re?re.performance(E):ne?.performance(E)},terminal:E=>{re?re.terminal(E):ne?.terminal(E)},startTiming:()=>re?.now()??ne?.now()??0,elapsed:E=>re?.elapsed(E)??Math.max(0,(ne?.now()??E)-E)}),[Re,re,ne]),Ee=(0,_.useRef)(null),_e=(0,_.useRef)(0),J=(0,_.useRef)(null),we=(0,_.useRef)(!1),[ve,T]=(0,_.useState)(!1),[O,Ae]=(0,_.useState)(!1),[ye,Q]=(0,_.useState)(0),Le=(0,_.useRef)(0),[rt,ct]=(0,_.useState)(!1),Oe=(0,_.useRef)(!1),ee=(0,_.useRef)(!1),[W,V]=(0,_.useState)(!1),[Be,Je]=(0,_.useState)(!1),{request:A,collect:oe,finish:F}=jr(),R=(0,_.useRef)({sessionId:e,required:!(0,xt.isValidEmail)(r?.trim()||H?.customer?.email?.trim())});R.current.sessionId!==e&&(R.current={sessionId:e,required:!(0,xt.isValidEmail)(r?.trim()||H?.customer?.email?.trim())});let at=R.current.required,Ct=(0,_.useMemo)(()=>n.replace(/\/+$/,""),[n]),pt=H?.gateways?.paypal?.providerObjectType??h,Fe=pt??(y?"subscription":"order"),mt=pt==="order"||pt==="setup_token",Et=(0,_.useMemo)(()=>JSON.stringify([Ct,d,P,c??"",Fe,mt,e,ge??""]),[Ct,d,P,c,ge,Fe,mt,e]),C=(0,_.useRef)(Et),te=C.current!==Et,Xe=(0,_.useRef)(ze),He=(0,_.useRef)(null),[zt,Lt]=(0,_.useState)([]),G=(0,_.useCallback)(E=>{Xe.current&&Lt(ot=>[...ot,`${new Date().toISOString().slice(11,23)} ${E}`])},[]);(0,_.useEffect)(()=>{Xe.current=ze,ze&&G("debug:enabled"),He.current?.setEnabled(ze)},[G,ze]);let dt=(0,_.useRef)(v),Qt=(0,_.useRef)(B),gt=(0,_.useRef)(M),Ut=(0,_.useRef)(m),An=(0,_.useRef)(S),Bn=(0,_.useRef)(q),Fn=(0,_.useRef)(U),Jt=(0,_.useRef)(w),Wn=(0,_.useRef)(i),mn=(0,_.useRef)(ce),qt=(0,_.useRef)(H),rr=(0,_.useRef)(r),wt=(0,_.useRef)(o),Dn=(0,_.useRef)(t),it=(0,_.useRef)(null),pr=(0,_.useRef)(0),kt=(0,_.useRef)(null),Pn=(0,_.useRef)(null),It=(0,_.useRef)(new Map),Kt=(0,_.useRef)(new Map),yn=(0,_.useRef)(!1);(0,_.useEffect)(()=>(yn.current=!0,()=>{yn.current=!1}),[]),(0,_.useEffect)(()=>{dt.current=v},[v]),(0,_.useEffect)(()=>{Wn.current=i},[i]),(0,_.useEffect)(()=>{Qt.current=B},[B]),(0,_.useEffect)(()=>{gt.current=M},[M]),(0,_.useEffect)(()=>{Ut.current=m},[m]),(0,_.useEffect)(()=>{An.current=S},[S]),(0,_.useEffect)(()=>{Bn.current=q},[q]),(0,_.useEffect)(()=>{Fn.current=U},[U]),(0,_.useEffect)(()=>{Jt.current=w},[w]),(0,_.useEffect)(()=>{mn.current=ce},[ce]),(0,_.useEffect)(()=>{qt.current=H},[H]),(0,_.useEffect)(()=>{rr.current=r},[r]),(0,_.useEffect)(()=>{wt.current=o},[o]),(0,_.useEffect)(()=>{Dn.current=t},[t]),(0,_.useEffect)(()=>{Le.current=ye},[ye]),(0,_.useEffect)(()=>{rt&&J.current?.focus()},[rt,ye]);let on=(0,_.useCallback)(()=>{window.setTimeout(()=>{J.current?.focus()},0)},[]),Cn=(0,_.useCallback)(()=>{T(!1),Q(E=>E+1)},[]),en=(0,_.useCallback)(()=>{ct(!1),(Ee.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??Ee.current)?.focus?.()},[]);(0,_.useEffect)(()=>{!ve||!we.current||(we.current=!1,en())},[en,ve,ye]);let Sn=(0,_.useCallback)((E,ot)=>{let $t=An.current;if($t){$t("paypal",E,ot);return}gt.current?.(yl(ot?.popupBlocked??vr(E)))},[]),Nt=()=>{kt.current?.timer&&(clearTimeout(kt.current.timer),kt.current.timer=null)},se=()=>{Nt();let E=pr.current+1;return pr.current=E,Pn.current=null,kt.current={generation:E,timer:null,yieldedControl:!1},ct(!1),E},an=E=>E!==void 0&&kt.current?.generation!==E?!1:(Nt(),kt.current=null,Pn.current=null,!0),Ln=E=>{let ot=E?.generation??kt.current?.generation??pr.current;(!E?.generation||kt.current?.generation===ot)&&(Nt(),kt.current=null),Pn.current=ot,E?.showRetry&&ct(!0),E?.remount&&Cn(),E?.focus!==!1&&on()},Gn=E=>kt.current?.generation===E&&Pn.current!==E,Cr=E=>{typeof document<"u"&&document.visibilityState!=="visible"||(Nt(),E.timer=setTimeout(()=>{kt.current?.generation===E.generation&&(kt.current=null,Pn.current=E.generation,Sn(new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}),ct(!0),Cn(),on())},600))},Sr=()=>{let E=kt.current;E?.yieldedControl&&Cr(E)},mr=()=>{let E=kt.current;E&&(E.yieldedControl=!0,Nt())},Mt=E=>{let ot=it.current;return ot&&Kt.current.set(E,ot),E};(0,_.useEffect)(()=>{let E=()=>{document.visibilityState==="visible"?Sr():mr()};return document.addEventListener("visibilitychange",E),window.addEventListener("focus",Sr),window.addEventListener("blur",mr),()=>{document.removeEventListener("visibilitychange",E),window.removeEventListener("focus",Sr),window.removeEventListener("blur",mr),Nt()}},[]),(0,_.useEffect)(()=>{C.current!==Et&&(C.current=Et,Oe.current=!1,ee.current=!1,T(!1),Ae(!1),V(!1),Jt.current?.("loading"))},[Et]),(0,_.useEffect)(()=>{et(()=>Fn.current?.(ve&&!W))},[ve,W]);let Ye=(0,xt.normalizeGatewayEnvironment)(c);(0,_.useEffect)(()=>{let E=d?`${d.slice(0,6)}\u2026(len ${d.length})`:"(empty)",ot=typeof navigator<"u"?navigator.userAgent:"(no navigator)";if(G(`mount clientId=${E} env=${c??"(unset)"}\u2192${Ye??"live"} ccy=${P} sub=${y}`),G(`ua=${ot.slice(0,80)}${ot.length>80?"\u2026":""}`),!d){G("FAIL: clientId empty \u2014 gateway misconfigured"),V(!0),L.error({errorCode:"CONFIGURATION_INVALID",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),console.error("[FloPay] DirectPayPal: clientId empty \u2014 gateway misconfigured");return}if(!Ee.current){G("FAIL: containerRef not attached");return}_e.current=L.startTiming(),L.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let $t=!1,fn=!1,Pe=()=>$t||fn,tn,wr=!1,Br=()=>{tn=(0,xt.generateIdempotencyKey)(),tn||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),wr=!0},sn=null,fr=!1,Jn=null,Nn=!1,At=()=>{!Jn||Nn||(Nn=!0,Jn.close().catch(()=>{}))},On=null,Xn=()=>{On!==null&&(L.log({name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal"}),L.performance({stage:"overlay_return",durationMs:L.elapsed(On),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal"}),On=null)},ln=!1,Xt=Ee.current,zn=null,Un=null,st=[],cn=null,dn=!1,qn=!1,wn=null,xe=g=>{if(!g||typeof g.getBoundingClientRect!="function")return"(no rect)";let p=g.getBoundingClientRect();return`${Math.round(p.width)}\xD7${Math.round(p.height)}`},Zt=g=>{if(!g)return"(empty)";try{let p=new URL(g,typeof window<"u"?window.location.href:"https://localhost"),b=p.pathname.toLowerCase();return b.includes("checkcaptcha")||b.includes("captcha")?`CAPTCHA(${p.host}${b})`:b.includes("risk")||b.includes("challenge")?`RISK(${p.host}${b})`:b.includes("smart/buttons")?`smart-buttons(${p.host})`:`${p.host}${b}`.slice(0,100)}catch{return g.slice(0,80)}},Bt=g=>{let p=g.getAttribute("src"),b=g.getAttribute("srcdoc"),Ce=g.getAttribute("name"),pe=g.getAttribute("sandbox"),We=[];return p&&We.push(`src=${Zt(p)}`),b&&We.push(`srcdoc[${b.length}ch]`),!p&&!b&&We.push("src=(empty) srcdoc=(empty)"),Ce&&We.push(`name=${Ce.slice(0,40)}`),pe!==null&&We.push(`sandbox="${pe.slice(0,40)}"`),We.join(" ")},gr=g=>{if(!(g instanceof HTMLIFrameElement))return"";try{let p=g.contentDocument;if(!p)return"cd=null";let b=p.body?.children.length??0,Ce=p.body?.innerHTML.length??0,pe=p.head?.innerHTML.length??0;return`cd=same-origin readyState=${p.readyState} body[${b}children,${Ce}ch] head[${pe}ch]`}catch(p){return`cd=cross-origin(${p.message.slice(0,30)})`}},$n=[],hr=g=>{if(Pe())return;let p=g.message??String(g.error??"(no message)");p&&(p.toLowerCase().includes("paypal")||p.toLowerCase().includes("zoid")||p.toLowerCase().includes("postrobot")||p.toLowerCase().includes("storage"))&&(G(`window:error ${p.slice(0,140)}`),$n.push(p))},gn=g=>{if(Pe())return;let p=g.reason instanceof Error?g.reason.message:String(g.reason??"(no reason)");p&&(p.toLowerCase().includes("paypal")||p.toLowerCase().includes("zoid")||p.toLowerCase().includes("postrobot")||p.toLowerCase().includes("storage"))&&(G(`window:rejection ${p.slice(0,140)}`),$n.push(p))},kn={value:0},Ft=()=>{for(zn?.disconnect(),zn=null,Un?.disconnect(),Un=null;st.length;)clearTimeout(st.pop());qn=!1,dn&&typeof window<"u"&&(window.removeEventListener("error",hr),window.removeEventListener("unhandledrejection",gn)),dn=!1},N=()=>{if(!(dn||Pe()||ln)){if(dn=!0,$n.length=0,kn.value=0,typeof window<"u"&&(window.addEventListener("error",hr),window.addEventListener("unhandledrejection",gn)),typeof PerformanceObserver<"u")try{Un=new PerformanceObserver(g=>{if(!Pe())for(let p of g.getEntries()){if(!p.name.toLowerCase().includes("paypal"))continue;kn.value+=1;let b=Math.round(p.duration);G(`net ${b}ms ${p.name.slice(0,90)}`)}}),Un.observe({type:"resource",buffered:!0})}catch{}wn?.()}},$=()=>{cn&&(clearTimeout(cn),cn=null)},ae=()=>{Ft(),$()},ie={setEnabled:g=>{g?N():Ft()}};He.current=ie,Xe.current&&N();let Te=g=>{if(!g)return!1;let p=g.toLowerCase();return p.includes("zoid destroyed")||p.includes("destroyed all components")||p.includes("window closed")||p.includes("detected container element removed")},z=g=>{if(Pe()||Te(g))return;let p=br(g)??g;et(()=>gt.current?.(p))},X=g=>{$t||(V(!0),g.includes("paypal_ineligible")||L.error({errorCode:"PROVIDER_LOAD_FAILED",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime"}),console.error("[FloPay] DirectPayPal load/render failure:",g))},f=(g,p=!1)=>{if($t)return;let b=Oe.current||!ue;if(fr)return;fr=!0,fn=!0,ae(),At();let Ce=p||Ki(g);if(Ce&&ue&&!Oe.current){Oe.current=!0,T(!1),Je(!1),Ae(!0),Jt.current?.("retrying"),sn=setTimeout(()=>{$t||Q(pe=>pe+1)},dl);return}if(Ce||b){if(T(!1),Je(!1),Ae(!1),V(!0),Jt.current?.("exhausted"),!ee.current){ee.current=!0;let pe=Ki(g)?"paypal_init_timeout":p?"paypal_render_timeout":"paypal_init_failure";console.error("[FloPay] Direct PayPal initialization failed:",pe)}return}X(g)};V(!1);let K=async(g,p=it.current)=>{if(Pe())return;let b=p?.sessionId??e;if(dt.current){await dt.current(g,{sessionId:b,accountPatch:p?.accountPatch,nonce:p?.nonce});return}let Ce=L.startTiming();L.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let pe=()=>{L.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),L.performance({stage:"processing",durationMs:L.elapsed(Ce),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})};try{let We=qt.current,Ze=p?.accountPatch?.email??rr.current,le=p?.accountPatch?.userId??We?.customer?.id??We?.accountData?.userId??"",D=p?.accountPatch?.firstName??We?.customer?.firstName??We?.accountData?.firstName,me=p?.accountPatch?.lastName??We?.customer?.lastName??We?.accountData?.lastName,je=await new Go.PaymentAPI(Ct,{telemetry:!1}).processPayment(le,{sessionId:b,nonce:p?.nonce??Dn.current,tokenizedData:g,accountData:{userId:le,email:Ze??We?.customer?.email??"",...D?{firstName:D}:{},...me?{lastName:me}:{},country:p?.accountPatch?.country??We?.customer?.country??We?.accountData?.country??void 0,zip:p?.accountPatch?.zip??We?.customer?.zip??We?.accountData?.zip??void 0}});if(je.ok){if(fn||$t&&yn.current)return;pe(),L.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),et(()=>Qt.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(Pe())return;let ft=await je.json().catch(()=>null),Ve=ft?.message??"PayPal payment failed.",Ot=br(Ve)??Ve;pe(),je.status===400&&(typeof ft?.declineCode=="string"||!Array.isArray(ft?.fields))?L.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):je.status===400||je.status===422?L.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx"}):L.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:je.status>=500?"5xx":je.status>=400?"4xx":je.status>=300?"3xx":"unknown",failureCategory:je.status>=500?"server_error":void 0}),z(Ot),et(()=>Ut.current?.(jt("paypal",Ot,{code:ft?.code,declineCode:ft?.declineCode})));return}catch(We){if(Pe())return;pe(),L.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let Ze=We instanceof Error?We.message:"PayPal payment failed.",le=br(Ze)??Ze;z(le),et(()=>Ut.current?.(jt("paypal",le)));return}},Z=()=>new xt.FloPayError("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),ut=g=>Pe()?Promise.reject(Z()):Promise.resolve(g),yt=async g=>{if(Pe())throw Z();wr||Br();let p=it.current,b=p?.sessionId??e,Ce=p?.nonce??Dn.current;L.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let pe;try{pe=await new Go.PaymentAPI(Ct,{telemetry:!1}).createSessionIntent(b,Ce??"",mt?{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:xt.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE,paymentMethodId:null,intentKind:Fe==="setup_token"?"setup":"payment"}:{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"},{idempotencyKey:tn})}catch(We){throw L.error({...(0,xt.classifyTelemetryFailure)(We,"PAYMENT_PROCESSING_FAILED","unknown"),stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"}),We}if(Pe())throw Z();if(pe.provider!=="paypal"||pe.providerObjectType!==Fe)throw new Error(g);return L.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),pe.providerObjectId},de=(g,p)=>{let b=p?.nonce??Dn.current;if(!b)return;let Ce=p?.sessionId??e,pe=Kr(g)??ir(g)??"provider_declined";new Go.PaymentAPI(Ct,{telemetry:!1}).reportSessionIntentDecline(Ce,b,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:pe}).catch(()=>{})},Me=ye;G("loadScript:scheduled (deferred 1 tick)");let Ht=null,tt=setTimeout(()=>{if($t){G("loadScript:skipped (cancelled before defer ran)");return}G("loadScript:start");let g=Ye==="live"?"production":Ye;Ht=(0,Hi.loadScript)({clientId:d,currency:P,...Fe==="subscription"?{intent:"subscription",vault:!0}:Fe==="order"?{intent:"capture"}:{},...g?{environment:g}:{},...g==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}}),Ht.then(p=>{if(G(`loadScript:resolved inactive=${Pe()} ns=${!!p} buttons=${!!p?.Buttons}`),Pe())return;if(!p?.Buttons){G("FAIL: namespace missing Buttons factory"),f("PayPal SDK did not expose the Buttons factory.");return}L.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),L.performance({stage:"provider_ready",durationMs:L.elapsed(_e.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),L.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let b=async(le,D)=>{if(Pe()||Le.current!==Me)return;let me=le.vaultSetupToken??le.subscriptionID??le.orderID??"",Ge=me?Kt.current.get(me):It.current.get(Me);if(!(!Ge||!Gn(Ge.generation))&&an(Ge.generation)){Kt.current.delete(me),It.current.delete(Ge.surfaceKey),Xn();try{if(Je(!0),et(()=>gt.current?.(null)),!me)throw new xt.FloPayError("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});let je=qt.current,ft=Rr(wt.current??[je?.customer?.firstName,je?.customer?.lastName].filter(Boolean).join(" ")),Ve=pn({email:Ge.accountPatch?.email?.trim()||rr.current?.trim()||je?.customer?.email?.trim(),firstName:Ge.accountPatch?.firstName?.trim()||ft.firstName,lastName:Ge.accountPatch?.lastName?.trim()||ft.lastName});if(!(0,xt.isValidEmail)(Ve.email)||!(Ve.firstName||Ve.lastName))try{let Ot=fl(await D?.order?.get?.());Ve=pn({email:Ot.email||Ve.email,firstName:Ot.firstName||Ve.firstName,lastName:Ot.lastName||Ve.lastName})}catch{}if((Wn.current||at)&&!(0,xt.isValidEmail)(Ve.email)){let Ot=await oe("PayPal",Ve);if(!Ot)return;Ve=Ot}(0,xt.isValidEmail)(Ve.email)&&(Ge.accountPatch=pn({...Ge.accountPatch,...Ve}),await Wn.current?.(Ve)),await K(Fe==="setup_token"?{id:me,type:"paypal_setup_token",isPaypal:!0,gateway:"paypal",paymentMethodType:xt.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE}:mt?{id:me,isPaypal:!0,gateway:"paypal",paymentMethodType:xt.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE}:{id:me,isPaypal:!0},Ge)}catch(je){z(je instanceof Error?je.message:"PayPal capture failed.")}finally{Pe()||Je(!1)}}},Ce=p.Buttons({style:{layout:"horizontal",height:Jo,tagline:!1},onClick:async(le,D)=>{if(Pe()){await D.reject();return}Br();let me=mn.current,Ge={};if(me)try{let Ve=await me("paypal");if(Pe()){await D.reject();return}if(!Ve.proceed){it.current=null,It.current.delete(Me),await D.reject();return}Ge={sessionId:Ve.sessionId,accountPatch:Ve.accountPatch,nonce:Ve.nonce}}catch(Ve){G(`onClick:runBeforeButtonClick rejected msg=${(Ve instanceof Error?Ve.message:String(Ve)).slice(0,120)}`),it.current=null,It.current.delete(Me),await D.reject();return}et(()=>Bn.current?.("paypal"));let ft={generation:se(),surfaceKey:Me,...Ge};it.current=ft,It.current.set(Me,ft),await D.resolve(),L.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),L.log({name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),L.log({name:"provider.overlay.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),On=L.startTiming()},createOrder:Fe==="order"?ge?()=>ut(ge).then(Mt):()=>yt("Failed to create PayPal order.").then(Mt):void 0,createSubscription:Fe==="subscription"?ge?()=>ut(ge).then(Mt):()=>yt("Failed to create PayPal subscription.").then(Mt):void 0,createVaultSetupToken:Fe==="setup_token"?()=>yt("Failed to create PayPal setup token.").then(Mt):void 0,onApprove:b,onCancel:()=>{if(Pe())return;let le=It.current.get(Me)??it.current;le&&It.current.delete(le.surfaceKey),it.current=null,Xn(),L.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),we.current=!0,Ln({generation:le?.generation,remount:!0,focus:!1})},onError:le=>{if(Pe()||Le.current!==Me)return;let D=le instanceof Error?le.message:"PayPal failed to render.";if(G(`onError rendered=${ln} msg=${D.slice(0,120)}`),ln){let me=It.current.get(Me)??it.current;if(me&&!Gn(me.generation)||!me&&Pn.current===pr.current)return;if(Te(D)){an(me?.generation);return}if(Xn(),fo(le)){L.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),de(le,me),et(()=>Ut.current?.(jt("paypal",D))),me&&It.current.delete(me.surfaceKey),it.current=null,an(me?.generation);return}let Ge=D.toLowerCase();L.error({errorCode:Ge.includes("popup")&&Ge.includes("block")?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),me&&It.current.delete(me.surfaceKey),it.current=null,Ln({generation:me?.generation,remount:!0,showRetry:!0,focus:!0}),Sn(le,{code:"paypal_runtime_failed"});return}f(D)}}),pe=Ce.isEligible();if(G(`isEligible=${pe}`),L.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!pe){T(!1),f("PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}Jn=Ce,wn=()=>{if(!dn||qn||Pe()||ln)return;qn=!0,G(`container:dims ${xe(Xt)} visibility=${typeof document<"u"?document.visibilityState:"(no document)"}`),typeof MutationObserver<"u"&&(zn=new MutationObserver(D=>{if(!Pe()){for(let me of D)if(me.type==="childList")me.addedNodes.forEach(Ge=>{if(!(Ge instanceof Element))return;let je=Ge.tagName.toLowerCase(),ft=(Ge.getAttribute("title")??"").slice(0,40),Ve=je==="iframe"?` ${Bt(Ge)}`:"";G(`child+ ${je}${ft?` title="${ft}"`:""}${Ve} dims=${xe(Ge)}`)});else if(me.type==="attributes"&&me.target instanceof Element){let Ge=me.target;if(Ge.tagName.toLowerCase()!=="iframe")continue;let je=me.attributeName;(je==="src"||je==="srcdoc")&&G(`attr~ iframe ${je}=${je==="srcdoc"?`[${(Ge.getAttribute("srcdoc")??"").length}ch]`:Zt(Ge.getAttribute("src"))} dims=${xe(Ge)}`)}}}),zn.observe(Xt,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let le=D=>{if(Pe()||ln)return;let me=Xt.querySelectorAll("iframe"),Ge=typeof document<"u"&&"hasStorageAccess"in document;G(`watchdog:${D} container=${xe(Xt)} children=${Xt.childElementCount} iframes=${me.length} visibility=${typeof document<"u"?document.visibilityState:"(no document)"} cookies=${typeof navigator<"u"?navigator.cookieEnabled:"?"} hasStorageAccessApi=${Ge} paypalNetRequests=${kn.value}`),me.forEach((je,ft)=>{let Ve=(je.getAttribute("title")??"").slice(0,40);G(` iframe[${ft}] ${xe(je)}${Ve?` title="${Ve}"`:""} ${Bt(je)}`);let Ot=gr(je);Ot&&G(` ${Ot}`)}),$n.length===0&&G(" (no PayPal/zoid window errors captured)")};st.push(setTimeout(()=>le("3s"),3e3)),st.push(setTimeout(()=>le("8s"),8e3)),st.push(setTimeout(()=>le("15s"),15e3))},wn(),G("render:start");let Ze=L.startTiming();cn=setTimeout(()=>{Pe()||ln||(G("watchdog:11s retryable render timeout"),f("PayPal Buttons render did not settle within 11000ms.",!0))},ul),Ce.render(Xt).then(()=>{if(G(`render:resolved inactive=${Pe()}`),ae(),Pe()){At();return}ln=!0,T(!0),Ae(!1),Jt.current?.("ready"),L.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),L.performance({stage:"checkout_render",durationMs:L.elapsed(Ze),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}).catch(le=>{let D=le instanceof Error?le.message:"PayPal failed to render.";G(`render:rejected msg=${D.slice(0,120)}`),ae(),f(D)})}).catch(p=>{let b=p instanceof Error?p.message:"PayPal SDK failed to load.";G(`loadScript:rejected msg=${b.slice(0,120)}`),f(b)})},0);return()=>{$t=!0,clearTimeout(tt),sn&&clearTimeout(sn),ae(),He.current===ie&&(He.current=null),At()}},[ue,Ct,d,P,c,Fe,mt,e,ge,ye,L,oe,at,G]);let yr=ze?(0,xn.jsxs)("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:W?"#fef2f2":"#f3f4f6",border:`1px solid ${W?"#fca5a5":"#d1d5db"}`,borderRadius:6,color:"#111827",font:"11px/1.35 ui-monospace, SFMono-Regular, Menlo, monospace",whiteSpace:"pre-wrap",wordBreak:"break-word",maxHeight:220,overflowY:"auto"},children:[`FloPay/DirectPayPal-debug (ready=${ve} failed=${W})`,zt.length===0?`
|
|
1
|
+
"use strict";var Ks=Object.create;var $o=Object.defineProperty;var Hs=Object.getOwnPropertyDescriptor;var Ys=Object.getOwnPropertyNames;var Ws=Object.getPrototypeOf,Gs=Object.prototype.hasOwnProperty;var Js=(e,t)=>{for(var n in t)$o(e,n,{get:t[n],enumerable:!0})},Ai=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Ys(t))!Gs.call(e,o)&&o!==n&&$o(e,o,{get:()=>t[o],enumerable:!(r=Hs(t,o))||r.enumerable});return e};var Bi=(e,t,n)=>(n=e!=null?Ks(Ws(e)):{},Ai(t||!e||!e.__esModule?$o(n,"default",{value:e,enumerable:!0}):n,e)),Xs=e=>Ai($o({},"__esModule",{value:!0}),e);var Gl={};Js(Gl,{DirectPayPalButton:()=>bo,FloPayAutomaticPaymentButton:()=>ws,FloPayCardSetup:()=>Is,FloPayCardSetupError:()=>_o,FloPayCheckout:()=>da,FloPayProvider:()=>Po,SplitCardForm:()=>ia,VaultCardFields:()=>Xr,dropThirdPartyOnlyError:()=>Rs.dropThirdPartyOnlyError,useCheckout:()=>qi,useFloPay:()=>sr,usePayPalFloPay:()=>Ho});module.exports=Xs(Gl);var Rs=require("@flopay/shared");var ua=require("@flopay/js"),bn=require("@flopay/shared"),qe=require("react");var St=require("react/jsx-runtime");function Zs(){return(0,St.jsxs)(St.Fragment,{children:[(0,St.jsxs)("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,St.jsx)("rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}),(0,St.jsx)("line",{x1:"2",x2:"22",y1:"10",y2:"10"})]}),"Credit / Debit Card",(0,St.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"#9ca3af",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{position:"absolute",right:"1rem"},"aria-hidden":"true",children:(0,St.jsx)("path",{d:"M9 18l6-6-6-6"})})]})}function Qs(){return(0,St.jsx)(St.Fragment,{children:"Go back"})}function el(){return(0,St.jsx)(St.Fragment,{children:"Secure card checkout"})}function Or(e){return e!==void 0&&(e===""||e===null||e===!1)}function zr({content:e}){return(0,St.jsx)(St.Fragment,{children:e===void 0?(0,St.jsx)(Zs,{}):e})}function Ur({content:e}){return(0,St.jsx)(St.Fragment,{children:e===void 0?(0,St.jsx)(Qs,{}):e})}function mo({content:e}){return(0,St.jsx)(St.Fragment,{children:e===void 0?(0,St.jsx)(el,{}):e})}var or=require("@flopay/shared");function qr(e,t,n,r={}){let o;return(i={})=>{if(o)return o;let d={...r,...i,email:i.email?.trim()||r.email?.trim()};if(!(0,or.isValidEmail)(d.email))return Promise.reject(new or.FloPayError("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}));let c={};for(let[P,y]of Object.entries(d)){if(typeof y!="string")continue;let h=y.trim();h&&(c[P]=h)}return o=e.claimCheckoutSession(t,n,{accountData:c}),o.catch(()=>{}),o}}function Fi(e,t){return t?e?{account:{...e.account??{},...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,..."checkoutMetadata"in t?{checkoutMetadata:t.checkoutMetadata}:"checkoutMetadata"in e?{checkoutMetadata:e.checkoutMetadata}:{},tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}:t:e}function _a(e,t){return t?{...e,account:{...e.account,...t.account??{}},couponCodes:t.couponCodes??e.couponCodes,..."checkoutMetadata"in t?{checkoutMetadata:t.checkoutMetadata}:{},tagsData:{...e.tagsData??{},...t.tagsData??{}},utmMetadata:t.utmMetadata??e.utmMetadata}:e}function Di(e,t){let n=e.products??[...(e.subscriptions??[]).map(i=>({type:"subscription",code:i.code??i.providerPlanId,name:i.subscriptionName??i.providerPlanName??i.code??i.providerPlanId??null,quantity:i.quantity??1,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount,currency:i.currency,metadata:i.metadata})),...(e.items??[]).map(i=>({type:"item",code:i.code??i.providerItemId,name:i.itemName??i.providerItemName??i.code??i.providerItemId??null,quantity:i.quantity??1,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount,currency:i.currency,metadata:i.metadata}))],r=n.reduce((i,d)=>i+(d.overrideAmount??d.totalAmount??0),0),o=e.currency??n.find(i=>i.currency)?.currency??"USD";return{id:"",clientSecret:"",mode:n.some(i=>i.type==="subscription")?"subscription":"payment",amount:Math.round(r*100),currency:o,status:"open",captureMethod:e.captureMethod,customer:{id:e.account.userId,email:e.account.email??"",firstName:e.account.firstName,lastName:e.account.lastName,gender:e.account.gender??void 0,city:e.account.city??void 0,state:e.account.state??void 0,country:e.account.country??void 0,zip:e.account.zip??void 0},successUrl:e.successUrl,cancelUrl:e.cancelUrl,checkoutMode:t??e.checkoutMode??"full",products:n.map((i,d)=>({uuid:`synthetic-${i.type??"item"}-${d}`,checkoutSessionId:"",type:i.type??"item",code:i.code,name:i.name??null,quantity:i.quantity??1,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount??null,currency:i.currency??o,metadata:i.metadata??null}))}}function Rr(e){let t=e?.trim().split(/\s+/).filter(Boolean)??[];return t.length===0?{}:{firstName:t[0],lastName:t.length>1?t.slice(1).join(" "):void 0}}function xa(e,t){return t?{...e,...t}:e}function jt(e,t,n){let r=typeof t=="string"?t:t.message,o=typeof t=="string"?n?.code:n?.code??t.code,i=typeof t=="string"?n?.declineCode:n?.declineCode??t.declineCode;return{method:e,message:r,...o?{code:o}:{},...i?{declineCode:i}:{}}}var tl=[{match:/^paypal authorization required\.?$/i,replacement:"For your additional security, please re-authenticate this payment via PayPal."}];function br(e){if(typeof e!="string")return e??void 0;let t=e.trim();if(!t)return e;for(let{match:n,replacement:r}of tl)if(n.test(t))return r;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 $r(e){return e?.status==="authorized"||e?.status==="complete"}function Li(e){return e?.status==="expired"&&(e.failureOutcome==="authorization_expired"||e.captureMethod==="manual")}function jo(e){let t=Li(e);return new or.FloPayError(t?"Authorization has expired.":"Checkout session has expired.","api_error",{code:t?"authorization_expired":"checkout_session_expired"})}function Vo(e){let t=Li(e);return new or.FloPayError(t?"Authorization has expired.":"Automatic payment failed. Please try again.","api_error",{code:t?"authorization_expired":e?.status==="expired"?"checkout_session_expired":"checkout_processing_timeout"})}function Ko(e,t){return e==="processing"||(0,or.isMoneySettledOutcome)(e,t)}function Ni(e){return e==="succeeded"?"succeeded":e==="processing"||e==="requires_capture"?"processing":"failed"}function Oi(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?{mode:"setup"}:{mode:"payment",amount:e}}function yo(e){let t=[e?.id,e?.originalPaymentMethodId];for(let n of t)if(typeof n=="string"&&n.startsWith("pm_"))return n}var Mr=require("@flopay/js"),be=require("@flopay/shared"),k=Bi(require("react"),1);var Ta=require("react"),_n=(0,Ta.createContext)({flopay:null,paypalFlopay:null,billingApiUrl:""}),Kn=(0,Ta.createContext)({session:null,loading:!1,error:null});var Go=require("@flopay/js"),xt=require("@flopay/shared"),Hi=require("@paypal/paypal-js"),x=require("react");var zi=require("@flopay/shared"),Hn=require("react"),ar=require("react/jsx-runtime");function pn(e){let{firstName:t,lastName:n,...r}=e,o=t?.trim(),i=n?.trim();return{...r,...o?{firstName:o}:{},...i?{lastName:i}:{}}}function jr(){let[e,t]=(0,Hn.useState)(null),n=(0,Hn.useRef)(null),r=(0,Hn.useRef)(0),o=(0,Hn.useCallback)((d,c)=>(n.current?.(null),r.current+=1,t({id:r.current,methodLabel:d,identity:c}),new Promise(P=>{n.current=P})),[]),i=(0,Hn.useCallback)(d=>{let c=n.current;n.current=null,t(null),c?.(d)},[]);return(0,Hn.useEffect)(()=>()=>{n.current?.(null),n.current=null},[]),{request:e,collect:o,finish:i}}function Vr({identity:e,methodLabel:t,onComplete:n,onCancel:r,submitting:o=!1,testId:i="flopay-buyer-identity-pane"}){let[d,c]=(0,Hn.useState)(e.email?.trim()??""),P=(0,zi.isValidEmail)(d.trim());return(0,ar.jsxs)("div",{"data-testid":i,style:{display:"flex",flexDirection:"column",gap:"0.75rem",padding:"0.875rem",border:"1px solid #d1d5db",borderRadius:8,background:"#fff",color:"#262833"},children:[(0,ar.jsxs)("div",{style:{fontWeight:700},children:["Continue with ",t]}),(0,ar.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",(0,ar.jsx)("input",{type:"email",autoComplete:"email","data-testid":"flopay-email",required:!0,value:d,onChange:y=>c(y.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]}),(0,ar.jsxs)("div",{style:{display:"flex",gap:"0.5rem"},children:[r&&(0,ar.jsx)("button",{type:"button",onClick:r,style:{flex:1,minHeight:42},children:"Cancel"}),(0,ar.jsxs)("button",{type:"button",disabled:!P||o,onClick:()=>{n(pn({...e,email:d.trim()}))},style:{flex:2,minHeight:42},children:["Continue with ",t]})]})]})}function nl(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 _r(e){if(typeof e!="string")return;let t=e.trim();return/^[a-z0-9_.-]{1,64}$/i.test(t)?t:void 0}function ir(e){if(typeof e!="object"||e===null)return;let t=e;return _r(t.code)??_r(t.type)??_r(t.name)}function Kr(e){if(!(typeof e!="object"||e===null))return _r(e.decline_code)}function fo(e){return typeof e!="object"||e===null?!1:_r(e.type)?.toLowerCase()==="card_error"||Kr(e)!==void 0}function vr(e){let t=nl(e)?.toLowerCase()??"",r=`${ir(e)?.toLowerCase()??""} ${t}`;return r.includes("popup")&&r.includes("block")}var Ui=require("@flopay/shared"),go=require("react");function sr(){return(0,go.useContext)(_n).flopay}function Ho(){return(0,go.useContext)(_n).paypalFlopay??null}function qi(){return(0,go.useContext)(Kn)}function $i(){return(0,go.useContext)(_n).billingApiUrl||(0,Ui.resolveBillingApiUrl)()}var ji=require("@flopay/shared"),xr=require("react");function et(e){if(!e)return;let t=n=>{console.error("[FloPay] Merchant callback failed; checkout continued.",n)};try{Promise.resolve(e()).catch(t)}catch(n){t(n)}}var Yo=require("react"),ho=typeof window>"u"?Yo.useEffect:Yo.useLayoutEffect;var rl={"checkout.mount":"checkout_mount","sdk.initialize.ready":"sdk_loaded","provider.ready":"sdk_loaded","checkout.rendered":"form_rendered","vault.widget.ready":"form_rendered","vault.submission.started":"tokenize","payment.tokenization.started":"tokenize","payment.processing.started":"process_attempt","payment.intent.started":"process_attempt","vault.action.required":"3ds_challenge","payment.three_ds.handoff":"3ds_challenge"};function ol(e){return e==="stripe"||e==="paypal"?e:void 0}function al(e){let t=ol(e.provider),n={schemaVersion:ji.FLO_INSTRUMENT_SCHEMA_VERSION,...t?{gateway:t}:{}};if(e.class==="lifecycle"){let r=rl[e.name];return r?{...n,name:r}:null}return e.class==="card_surface"?{...n,name:"card_expanded"}:e.errorCode==="CHECKOUT_SESSION_CREATE_FAILED"?{...n,name:"checkout_error",phase:"session_create"}:e.errorCode==="SDK_INITIALIZATION_FAILED"||e.errorCode==="PROVIDER_LOAD_FAILED"?{...n,name:"checkout_error",phase:"sdk_load"}:e.errorCode==="PAYMENT_PROCESSING_FAILED"?{...n,name:"checkout_error",phase:e.requestCategory==="intent_create"?"wallets":"process"}:null}var Ma=new Set(["checkout_mount","sdk_loaded","form_rendered","card_expanded"]);function Hr(e,t){let n=(0,xr.useRef)(e);n.current=e;let r=(0,xr.useRef)(new Set),o=(0,xr.useRef)(t),i=(0,xr.useRef)(t);return ho(()=>{i.current=t,o.current!==t&&(o.current=t,r.current.clear())},[t]),(0,xr.useCallback)(d=>{if(i.current!==t)return;let c=al(d);if(c){if(Ma.has(c.name)){if(r.current.has(c.name))return;r.current.add(c.name)}et(()=>n.current?.(c))}},[t])}var il=Symbol.for("@flopay/js.telemetry.bridge.v1"),sl=Symbol.for("@flopay/js.telemetry.reporter-factory.v1");function ll(){return{error:()=>{},log:()=>{},performance:()=>{},terminal:()=>{},now:()=>globalThis.performance?.now()??0,elapsed:e=>Math.max(0,(globalThis.performance?.now()??e)-e),setCheckoutContext:()=>{},beginCheckout:()=>globalThis.performance?.now()??0,disable:()=>{},subscribe:()=>()=>{},flush:async()=>{},destroy:()=>{}}}function cl(e){let t=ll(),n=(o,i)=>o?o.bind(e):i,r=n(e.now,t.now);return{error:n(e.error,t.error),log:n(e.log,t.log),performance:n(e.performance,t.performance),terminal:n(e.terminal,t.terminal),now:r,elapsed:e.elapsed?e.elapsed.bind(e):o=>Math.max(0,r()-o),setCheckoutContext:n(e.setCheckoutContext,t.setCheckoutContext),beginCheckout:n(e.beginCheckout,t.beginCheckout),disable:n(e.disable,t.disable),subscribe:n(e.subscribe,t.subscribe),flush:n(e.flush,t.flush),destroy:n(e.destroy,t.destroy)}}function Wo(e){let t=globalThis[sl];return cl(t?.(e)??{})}function Vt(e){if(e)return e[il]}var xn=require("react/jsx-runtime"),Jo=45,dl=1e3,ul=11e3,pl=["https://www.paypal.com","https://www.sandbox.paypal.com"],Vi="We couldn't open PayPal. Try again or choose another payment method.",ml={width:"100%",minHeight:Jo,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 Ki(e){return e.includes("No ack for postMessage init()")&&pl.some(t=>e.includes(t))&&e.includes("10000ms")}function yl(e){return e?`${Vi} Allow pop-ups for this site, then try again.`:Vi}function fl(e){let t=e,n=t?.payer??t?.payment_source?.paypal;return{email:n?.email_address?.trim()||void 0,firstName:n?.name?.given_name?.trim()||void 0,lastName:n?.name?.surname?.trim()||void 0}}function Yi({sessionId:e,nonce:t,billingApiUrl:n,email:r,billingName:o,onBuyerIdentityReady:i,clientId:d,environment:c,currency:P,isSubscription:y,providerObjectType:h,onTokenizedBody:v,onComplete:B,onErrorChange:M,onDecline:m,onTechnicalFailure:S,isProcessing:he=!1,onLoadStateChange:U,onInitializationStateChange:w,allowAutomaticRetry:ue=!0,onButtonClick:q,runBeforeButtonClick:ce,session:H,existingOrderId:fe,telemetry:$e,telemetryContext:Se,onInstrument:Pt,debug:ze=!1}){let Ie=sr(),Re=Hr(Pt,e),ne=(0,x.useMemo)(()=>{if(Ie)return null;let E=Wo({billingApiUrl:n,sdkPackage:"@flopay/react",sdkVersion:xt.SDK_VERSION,enabled:$e!==!1});return E.setCheckoutContext(Se??{}),E.beginCheckout(Se??{}),E},[n,Ie,$e,Se?.checkoutMode,Se?.layout]),re=(0,x.useMemo)(()=>Vt(Ie),[Ie]);(0,x.useEffect)(()=>()=>{ne&&ne.flush().catch(()=>{}).finally(()=>ne.destroy())},[ne]);let L=(0,x.useMemo)(()=>({error:E=>{re?re.error(E):ne?.error(E),Re({class:"technical_error",errorCode:E.requestCategory==="intent_create"?"PAYMENT_PROCESSING_FAILED":E.errorCode,requestCategory:E.requestCategory,provider:E.provider})},log:E=>{re?re.log(E):ne?.log(E),Re({class:"lifecycle",name:E.name,provider:E.provider})},performance:E=>{re?re.performance(E):ne?.performance(E)},terminal:E=>{re?re.terminal(E):ne?.terminal(E)},startTiming:()=>re?.now()??ne?.now()??0,elapsed:E=>re?.elapsed(E)??Math.max(0,(ne?.now()??E)-E)}),[Re,re,ne]),Ee=(0,x.useRef)(null),_e=(0,x.useRef)(0),J=(0,x.useRef)(null),we=(0,x.useRef)(!1),[ve,T]=(0,x.useState)(!1),[O,Ae]=(0,x.useState)(!1),[ye,Q]=(0,x.useState)(0),Le=(0,x.useRef)(0),[rt,ct]=(0,x.useState)(!1),Oe=(0,x.useRef)(!1),ee=(0,x.useRef)(!1),[W,V]=(0,x.useState)(!1),[Be,Je]=(0,x.useState)(!1),{request:A,collect:oe,finish:F}=jr(),R=(0,x.useRef)({sessionId:e,required:!(0,xt.isValidEmail)(r?.trim()||H?.customer?.email?.trim())});R.current.sessionId!==e&&(R.current={sessionId:e,required:!(0,xt.isValidEmail)(r?.trim()||H?.customer?.email?.trim())});let at=R.current.required,Ct=(0,x.useMemo)(()=>n.replace(/\/+$/,""),[n]),pt=H?.gateways?.paypal?.providerObjectType??h,Fe=pt??(y?"subscription":"order"),mt=pt==="order"||pt==="setup_token",Et=(0,x.useMemo)(()=>JSON.stringify([Ct,d,P,c??"",Fe,mt,e,fe??""]),[Ct,d,P,c,fe,Fe,mt,e]),C=(0,x.useRef)(Et),te=C.current!==Et,Xe=(0,x.useRef)(ze),He=(0,x.useRef)(null),[zt,Lt]=(0,x.useState)([]),G=(0,x.useCallback)(E=>{Xe.current&&Lt(ot=>[...ot,`${new Date().toISOString().slice(11,23)} ${E}`])},[]);(0,x.useEffect)(()=>{Xe.current=ze,ze&&G("debug:enabled"),He.current?.setEnabled(ze)},[G,ze]);let dt=(0,x.useRef)(v),Qt=(0,x.useRef)(B),gt=(0,x.useRef)(M),Ut=(0,x.useRef)(m),An=(0,x.useRef)(S),Bn=(0,x.useRef)(q),Fn=(0,x.useRef)(U),Jt=(0,x.useRef)(w),Wn=(0,x.useRef)(i),mn=(0,x.useRef)(ce),qt=(0,x.useRef)(H),rr=(0,x.useRef)(r),wt=(0,x.useRef)(o),Dn=(0,x.useRef)(t),it=(0,x.useRef)(null),pr=(0,x.useRef)(0),kt=(0,x.useRef)(null),Pn=(0,x.useRef)(null),It=(0,x.useRef)(new Map),Kt=(0,x.useRef)(new Map),yn=(0,x.useRef)(!1);(0,x.useEffect)(()=>(yn.current=!0,()=>{yn.current=!1}),[]),(0,x.useEffect)(()=>{dt.current=v},[v]),(0,x.useEffect)(()=>{Wn.current=i},[i]),(0,x.useEffect)(()=>{Qt.current=B},[B]),(0,x.useEffect)(()=>{gt.current=M},[M]),(0,x.useEffect)(()=>{Ut.current=m},[m]),(0,x.useEffect)(()=>{An.current=S},[S]),(0,x.useEffect)(()=>{Bn.current=q},[q]),(0,x.useEffect)(()=>{Fn.current=U},[U]),(0,x.useEffect)(()=>{Jt.current=w},[w]),(0,x.useEffect)(()=>{mn.current=ce},[ce]),(0,x.useEffect)(()=>{qt.current=H},[H]),(0,x.useEffect)(()=>{rr.current=r},[r]),(0,x.useEffect)(()=>{wt.current=o},[o]),(0,x.useEffect)(()=>{Dn.current=t},[t]),(0,x.useEffect)(()=>{Le.current=ye},[ye]),(0,x.useEffect)(()=>{rt&&J.current?.focus()},[rt,ye]);let on=(0,x.useCallback)(()=>{window.setTimeout(()=>{J.current?.focus()},0)},[]),Cn=(0,x.useCallback)(()=>{T(!1),Q(E=>E+1)},[]),en=(0,x.useCallback)(()=>{ct(!1),(Ee.current?.querySelector('iframe, button, [tabindex]:not([tabindex="-1"])')??Ee.current)?.focus?.()},[]);(0,x.useEffect)(()=>{!ve||!we.current||(we.current=!1,en())},[en,ve,ye]);let Sn=(0,x.useCallback)((E,ot)=>{let $t=An.current;if($t){$t("paypal",E,ot);return}gt.current?.(yl(ot?.popupBlocked??vr(E)))},[]),Nt=()=>{kt.current?.timer&&(clearTimeout(kt.current.timer),kt.current.timer=null)},se=()=>{Nt();let E=pr.current+1;return pr.current=E,Pn.current=null,kt.current={generation:E,timer:null,yieldedControl:!1},ct(!1),E},an=E=>E!==void 0&&kt.current?.generation!==E?!1:(Nt(),kt.current=null,Pn.current=null,!0),Ln=E=>{let ot=E?.generation??kt.current?.generation??pr.current;(!E?.generation||kt.current?.generation===ot)&&(Nt(),kt.current=null),Pn.current=ot,E?.showRetry&&ct(!0),E?.remount&&Cn(),E?.focus!==!1&&on()},Gn=E=>kt.current?.generation===E&&Pn.current!==E,Cr=E=>{typeof document<"u"&&document.visibilityState!=="visible"||(Nt(),E.timer=setTimeout(()=>{kt.current?.generation===E.generation&&(kt.current=null,Pn.current=E.generation,Sn(new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}),ct(!0),Cn(),on())},600))},Sr=()=>{let E=kt.current;E?.yieldedControl&&Cr(E)},mr=()=>{let E=kt.current;E&&(E.yieldedControl=!0,Nt())},Mt=E=>{let ot=it.current;return ot&&Kt.current.set(E,ot),E};(0,x.useEffect)(()=>{let E=()=>{document.visibilityState==="visible"?Sr():mr()};return document.addEventListener("visibilitychange",E),window.addEventListener("focus",Sr),window.addEventListener("blur",mr),()=>{document.removeEventListener("visibilitychange",E),window.removeEventListener("focus",Sr),window.removeEventListener("blur",mr),Nt()}},[]),(0,x.useEffect)(()=>{C.current!==Et&&(C.current=Et,Oe.current=!1,ee.current=!1,T(!1),Ae(!1),V(!1),Jt.current?.("loading"))},[Et]),(0,x.useEffect)(()=>{et(()=>Fn.current?.(ve&&!W))},[ve,W]);let Ye=(0,xt.normalizeGatewayEnvironment)(c);(0,x.useEffect)(()=>{let E=d?`${d.slice(0,6)}\u2026(len ${d.length})`:"(empty)",ot=typeof navigator<"u"?navigator.userAgent:"(no navigator)";if(G(`mount clientId=${E} env=${c??"(unset)"}\u2192${Ye??"live"} ccy=${P} sub=${y}`),G(`ua=${ot.slice(0,80)}${ot.length>80?"\u2026":""}`),!d){G("FAIL: clientId empty \u2014 gateway misconfigured"),V(!0),L.error({errorCode:"CONFIGURATION_INVALID",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),console.error("[FloPay] DirectPayPal: clientId empty \u2014 gateway misconfigured");return}if(!Ee.current){G("FAIL: containerRef not attached");return}_e.current=L.startTiming(),L.log({name:"provider.load.started",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal"});let $t=!1,fn=!1,Pe=()=>$t||fn,tn,wr=!1,Br=()=>{tn=(0,xt.generateIdempotencyKey)(),tn||console.warn("[FloPay] DirectPayPal: secure idempotency key unavailable; retries may not be deduplicated."),wr=!0},sn=null,fr=!1,Jn=null,Nn=!1,At=()=>{!Jn||Nn||(Nn=!0,Jn.close().catch(()=>{}))},On=null,Xn=()=>{On!==null&&(L.log({name:"provider.overlay.returned",stage:"overlay_return",provider:"paypal",paymentMethodCategory:"paypal"}),L.performance({stage:"overlay_return",durationMs:L.elapsed(On),durationMode:"buyer",provider:"paypal",paymentMethodCategory:"paypal"}),On=null)},ln=!1,Xt=Ee.current,zn=null,Un=null,st=[],cn=null,dn=!1,qn=!1,wn=null,xe=g=>{if(!g||typeof g.getBoundingClientRect!="function")return"(no rect)";let p=g.getBoundingClientRect();return`${Math.round(p.width)}\xD7${Math.round(p.height)}`},Zt=g=>{if(!g)return"(empty)";try{let p=new URL(g,typeof window<"u"?window.location.href:"https://localhost"),b=p.pathname.toLowerCase();return b.includes("checkcaptcha")||b.includes("captcha")?`CAPTCHA(${p.host}${b})`:b.includes("risk")||b.includes("challenge")?`RISK(${p.host}${b})`:b.includes("smart/buttons")?`smart-buttons(${p.host})`:`${p.host}${b}`.slice(0,100)}catch{return g.slice(0,80)}},Bt=g=>{let p=g.getAttribute("src"),b=g.getAttribute("srcdoc"),Ce=g.getAttribute("name"),pe=g.getAttribute("sandbox"),We=[];return p&&We.push(`src=${Zt(p)}`),b&&We.push(`srcdoc[${b.length}ch]`),!p&&!b&&We.push("src=(empty) srcdoc=(empty)"),Ce&&We.push(`name=${Ce.slice(0,40)}`),pe!==null&&We.push(`sandbox="${pe.slice(0,40)}"`),We.join(" ")},gr=g=>{if(!(g instanceof HTMLIFrameElement))return"";try{let p=g.contentDocument;if(!p)return"cd=null";let b=p.body?.children.length??0,Ce=p.body?.innerHTML.length??0,pe=p.head?.innerHTML.length??0;return`cd=same-origin readyState=${p.readyState} body[${b}children,${Ce}ch] head[${pe}ch]`}catch(p){return`cd=cross-origin(${p.message.slice(0,30)})`}},$n=[],hr=g=>{if(Pe())return;let p=g.message??String(g.error??"(no message)");p&&(p.toLowerCase().includes("paypal")||p.toLowerCase().includes("zoid")||p.toLowerCase().includes("postrobot")||p.toLowerCase().includes("storage"))&&(G(`window:error ${p.slice(0,140)}`),$n.push(p))},gn=g=>{if(Pe())return;let p=g.reason instanceof Error?g.reason.message:String(g.reason??"(no reason)");p&&(p.toLowerCase().includes("paypal")||p.toLowerCase().includes("zoid")||p.toLowerCase().includes("postrobot")||p.toLowerCase().includes("storage"))&&(G(`window:rejection ${p.slice(0,140)}`),$n.push(p))},kn={value:0},Ft=()=>{for(zn?.disconnect(),zn=null,Un?.disconnect(),Un=null;st.length;)clearTimeout(st.pop());qn=!1,dn&&typeof window<"u"&&(window.removeEventListener("error",hr),window.removeEventListener("unhandledrejection",gn)),dn=!1},N=()=>{if(!(dn||Pe()||ln)){if(dn=!0,$n.length=0,kn.value=0,typeof window<"u"&&(window.addEventListener("error",hr),window.addEventListener("unhandledrejection",gn)),typeof PerformanceObserver<"u")try{Un=new PerformanceObserver(g=>{if(!Pe())for(let p of g.getEntries()){if(!p.name.toLowerCase().includes("paypal"))continue;kn.value+=1;let b=Math.round(p.duration);G(`net ${b}ms ${p.name.slice(0,90)}`)}}),Un.observe({type:"resource",buffered:!0})}catch{}wn?.()}},$=()=>{cn&&(clearTimeout(cn),cn=null)},ae=()=>{Ft(),$()},ie={setEnabled:g=>{g?N():Ft()}};He.current=ie,Xe.current&&N();let Te=g=>{if(!g)return!1;let p=g.toLowerCase();return p.includes("zoid destroyed")||p.includes("destroyed all components")||p.includes("window closed")||p.includes("detected container element removed")},z=g=>{if(Pe()||Te(g))return;let p=br(g)??g;et(()=>gt.current?.(p))},X=g=>{$t||(V(!0),g.includes("paypal_ineligible")||L.error({errorCode:"PROVIDER_LOAD_FAILED",stage:"provider_load",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk",failureCategory:"provider_runtime"}),console.error("[FloPay] DirectPayPal load/render failure:",g))},f=(g,p=!1)=>{if($t)return;let b=Oe.current||!ue;if(fr)return;fr=!0,fn=!0,ae(),At();let Ce=p||Ki(g);if(Ce&&ue&&!Oe.current){Oe.current=!0,T(!1),Je(!1),Ae(!0),Jt.current?.("retrying"),sn=setTimeout(()=>{$t||Q(pe=>pe+1)},dl);return}if(Ce||b){if(T(!1),Je(!1),Ae(!1),V(!0),Jt.current?.("exhausted"),!ee.current){ee.current=!0;let pe=Ki(g)?"paypal_init_timeout":p?"paypal_render_timeout":"paypal_init_failure";console.error("[FloPay] Direct PayPal initialization failed:",pe)}return}X(g)};V(!1);let K=async(g,p=it.current)=>{if(Pe())return;let b=p?.sessionId??e;if(dt.current){await dt.current(g,{sessionId:b,accountPatch:p?.accountPatch,nonce:p?.nonce});return}let Ce=L.startTiming();L.log({name:"payment.processing.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"});let pe=()=>{L.log({name:"payment.processing.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),L.performance({stage:"processing",durationMs:L.elapsed(Ce),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})};try{let We=qt.current,Ze=p?.accountPatch?.email??rr.current,le=p?.accountPatch?.userId??We?.customer?.id??We?.accountData?.userId??"",D=p?.accountPatch?.firstName??We?.customer?.firstName??We?.accountData?.firstName,me=p?.accountPatch?.lastName??We?.customer?.lastName??We?.accountData?.lastName,je=await new Go.PaymentAPI(Ct,{telemetry:!1}).processPayment(le,{sessionId:b,nonce:p?.nonce??Dn.current,paymentMethodCategory:"paypal",tokenizedData:g,accountData:{userId:le,email:Ze??We?.customer?.email??"",...D?{firstName:D}:{},...me?{lastName:me}:{},country:p?.accountPatch?.country??We?.customer?.country??We?.accountData?.country??void 0,zip:p?.accountPatch?.zip??We?.customer?.zip??We?.accountData?.zip??void 0}});if(je.ok){if(fn||$t&&yn.current)return;pe(),L.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),et(()=>Qt.current?.({status:"succeeded",checkoutMethod:"paypal"}));return}if(Pe())return;let ft=await je.json().catch(()=>null),Ve=ft?.message??"PayPal payment failed.",Ot=br(Ve)??Ve;pe(),je.status===400&&(typeof ft?.declineCode=="string"||!Array.isArray(ft?.fields))?L.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):je.status===400||je.status===422?L.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal",statusClass:"4xx"}):L.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:je.status>=500?"5xx":je.status>=400?"4xx":je.status>=300?"3xx":"unknown",failureCategory:je.status>=500?"server_error":void 0}),z(Ot),et(()=>Ut.current?.(jt("paypal",Ot,{code:ft?.code,declineCode:ft?.declineCode})));return}catch(We){if(Pe())return;pe(),L.error({errorCode:"NETWORK_REQUEST_FAILED",failureCategory:"transport_error",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"process_payment",statusClass:"network_error"});let Ze=We instanceof Error?We.message:"PayPal payment failed.",le=br(Ze)??Ze;z(le),et(()=>Ut.current?.(jt("paypal",le)));return}},Z=()=>new xt.FloPayError("PayPal render was superseded.","api_error",{code:"paypal_render_superseded"}),ut=g=>Pe()?Promise.reject(Z()):Promise.resolve(g),yt=async g=>{if(Pe())throw Z();wr||Br();let p=it.current,b=p?.sessionId??e,Ce=p?.nonce??Dn.current;L.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});let pe;try{pe=await new Go.PaymentAPI(Ct,{telemetry:!1}).createSessionIntent(b,Ce??"",mt?{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:xt.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE,paymentMethodId:null,intentKind:Fe==="setup_token"?"setup":"payment"}:{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"},{idempotencyKey:tn})}catch(We){throw L.error({...(0,xt.classifyTelemetryFailure)(We,"PAYMENT_PROCESSING_FAILED","unknown"),stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"}),We}if(Pe())throw Z();if(pe.provider!=="paypal"||pe.providerObjectType!==Fe)throw new Error(g);return L.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),pe.providerObjectId},de=(g,p)=>{let b=p?.nonce??Dn.current;if(!b)return;let Ce=p?.sessionId??e,pe=Kr(g)??ir(g)??"provider_declined";new Go.PaymentAPI(Ct,{telemetry:!1}).reportSessionIntentDecline(Ce,b,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:pe}).catch(()=>{})},Me=ye;G("loadScript:scheduled (deferred 1 tick)");let Ht=null,tt=setTimeout(()=>{if($t){G("loadScript:skipped (cancelled before defer ran)");return}G("loadScript:start");let g=Ye==="live"?"production":Ye;Ht=(0,Hi.loadScript)({clientId:d,currency:P,...Fe==="subscription"?{intent:"subscription",vault:!0}:Fe==="order"?{intent:"capture"}:{},...g?{environment:g}:{},...g==="sandbox"?{dataNamespace:"paypal_sandbox"}:{}}),Ht.then(p=>{if(G(`loadScript:resolved inactive=${Pe()} ns=${!!p} buttons=${!!p?.Buttons}`),Pe())return;if(!p?.Buttons){G("FAIL: namespace missing Buttons factory"),f("PayPal SDK did not expose the Buttons factory.");return}L.log({name:"provider.ready",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),L.performance({stage:"provider_ready",durationMs:L.elapsed(_e.current),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),L.log({name:"provider.availability.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"});let b=async(le,D)=>{if(Pe()||Le.current!==Me)return;let me=le.vaultSetupToken??le.subscriptionID??le.orderID??"",Ge=me?Kt.current.get(me):It.current.get(Me);if(!(!Ge||!Gn(Ge.generation))&&an(Ge.generation)){Kt.current.delete(me),It.current.delete(Ge.surfaceKey),Xn();try{if(Je(!0),et(()=>gt.current?.(null)),!me)throw new xt.FloPayError("PayPal did not return an approval token.","api_error",{code:"paypal_missing_token"});let je=qt.current,ft=Rr(wt.current??[je?.customer?.firstName,je?.customer?.lastName].filter(Boolean).join(" ")),Ve=pn({email:Ge.accountPatch?.email?.trim()||rr.current?.trim()||je?.customer?.email?.trim(),firstName:Ge.accountPatch?.firstName?.trim()||ft.firstName,lastName:Ge.accountPatch?.lastName?.trim()||ft.lastName});if(!(0,xt.isValidEmail)(Ve.email)||!(Ve.firstName||Ve.lastName))try{let Ot=fl(await D?.order?.get?.());Ve=pn({email:Ot.email||Ve.email,firstName:Ot.firstName||Ve.firstName,lastName:Ot.lastName||Ve.lastName})}catch{}if((Wn.current||at)&&!(0,xt.isValidEmail)(Ve.email)){let Ot=await oe("PayPal",Ve);if(!Ot)return;Ve=Ot}(0,xt.isValidEmail)(Ve.email)&&(Ge.accountPatch=pn({...Ge.accountPatch,...Ve}),await Wn.current?.(Ve)),await K(Fe==="setup_token"?{id:me,type:"paypal_setup_token",isPaypal:!0,gateway:"paypal",paymentMethodType:xt.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE}:mt?{id:me,isPaypal:!0,gateway:"paypal",paymentMethodType:xt.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE}:{id:me,isPaypal:!0},Ge)}catch(je){z(je instanceof Error?je.message:"PayPal capture failed.")}finally{Pe()||Je(!1)}}},Ce=p.Buttons({style:{layout:"horizontal",height:Jo,tagline:!1},onClick:async(le,D)=>{if(Pe()){await D.reject();return}Br();let me=mn.current,Ge={};if(me)try{let Ve=await me("paypal");if(Pe()){await D.reject();return}if(!Ve.proceed){it.current=null,It.current.delete(Me),await D.reject();return}Ge={sessionId:Ve.sessionId,accountPatch:Ve.accountPatch,nonce:Ve.nonce}}catch(Ve){G(`onClick:runBeforeButtonClick rejected msg=${(Ve instanceof Error?Ve.message:String(Ve)).slice(0,120)}`),it.current=null,It.current.delete(Me),await D.reject();return}et(()=>Bn.current?.("paypal"));let ft={generation:se(),surfaceKey:Me,...Ge};it.current=ft,It.current.set(Me,ft),await D.resolve(),L.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),L.log({name:"provider.popup.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),L.log({name:"provider.overlay.opened",stage:"overlay_open",provider:"paypal",paymentMethodCategory:"paypal"}),On=L.startTiming()},createOrder:Fe==="order"?fe?()=>ut(fe).then(Mt):()=>yt("Failed to create PayPal order.").then(Mt):void 0,createSubscription:Fe==="subscription"?fe?()=>ut(fe).then(Mt):()=>yt("Failed to create PayPal subscription.").then(Mt):void 0,createVaultSetupToken:Fe==="setup_token"?()=>yt("Failed to create PayPal setup token.").then(Mt):void 0,onApprove:b,onCancel:()=>{if(Pe())return;let le=It.current.get(Me)??it.current;le&&It.current.delete(le.surfaceKey),it.current=null,Xn(),L.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),we.current=!0,Ln({generation:le?.generation,remount:!0,focus:!1})},onError:le=>{if(Pe()||Le.current!==Me)return;let D=le instanceof Error?le.message:"PayPal failed to render.";if(G(`onError rendered=${ln} msg=${D.slice(0,120)}`),ln){let me=It.current.get(Me)??it.current;if(me&&!Gn(me.generation)||!me&&Pn.current===pr.current)return;if(Te(D)){an(me?.generation);return}if(Xn(),fo(le)){L.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),de(le,me),et(()=>Ut.current?.(jt("paypal",D))),me&&It.current.delete(me.surfaceKey),it.current=null,an(me?.generation);return}let Ge=D.toLowerCase();L.error({errorCode:Ge.includes("popup")&&Ge.includes("block")?"POPUP_BLOCKED":"PROVIDER_RUNTIME_FAILED",failureCategory:"provider_runtime",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"provider_sdk"}),me&&It.current.delete(me.surfaceKey),it.current=null,Ln({generation:me?.generation,remount:!0,showRetry:!0,focus:!0}),Sn(le,{code:"paypal_runtime_failed"});return}f(D)}}),pe=Ce.isEligible();if(G(`isEligible=${pe}`),L.log({name:"provider.eligibility.checked",stage:"provider_ready",provider:"paypal",paymentMethodCategory:"paypal"}),!pe){T(!1),f("PayPal buttons are not eligible to render in this context (paypal_ineligible).");return}Jn=Ce,wn=()=>{if(!dn||qn||Pe()||ln)return;qn=!0,G(`container:dims ${xe(Xt)} visibility=${typeof document<"u"?document.visibilityState:"(no document)"}`),typeof MutationObserver<"u"&&(zn=new MutationObserver(D=>{if(!Pe()){for(let me of D)if(me.type==="childList")me.addedNodes.forEach(Ge=>{if(!(Ge instanceof Element))return;let je=Ge.tagName.toLowerCase(),ft=(Ge.getAttribute("title")??"").slice(0,40),Ve=je==="iframe"?` ${Bt(Ge)}`:"";G(`child+ ${je}${ft?` title="${ft}"`:""}${Ve} dims=${xe(Ge)}`)});else if(me.type==="attributes"&&me.target instanceof Element){let Ge=me.target;if(Ge.tagName.toLowerCase()!=="iframe")continue;let je=me.attributeName;(je==="src"||je==="srcdoc")&&G(`attr~ iframe ${je}=${je==="srcdoc"?`[${(Ge.getAttribute("srcdoc")??"").length}ch]`:Zt(Ge.getAttribute("src"))} dims=${xe(Ge)}`)}}}),zn.observe(Xt,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcdoc"]}));let le=D=>{if(Pe()||ln)return;let me=Xt.querySelectorAll("iframe"),Ge=typeof document<"u"&&"hasStorageAccess"in document;G(`watchdog:${D} container=${xe(Xt)} children=${Xt.childElementCount} iframes=${me.length} visibility=${typeof document<"u"?document.visibilityState:"(no document)"} cookies=${typeof navigator<"u"?navigator.cookieEnabled:"?"} hasStorageAccessApi=${Ge} paypalNetRequests=${kn.value}`),me.forEach((je,ft)=>{let Ve=(je.getAttribute("title")??"").slice(0,40);G(` iframe[${ft}] ${xe(je)}${Ve?` title="${Ve}"`:""} ${Bt(je)}`);let Ot=gr(je);Ot&&G(` ${Ot}`)}),$n.length===0&&G(" (no PayPal/zoid window errors captured)")};st.push(setTimeout(()=>le("3s"),3e3)),st.push(setTimeout(()=>le("8s"),8e3)),st.push(setTimeout(()=>le("15s"),15e3))},wn(),G("render:start");let Ze=L.startTiming();cn=setTimeout(()=>{Pe()||ln||(G("watchdog:11s retryable render timeout"),f("PayPal Buttons render did not settle within 11000ms.",!0))},ul),Ce.render(Xt).then(()=>{if(G(`render:resolved inactive=${Pe()}`),ae(),Pe()){At();return}ln=!0,T(!0),Ae(!1),Jt.current?.("ready"),L.log({name:"checkout.rendered",stage:"checkout_render",provider:"paypal",paymentMethodCategory:"paypal"}),L.performance({stage:"checkout_render",durationMs:L.elapsed(Ze),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"})}).catch(le=>{let D=le instanceof Error?le.message:"PayPal failed to render.";G(`render:rejected msg=${D.slice(0,120)}`),ae(),f(D)})}).catch(p=>{let b=p instanceof Error?p.message:"PayPal SDK failed to load.";G(`loadScript:rejected msg=${b.slice(0,120)}`),f(b)})},0);return()=>{$t=!0,clearTimeout(tt),sn&&clearTimeout(sn),ae(),He.current===ie&&(He.current=null),At()}},[ue,Ct,d,P,c,Fe,mt,e,fe,ye,L,oe,at,G]);let yr=ze?(0,xn.jsxs)("pre",{"data-testid":"flopay-direct-paypal-debug",style:{margin:"0 0 8px 0",padding:"6px 8px",background:W?"#fef2f2":"#f3f4f6",border:`1px solid ${W?"#fca5a5":"#d1d5db"}`,borderRadius:6,color:"#111827",font:"11px/1.35 ui-monospace, SFMono-Regular, Menlo, monospace",whiteSpace:"pre-wrap",wordBreak:"break-word",maxHeight:220,overflowY:"auto"},children:[`FloPay/DirectPayPal-debug (ready=${ve} failed=${W})`,zt.length===0?`
|
|
2
2
|
(waiting for first lifecycle event\u2026)`:`
|
|
3
3
|
${zt.join(`
|
|
4
|
-
`)}`]}):null;return W&&!te?ze?(0,xn.jsx)("div",{children:yr}):null:(0,xn.jsxs)("div",{children:[yr,A&&(0,xn.jsx)(Vr,{identity:A.identity,methodLabel:A.methodLabel,testId:"flopay-direct-paypal-identity-pane",onComplete:F,onCancel:()=>F(null)}),(0,xn.jsxs)("div",{"aria-hidden":O||A?!0:void 0,style:O||A?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:Jo},children:[!ve&&!O&&(0,xn.jsx)("div",{"data-testid":"flopay-direct-paypal-placeholder",style:{position:"absolute",inset:0,borderRadius:8,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite",pointerEvents:"none"}}),(0,xn.jsx)("div",{ref:Ee,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,role:"group","aria-label":"PayPal payment method",style:{minHeight:Jo,display:"flex",opacity:ve?1:0},"aria-busy":Be||
|
|
4
|
+
`)}`]}):null;return W&&!te?ze?(0,xn.jsx)("div",{children:yr}):null:(0,xn.jsxs)("div",{children:[yr,A&&(0,xn.jsx)(Vr,{identity:A.identity,methodLabel:A.methodLabel,testId:"flopay-direct-paypal-identity-pane",onComplete:F,onCancel:()=>F(null)}),(0,xn.jsxs)("div",{"aria-hidden":O||A?!0:void 0,style:O||A?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:{position:"relative",minHeight:Jo},children:[!ve&&!O&&(0,xn.jsx)("div",{"data-testid":"flopay-direct-paypal-placeholder",style:{position:"absolute",inset:0,borderRadius:8,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite",pointerEvents:"none"}}),(0,xn.jsx)("div",{ref:Ee,"data-testid":"flopay-direct-paypal-container",tabIndex:-1,role:"group","aria-label":"PayPal payment method",style:{minHeight:Jo,display:"flex",opacity:ve?1:0},"aria-busy":Be||he},ye)]},ye),rt&&(0,xn.jsx)("button",{ref:J,type:"button","data-testid":"flopay-direct-paypal-focus-target",onClick:en,style:ml,children:"Try PayPal again"})]})}function bo(e){return(0,xn.jsx)(Yi,{...e})}function Wi(e){return(0,xn.jsx)(Yi,{...e})}var vo=require("react/jsx-runtime");function Yr({children:e,margin:t,icon:n=!0,styleOverride:r}){return(0,vo.jsxs)("div",{role:"alert","data-testid":"flopay-error",style:{margin:t,padding:"0.625rem 0.875rem",background:"#FEF2F2",border:"1px solid #FECACA",borderRadius:"8px",color:"#991B1B",fontSize:"0.85rem",fontWeight:600,...n?{display:"flex",alignItems:"center",gap:"0.5rem"}:{},...r??{}},children:[n&&(0,vo.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:(0,vo.jsx)("path",{d:"M12 9v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z",stroke:"#DC2626",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}),e]})}var Dt=require("react/jsx-runtime");function Tn({status:e,errorMessage:t,authorized:n=!1,processingLabel:r="PROCESSING...",successLabel:o,errorLabel:i="PAYMENT FAILED",successNote:d="You will be automatically redirected, do not close or navigate away from this window."}){return(0,Dt.jsx)("div",{"data-testid":"flopay-processing-overlay","data-status":e,role:"dialog","aria-modal":"true",style:{position:"fixed",inset:0,background:"rgba(0,0,0,0.35)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3,backdropFilter:"blur(2px)"},children:(0,Dt.jsxs)("div",{style:{background:"white",borderRadius:12,padding:"2rem 2.5rem",textAlign:"center",boxShadow:"0 8px 32px rgba(0,0,0,0.18)",minWidth:240,display:"flex",flexDirection:"column",alignItems:"center",gap:16},children:[(0,Dt.jsxs)("div",{style:{width:48,height:48,position:"relative"},children:[e==="processing"&&(0,Dt.jsxs)("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:{animation:"flopay-spin 0.8s linear infinite"},children:[(0,Dt.jsx)("circle",{cx:"12",cy:"12",r:"10",stroke:"#e5e7eb",strokeWidth:"3"}),(0,Dt.jsx)("path",{d:"M4 12a8 8 0 018-8v3a5 5 0 00-5 5H4z",fill:"#4A49FF"})]}),e==="success"&&(0,Dt.jsx)("div",{style:{animation:"flopay-pop 0.4s cubic-bezier(0.34,1.56,0.64,1)"},children:(0,Dt.jsxs)("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[(0,Dt.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#22c55e"}),(0,Dt.jsx)("path",{d:"M7 12.5l3 3 7-7",stroke:"white",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{strokeDasharray:20,strokeDashoffset:20,animation:"flopay-draw 0.4s 0.15s ease forwards"}})]})}),e==="error"&&(0,Dt.jsx)("div",{style:{animation:"flopay-shake 0.4s ease"},children:(0,Dt.jsxs)("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[(0,Dt.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#ef4444"}),(0,Dt.jsx)("path",{d:"M8 8l8 8M16 8l-8 8",stroke:"white",strokeWidth:"2.5",strokeLinecap:"round",style:{strokeDasharray:12,strokeDashoffset:12,animation:"flopay-draw 0.3s 0.1s ease forwards"}})]})})]}),(0,Dt.jsxs)("span",{style:{fontSize:14,fontWeight:600,letterSpacing:"0.05em",color:e==="success"?"#16a34a":e==="error"?"#dc2626":"#374151"},children:[e==="processing"&&r,e==="success"&&(o??(n?"PAYMENT AUTHORISED":"PAYMENT SUCCESSFUL")),e==="error"&&i]}),e==="success"&&d!==null&&(0,Dt.jsx)("p",{style:{fontSize:13,color:"#6b7280",fontWeight:400,maxWidth:260,lineHeight:1.4,margin:0},children:d}),e==="error"&&t&&(0,Dt.jsx)("p",{style:{fontSize:13,color:"#6b7280",fontWeight:400,maxWidth:260,lineHeight:1.4,margin:0},children:t}),(0,Dt.jsx)("style",{children:`
|
|
5
5
|
@keyframes flopay-spin { to { transform: rotate(360deg); } }
|
|
6
6
|
@keyframes flopay-pop { 0% { transform: scale(0); } 100% { transform: scale(1); } }
|
|
7
7
|
@keyframes flopay-draw { to { stroke-dashoffset: 0; } }
|
|
8
8
|
@keyframes flopay-shake { 0%,100% { transform: translateX(0); } 20%,60% { transform: translateX(-4px); } 40%,80% { transform: translateX(4px); } }
|
|
9
|
-
`})]})})}var Gi=require("@flopay/shared"),Gt=require("react");var Ji=require("react/jsx-runtime");function Po({flopay:e,paypalFlopay:t,options:n,onInstrument:r,children:o}){let[i,d]=(0,Gt.useState)(e instanceof Promise?null:e),[c,P]=(0,Gt.useState)(t instanceof Promise||!t?null:t),y=(0,Gt.useRef)(null),h=(0,Gt.useRef)(null),v=Hr(r);(0,Gt.useEffect)(()=>{v({class:"lifecycle",name:"checkout.mount"})},[v]),(0,Gt.useEffect)(()=>{i&&v({class:"lifecycle",name:"sdk.initialize.ready"})},[v,i]),(0,Gt.useEffect)(()=>{if(i)return Vt(i)?.subscribe?.(v)},[v,i]),(0,Gt.useEffect)(()=>{if(!(!c||c===i))return Vt(c)?.subscribe?.(v)},[v,i,c]),(0,Gt.useEffect)(()=>{if(!i)return;let m=Vt(i);return y.current=m?.beginCheckout()??m?.now()??0,m?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{m?.log({name:"checkout.unmount",stage:"unmount"})}},[i]),(0,Gt.useEffect)(()=>{let m=!1;return e instanceof Promise?e.then(S=>{m||d(S)},()=>{m||v({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"})}):d(e),()=>{m=!0}},[v,e]),(0,Gt.useEffect)(()=>{let m=!1;if(!t){P(null);return}return t instanceof Promise?t.then(S=>{m||P(S)},()=>{m||v({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED",provider:"paypal"})}):P(t),()=>{m=!0}},[v,t]),(0,Gt.useEffect)(()=>{if(!i||h.current===i)return;h.current=i;let m=Vt(i);m?.log({name:"checkout.rendered",stage:"checkout_render"}),v({class:"lifecycle",name:"checkout.rendered"}),m?.performance({stage:"checkout_render",durationMs:m.elapsed(y.current??0),durationMode:"machine"})},[v,i]);let B=(0,Gi.resolveBillingApiUrl)(n?.billingApiUrl),M=(0,Gt.useMemo)(()=>({flopay:i,paypalFlopay:c,billingApiUrl:B,emitInstrument:v}),[i,c,B,v]);return(0,Ji.jsx)(_n.Provider,{value:M,children:o})}var Xo="flopay_recent_completion_";function Wr(e){if(!(!e||typeof window>"u"))try{let t={expiresAt:Date.now()+6e4};window.sessionStorage.setItem(Xo+e,JSON.stringify(t))}catch{}}function Ba(e){if(!e||typeof window>"u")return!1;try{let t=window.sessionStorage.getItem(Xo+e);if(!t)return!1;let n=JSON.parse(t);return typeof n?.expiresAt!="number"||n.expiresAt<=Date.now()?(window.sessionStorage.removeItem(Xo+e),!1):!0}catch{return!1}}var Gr=require("@flopay/js"),Ue=require("@flopay/shared");var So="card";async function gl(e,t,n){if(n){if(typeof e.retrieveSetupIntent!="function")return null;let{setupIntent:i,error:d}=await e.retrieveSetupIntent(t);return{error:d,intent:i??null}}if(typeof e.retrievePaymentIntent!="function")return null;let{paymentIntent:r,error:o}=await e.retrievePaymentIntent(t);return{error:o,intent:r??null}}async function hl(e,t,n,r){if(r){if(typeof e.confirmCardSetup!="function")return null;let{setupIntent:d,error:c}=await e.confirmCardSetup(t,n);return{error:c,intent:d??null}}if(typeof e.confirmCardPayment!="function")return null;let{paymentIntent:o,error:i}=await e.confirmCardPayment(t,n);return{error:i,intent:o??null}}function Da(e,t){return Object.assign(e,{checkoutMethod:t})}function lr(e,t){let n=e instanceof Ue.FloPayError?e:new Ue.FloPayError(e instanceof Error?e.message:"Payment provider failed.","api_error",{code:"provider_runtime_failure"});return Object.assign(n,{checkoutMethod:t,telemetryFailureCategory:"provider_runtime",telemetryRequestCategory:"provider_sdk"})}async function Co(e,t){try{return await e()}catch(n){throw lr(n,t)}}function Xi(e){return!e?.type||!e.threeDSecureToken||e.type!=="3ds_required"&&e.type!=="paypal_redirect_required"?null:{type:e.type,threeDSecureToken:e.threeDSecureToken,paymentMethodId:e.paymentMethodId}}function bl(e){return e.status==="succeeded"||e.status==="declined"}async function Zi(e){if(typeof document>"u"||typeof window>"u")throw new Ue.FloPayError("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});if(e.signal?.aborted)throw new Ue.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"});let t=3e5,n=1e3,r=15e3,o=`${e.billingApiUrl.replace(/\/$/,"")}/v1/checkouts/sessions/${encodeURIComponent(e.sessionId)}/3ds/complete`,i=async()=>{let h=new AbortController,v=()=>h.abort();e.signal?.aborted?h.abort():e.signal?.addEventListener("abort",v);let B=window.setTimeout(()=>h.abort(),r);try{let M=await fetch(o,{method:"POST",headers:{"x-checkout-session-token":e.nonce,"content-type":"application/json"},body:"{}",signal:h.signal});if(!M.ok)return{status:"unknown"};let m=await M.json().catch(()=>null);return vl(m)}catch{return{status:"unknown"}}finally{window.clearTimeout(B),e.signal?.removeEventListener("abort",v)}},d=document.activeElement instanceof HTMLElement?document.activeElement:null,c=document.createElement("div");c.setAttribute("data-flopay-auto-3ds-overlay","1"),c.setAttribute("role","dialog"),c.setAttribute("aria-modal","true"),c.setAttribute("aria-label","Card authentication"),c.style.cssText=["position:fixed","inset:0","z-index:2147483647","background:rgba(15,23,42,0.6)","display:flex","align-items:center","justify-content:center","padding:16px"].join(";");let P=document.createElement("iframe");P.setAttribute("title","Card authentication"),P.setAttribute("allow","payment"),P.tabIndex=0,P.style.cssText=["width:min(100%,460px)","height:min(100%,640px)","border:0","border-radius:12px","background:#fff","box-shadow:0 12px 30px rgba(0,0,0,0.35)"].join(";"),P.src=e.nextActionRedirectUrl,c.appendChild(P),document.body.appendChild(c),P.focus();let y=null;try{y=new URL(e.billingApiUrl,window.location.href).origin}catch{y=null}try{let h=await new Promise((v,B)=>{let M=!1,m=0,S=0,fe=0,U=!1,w=()=>{window.clearTimeout(m),window.clearInterval(S),window.clearTimeout(fe),window.removeEventListener("message",H),P.removeEventListener("load",q),e.signal?.removeEventListener("abort",ce)},ue=async()=>{if(!(M||U)){U=!0;try{let ge=await i();if(M||!bl(ge))return;M=!0,w(),v(ge)}finally{U=!1}}},q=()=>{window.clearTimeout(fe),fe=window.setTimeout(()=>{ue()},250)},ce=()=>{M||(M=!0,w(),B(new Ue.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"})))},H=ge=>{if(ge.source!==P.contentWindow||y&&ge.origin!==y)return;let $e=ge.data;!$e||typeof $e!="object"||$e.source!=="flopay-vault-3ds-return"||M||(M=!0,w(),v(null))};m=window.setTimeout(()=>{M||(M=!0,w(),B(new Ue.FloPayError("Card authentication timed out.","api_error",{code:"three_ds_timeout"})))},t),S=window.setInterval(()=>{ue()},n),P.addEventListener("load",q),window.addEventListener("message",H),e.signal?.addEventListener("abort",ce),e.signal?.aborted&&ce()});return h||await i()}finally{c.parentNode?.removeChild(c),d?.isConnected&&d.focus()}}function vl(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 Pr(e,t="Payment failed. Please try again.",n){let r=n?.checkoutMethod??e?.checkoutMethod??(e?.type==="paypal_redirect_required"?"paypal":"card"),o=e?.message??t,i=br(o)??o;return Da(new Ue.FloPayError(i,"api_error",{code:(0,Ue.normalizeCheckoutFailureOutcome)(e?.outcome)??(0,Ue.normalizeCheckoutFailureOutcome)(e?.type)??e?.gatewayErrorCode}),r)}function Fa(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function Zo(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}async function Pl(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 Qi(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let o of n)if(typeof o=="string"&&o.length>0&&(!t?.requirePaymentIntentClientSecret||Zo(o)))return o;let r=e?.data;if(r&&typeof r=="object"){let o=r,i=[o.threeDSecureToken,o.clientSecret,o.stripeClientSecret,o.id];for(let c of i)if(typeof c=="string"&&c.length>0&&(!t?.requirePaymentIntentClientSecret||Zo(c)))return c;let d=o.gateways;if(d&&typeof d=="object"){let c=d.stripe;if(c&&typeof c=="object"){let P=c,y=[P.stripeClientSecret,P.clientSecret];for(let h of y)if(typeof h=="string"&&h.length>0&&(!t?.requirePaymentIntentClientSecret||Zo(h)))return h}}}}async function Cl({billingApiUrl:e,sessionId:t,nonce:n,responseJson:r}){let o=Qi(r,{requirePaymentIntentClientSecret:!0});if(typeof o=="string"&&o.length>0)return{type:"3ds_required",threeDSecureToken:o};if(!t)return null;try{let c=(await new Gr.PaymentAPI(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(Zo(c))return{type:"3ds_required",threeDSecureToken:c}}catch{}return null}async function Jr({billingApiUrl:e,sessionId:t,session:n,nonce:r,tokenizedData:o,returnUrl:i,telemetry:d}){let c=e.replace(/\/+$/,""),P=t??n.id,y=r??n.clientSecret,h=n.customer?.id??n.accountData?.userId??"",v=n.customer?.email??n.accountData?.email??"",B=n.customer?.firstName??n.accountData?.firstName??"",M=n.customer?.lastName??n.accountData?.lastName??"",m=n.customer?.country??n.accountData?.country??void 0,S=n.customer?.zip??n.accountData?.zip??void 0,fe=new Gr.PaymentAPI(c,d===!1?{telemetry:!1}:void 0),U=await Pl(()=>fe.processPayment(h,{sessionId:P,nonce:y,tokenizedData:o,accountData:{userId:h,email:v,firstName:B,lastName:M,country:m,zip:S},returnUrl:i??Fa(n)}));if(U.ok){let q=typeof U.json=="function"?await U.json().catch(()=>null):null;return(0,Ue.isAuthorizationOnlySession)(n)||q?.status==="authorized"?{type:"success",result:{status:"authorized",paymentId:typeof q?.paymentId=="string"?q.paymentId:n.paymentId,sessionId:typeof q?.sessionId=="string"?q.sessionId:P,authorizationExpiresAt:typeof q?.authorizationExpiresAt=="string"?q.authorizationExpiresAt:n.authorizationExpiresAt,paymentMethodId:yo(o),checkoutMethod:o?o.isPaypal?"paypal":"card":void 0}}:{type:"success",result:{status:"succeeded",paymentIntentId:o?.threeDSecureActionResultTokenId,paymentMethodId:yo(o),checkoutMethod:o?o.isPaypal?"paypal":"card":void 0}}}let w;try{w=await U.json()}catch{throw new Ue.FloPayError("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:U.status})}if(w?.type==="paypal_redirect_required"||w?.type==="3ds_required"){let q=Qi(w);if(!q)throw new Ue.FloPayError("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:U.status});return{type:w.type,threeDSecureToken:q,paymentMethodId:w.paymentMethodId}}if(w?.gatewayErrorCode==="authentication_required"){let q=await Cl({billingApiUrl:c,sessionId:P,nonce:y,responseJson:w});if(q)return q;throw Da(new Ue.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}let ue=new Ue.FloPayError(w?.message??"Payment failed. Please try again.","api_error",{code:w?.code??w?.gatewayErrorCode,declineCode:w?.declineCode??w?.gatewayDeclineReason,statusCode:U.status});throw Object.assign(ue,{telemetryOutcome:(0,Ue.classifyPaymentRejection)(U.status,w)})}async function Qo(e,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:i,session:d,returnUrl:c,telemetry:P}){let y=t?.getRawProvider();if(!y)throw lr(new Ue.FloPayError("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!r||!e.threeDSecureToken)throw Da(new Ue.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let h=(0,Ue.isSetupIntentClientSecret)(e.threeDSecureToken),v=null,B=e.paymentMethodId,M=await Co(()=>gl(y,e.threeDSecureToken,h),"card");if(M){if(M.error)throw lr(new Ue.FloPayError(M.error.message??`Failed to retrieve 3DS ${h?"setup":"payment"} status.`,"api_error",{code:M.error.code}),"card");let S=M.intent;!B&&S?.payment_method&&(typeof S.payment_method=="string"?B=S.payment_method:"id"in S.payment_method&&(B=S.payment_method.id??void 0))}let m=B?await Co(()=>hl(y,e.threeDSecureToken,{payment_method:B,return_url:c??Fa(d)??window.location.href},h),"card"):null;if(m){if(m.error)throw lr(new Ue.FloPayError(m.error.message??"3DS authentication failed.","api_error",{code:m.error.code}),"card");v=m.intent}else{let S=await Co(()=>y.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(S.error)throw lr(new Ue.FloPayError(S.error.message??"3DS authentication failed.","api_error",{code:S.error.code}),"card");v=(h?S.setupIntent:S.paymentIntent)??null}if(v&&(v.status==="requires_capture"||v.status==="succeeded"||v.status==="processing")){let S=await Jr({billingApiUrl:o,sessionId:i,session:d,telemetry:P,tokenizedData:{id:v.id,type:"card",threeDSecureActionResultTokenId:v.id},returnUrl:c});return S.type==="success"?{...S.result,paymentIntentId:S.result.paymentIntentId??v.id,paymentMethodId:S.result.paymentMethodId??B}:Qo(S,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:i,session:d,returnUrl:c,telemetry:P})}throw lr(new Ue.FloPayError("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let h=(n??t)?.getRawProvider();if(!h)throw lr(new Ue.FloPayError("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:B}=await Co(()=>h.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(B)throw lr(new Ue.FloPayError(B.message??"PayPal authorization failed.","api_error",{code:B.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:v}=await Co(()=>h.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:c??Fa(d)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(v)throw lr(new Ue.FloPayError(v.message??"PayPal authorization failed.","api_error",{code:v.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new Ue.FloPayError("Unsupported payment redirect state.","api_error")}function wo(e){if(e instanceof Ue.FloPayError){let r=br(e.message);return r&&r!==e.message?Object.assign(new Ue.FloPayError(r,e.type,{code:e.code,declineCode:e.declineCode,param:e.param,statusCode:e.statusCode}),{checkoutMethod:e.checkoutMethod,telemetryFailureCategory:e.telemetryFailureCategory,telemetryOutcome:e.telemetryOutcome,telemetryRequestCategory:e.telemetryRequestCategory}):e}let t=e instanceof Error?e.message:"Payment failed. Please try again.",n=br(t)??t;return new Ue.FloPayError(n,"api_error")}function ea(e){let t=e.data.stripe?.publishableKey,n=!!e.data.paypal?.publishableKey;if(!t&&!n)throw new Ue.FloPayError("Session advertises no supported gateways (expected `gateways.stripe` and/or `gateways.paypal`).","validation_error");return t?{publishableKey:t,paypalPublishableKey:e.data.stripe?.paypalPublishableKey??t}:{}}async function ta({publishableKey:e,paypalPublishableKey:t,billingApiUrl:n,locale:r,telemetry:o}){if(!e)return{flopay:null,paypalFlopay:null};let i=!!t&&t!==e,[d,c]=await Promise.all([(0,Gr.loadFloPay)(e,{billingApiUrl:n,locale:r,telemetry:o}),i?(0,Gr.loadFloPay)(t,{billingApiUrl:n,locale:r,telemetry:o}).catch(P=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",P),null)):Promise.resolve(null)]);return{flopay:d,paypalFlopay:t?i?c:d:null}}var dr=require("@flopay/js"),u=require("@flopay/shared"),Tt=require("@stripe/react-stripe-js"),a=Bi(require("react"),1);function es(e){let t=e??(typeof navigator<"u"?navigator.userAgent:"");return t?!!(/FBAN|FBAV|FB_IAB|FBIOS|Instagram|musical_ly|BytedanceWebview|TikTok/i.test(t)||/Twitter|Snapchat|Pinterest|LinkedInApp|Line\/|MicroMessenger|GSA\//i.test(t)||/Android.*;\s?wv\)/.test(t)||/(iPhone|iPad|iPod).*AppleWebKit(?!.*Safari)/.test(t)):!1}var ts={alipay:"https://cdn.flopay.com/sdk-logos/v1/alipay.svg",bancontact:"https://cdn.flopay.com/sdk-logos/v1/bancontact.svg",blik:"https://cdn.flopay.com/sdk-logos/v1/blik.svg",eps:"https://cdn.flopay.com/sdk-logos/v1/eps.svg",giropay:"https://cdn.flopay.com/sdk-logos/v1/giropay.svg",ideal:"https://cdn.flopay.com/sdk-logos/v1/ideal.svg",klarna:"https://cdn.flopay.com/sdk-logos/v1/klarna.svg",p24:"https://cdn.flopay.com/sdk-logos/v1/p24.svg",sepa_debit:"https://cdn.flopay.com/sdk-logos/v1/sepa_debit.svg",wechat_pay:"https://cdn.flopay.com/sdk-logos/v1/wechat_pay.svg"};var cr=require("react"),ns=require("react/jsx-runtime");function Xr({capture:e,html:t,messageToken:n,expectedOrigin:r,theme:o,containerStyle:i,onReady:d,onError:c,onValidation:P}){let y=(0,cr.useRef)(null),h=(0,cr.useRef)(d),v=(0,cr.useRef)(c),B=(0,cr.useRef)(P);h.current=d,v.current=c,B.current=P;let M=(0,cr.useRef)(o);return M.current=o,(0,cr.useEffect)(()=>{let m=y.current;if(!m)return;let S=!0,fe=!1,U=()=>{!S||fe||(fe=!0,h.current?.())},w=e.on("ready",()=>{U()}),ue=e.on("error",H=>{v.current?.(H.message??"There was a problem loading the secure card form.")}),q=e.on("validation",H=>{B.current?.(H.message??null)}),ce={html:t,...n?{messageToken:n}:{},...r?{expectedOrigin:r}:{},...M.current?{theme:M.current}:{}};return e.mount(m,ce).then(()=>{U()}).catch(H=>{S&&v.current?.(H instanceof Error?H.message:"Failed to load the secure card form.")}),()=>{S=!1,w(),ue(),q(),e.unmount()}},[e,t,n,r]),(0,cr.useEffect)(()=>{o&&e.applyTheme?.(o)},[e,o]),(0,ns.jsx)("div",{ref:y,"data-testid":"flopay-vault-card-fields",style:i})}function Zr(e,t=.12){let n=/^#?([0-9a-fA-F]{6})$/.exec(e.trim());if(!n)return e;let r=parseInt(n[1],16),o=Math.max(0,Math.min(1,1-t)),i=Math.round((r>>16&255)*o),d=Math.round((r>>8&255)*o),c=Math.round((r&255)*o);return`#${(1<<24|i<<16|d<<8|c).toString(16).slice(1)}`}function La(e){if(typeof e=="number"||typeof e=="string")return e}function na({appearance:e,buttonsStyles:t,layout:n="default"}){let r=e?.variables,o=y=>typeof y=="string"&&y?y:void 0,i=t.submitButton,d=o(r?.colorPrimary)??o(i?.backgroundColor)??"#4A49FF",c=n==="buttons",P=t.nameInput;return{primaryColor:d,primaryHoverColor:o(r?.colorPrimaryHover)??Zr(d,.12),inputBackgroundColor:o(t.cardInputBackground)??o(r?.colorBackground)??"#ffffff",textColor:o(t.cardInputColor)??o(P?.color)??o(r?.colorText)??"#262833",borderColor:o(t.cardInputBorder)??(c?"#e5e7eb":"#A4A4FF"),placeholderColor:o(t.cardInputPlaceholderColor)??"#9ca3af",errorColor:o(r?.colorDanger)??"#dc2626",successColor:"#16a34a",fontFamily:o(P?.fontFamily)??o(r?.fontFamily)??"Poppins, sans-serif",fontSize:o(t.cardInputFontSize)??o(r?.fontSizeBase)??"16px",fontWeight:String(La(P?.fontWeight)??400),borderRadius:o(r?.borderRadius)??"8px"}}var l=require("react/jsx-runtime"),er="flopay_stripe_resume",rs="flopay_wallet_resume";function us(e){return e instanceof u.FloPayError&&(e.type==="validation_error"||e.statusCode===400||e.statusCode===422)}async function oa(e,t,...n){let r=n[2].provider;t?.({class:"lifecycle",name:"payment.intent.started",provider:r});try{return await new dr.PaymentAPI(e).createSessionIntent(...n)}catch(o){throw us(o)||t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"intent_create",provider:r}),o}}var ko="flopay_paypal_resume",Sl=250,os="Just a moment \u2014 we are finalizing your order. Please press pay again.";function qa(e,t,n){e?.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:"provider_runtime",stage:"provider_load",provider:t,paymentMethodCategory:n,requestCategory:"provider_sdk"})}async function aa({billingApiUrl:e,sessionId:t,nonce:n,request:r}){if(!(!t||!n))try{await new dr.PaymentAPI(e,{telemetry:!1}).reportSessionIntentDecline(t,n,r)}catch{}}function wl(e){return e instanceof u.FloPayError&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function Na(e){return e?.html?{html:e.html,...e.messageToken?{messageToken:e.messageToken}:{},...e.expectedOrigin?{expectedOrigin:e.expectedOrigin}:{}}:null}function kl({event:e,fallbackEmail:t,fallbackName:n}){let r=e.billingDetails,o=Rr(r?.name),i=Rr(n);return pn({email:((0,u.isValidEmail)(t?.trim())?t?.trim():void 0)??r?.email?.trim(),firstName:i.firstName??o.firstName,lastName:i.lastName??o.lastName})}async function ps({event:e,prepared:t,email:n,billingName:r,methodLabel:o,collect:i}){let d=kl({event:e,fallbackEmail:t?.accountPatch?.email??n,fallbackName:[t?.accountPatch?.firstName,t?.accountPatch?.lastName].filter(Boolean).join(" ")||r});return(0,u.isValidEmail)(d.email)?d:i(o,d)}var Il=`
|
|
9
|
+
`})]})})}var Gi=require("@flopay/shared"),Gt=require("react");var Ji=require("react/jsx-runtime");function Po({flopay:e,paypalFlopay:t,options:n,onInstrument:r,children:o}){let[i,d]=(0,Gt.useState)(e instanceof Promise?null:e),[c,P]=(0,Gt.useState)(t instanceof Promise||!t?null:t),y=(0,Gt.useRef)(null),h=(0,Gt.useRef)(null),v=Hr(r);(0,Gt.useEffect)(()=>{v({class:"lifecycle",name:"checkout.mount"})},[v]),(0,Gt.useEffect)(()=>{i&&v({class:"lifecycle",name:"sdk.initialize.ready"})},[v,i]),(0,Gt.useEffect)(()=>{if(i)return Vt(i)?.subscribe?.(v)},[v,i]),(0,Gt.useEffect)(()=>{if(!(!c||c===i))return Vt(c)?.subscribe?.(v)},[v,i,c]),(0,Gt.useEffect)(()=>{if(!i)return;let m=Vt(i);return y.current=m?.beginCheckout()??m?.now()??0,m?.log({name:"checkout.mount",stage:"checkout_mount"}),()=>{m?.log({name:"checkout.unmount",stage:"unmount"})}},[i]),(0,Gt.useEffect)(()=>{let m=!1;return e instanceof Promise?e.then(S=>{m||d(S)},()=>{m||v({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"})}):d(e),()=>{m=!0}},[v,e]),(0,Gt.useEffect)(()=>{let m=!1;if(!t){P(null);return}return t instanceof Promise?t.then(S=>{m||P(S)},()=>{m||v({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED",provider:"paypal"})}):P(t),()=>{m=!0}},[v,t]),(0,Gt.useEffect)(()=>{if(!i||h.current===i)return;h.current=i;let m=Vt(i);m?.log({name:"checkout.rendered",stage:"checkout_render"}),v({class:"lifecycle",name:"checkout.rendered"}),m?.performance({stage:"checkout_render",durationMs:m.elapsed(y.current??0),durationMode:"machine"})},[v,i]);let B=(0,Gi.resolveBillingApiUrl)(n?.billingApiUrl),M=(0,Gt.useMemo)(()=>({flopay:i,paypalFlopay:c,billingApiUrl:B,emitInstrument:v}),[i,c,B,v]);return(0,Ji.jsx)(_n.Provider,{value:M,children:o})}var Xo="flopay_recent_completion_";function Wr(e){if(!(!e||typeof window>"u"))try{let t={expiresAt:Date.now()+6e4};window.sessionStorage.setItem(Xo+e,JSON.stringify(t))}catch{}}function Ba(e){if(!e||typeof window>"u")return!1;try{let t=window.sessionStorage.getItem(Xo+e);if(!t)return!1;let n=JSON.parse(t);return typeof n?.expiresAt!="number"||n.expiresAt<=Date.now()?(window.sessionStorage.removeItem(Xo+e),!1):!0}catch{return!1}}var Gr=require("@flopay/js"),Ue=require("@flopay/shared");var So="card";async function gl(e,t,n){if(n){if(typeof e.retrieveSetupIntent!="function")return null;let{setupIntent:i,error:d}=await e.retrieveSetupIntent(t);return{error:d,intent:i??null}}if(typeof e.retrievePaymentIntent!="function")return null;let{paymentIntent:r,error:o}=await e.retrievePaymentIntent(t);return{error:o,intent:r??null}}async function hl(e,t,n,r){if(r){if(typeof e.confirmCardSetup!="function")return null;let{setupIntent:d,error:c}=await e.confirmCardSetup(t,n);return{error:c,intent:d??null}}if(typeof e.confirmCardPayment!="function")return null;let{paymentIntent:o,error:i}=await e.confirmCardPayment(t,n);return{error:i,intent:o??null}}function Da(e,t){return Object.assign(e,{checkoutMethod:t})}function lr(e,t){let n=e instanceof Ue.FloPayError?e:new Ue.FloPayError(e instanceof Error?e.message:"Payment provider failed.","api_error",{code:"provider_runtime_failure"});return Object.assign(n,{checkoutMethod:t,telemetryFailureCategory:"provider_runtime",telemetryRequestCategory:"provider_sdk"})}async function Co(e,t){try{return await e()}catch(n){throw lr(n,t)}}function Xi(e){return!e?.type||!e.threeDSecureToken||e.type!=="3ds_required"&&e.type!=="paypal_redirect_required"?null:{type:e.type,threeDSecureToken:e.threeDSecureToken,paymentMethodId:e.paymentMethodId}}function bl(e){return e.status==="succeeded"||e.status==="declined"}async function Zi(e){if(typeof document>"u"||typeof window>"u")throw new Ue.FloPayError("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});if(e.signal?.aborted)throw new Ue.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"});let t=3e5,n=1e3,r=15e3,o=`${e.billingApiUrl.replace(/\/$/,"")}/v1/checkouts/sessions/${encodeURIComponent(e.sessionId)}/3ds/complete`,i=async()=>{let h=new AbortController,v=()=>h.abort();e.signal?.aborted?h.abort():e.signal?.addEventListener("abort",v);let B=window.setTimeout(()=>h.abort(),r);try{let M=await fetch(o,{method:"POST",headers:{"x-checkout-session-token":e.nonce,"content-type":"application/json"},body:"{}",signal:h.signal});if(!M.ok)return{status:"unknown"};let m=await M.json().catch(()=>null);return vl(m)}catch{return{status:"unknown"}}finally{window.clearTimeout(B),e.signal?.removeEventListener("abort",v)}},d=document.activeElement instanceof HTMLElement?document.activeElement:null,c=document.createElement("div");c.setAttribute("data-flopay-auto-3ds-overlay","1"),c.setAttribute("role","dialog"),c.setAttribute("aria-modal","true"),c.setAttribute("aria-label","Card authentication"),c.style.cssText=["position:fixed","inset:0","z-index:2147483647","background:rgba(15,23,42,0.6)","display:flex","align-items:center","justify-content:center","padding:16px"].join(";");let P=document.createElement("iframe");P.setAttribute("title","Card authentication"),P.setAttribute("allow","payment"),P.tabIndex=0,P.style.cssText=["width:min(100%,460px)","height:min(100%,640px)","border:0","border-radius:12px","background:#fff","box-shadow:0 12px 30px rgba(0,0,0,0.35)"].join(";"),P.src=e.nextActionRedirectUrl,c.appendChild(P),document.body.appendChild(c),P.focus();let y=null;try{y=new URL(e.billingApiUrl,window.location.href).origin}catch{y=null}try{let h=await new Promise((v,B)=>{let M=!1,m=0,S=0,he=0,U=!1,w=()=>{window.clearTimeout(m),window.clearInterval(S),window.clearTimeout(he),window.removeEventListener("message",H),P.removeEventListener("load",q),e.signal?.removeEventListener("abort",ce)},ue=async()=>{if(!(M||U)){U=!0;try{let fe=await i();if(M||!bl(fe))return;M=!0,w(),v(fe)}finally{U=!1}}},q=()=>{window.clearTimeout(he),he=window.setTimeout(()=>{ue()},250)},ce=()=>{M||(M=!0,w(),B(new Ue.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted"})))},H=fe=>{if(fe.source!==P.contentWindow||y&&fe.origin!==y)return;let $e=fe.data;!$e||typeof $e!="object"||$e.source!=="flopay-vault-3ds-return"||M||(M=!0,w(),v(null))};m=window.setTimeout(()=>{M||(M=!0,w(),B(new Ue.FloPayError("Card authentication timed out.","api_error",{code:"three_ds_timeout"})))},t),S=window.setInterval(()=>{ue()},n),P.addEventListener("load",q),window.addEventListener("message",H),e.signal?.addEventListener("abort",ce),e.signal?.aborted&&ce()});return h||await i()}finally{c.parentNode?.removeChild(c),d?.isConnected&&d.focus()}}function vl(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 Pr(e,t="Payment failed. Please try again.",n){let r=n?.checkoutMethod??e?.checkoutMethod??(e?.type==="paypal_redirect_required"?"paypal":"card"),o=e?.message??t,i=br(o)??o;return Da(new Ue.FloPayError(i,"api_error",{code:(0,Ue.normalizeCheckoutFailureOutcome)(e?.outcome)??(0,Ue.normalizeCheckoutFailureOutcome)(e?.type)??e?.gatewayErrorCode}),r)}function Fa(e){return typeof window<"u"&&window.location.href?window.location.href:e.successUrl||e.cancelUrl||void 0}function Zo(e){return typeof e=="string"&&e.startsWith("pi_")&&e.includes("_secret_")}function Qi(e,t){let n=[e?.threeDSecureToken,e?.clientSecret,e?.stripeClientSecret];for(let o of n)if(typeof o=="string"&&o.length>0&&(!t?.requirePaymentIntentClientSecret||Zo(o)))return o;let r=e?.data;if(r&&typeof r=="object"){let o=r,i=[o.threeDSecureToken,o.clientSecret,o.stripeClientSecret,o.id];for(let c of i)if(typeof c=="string"&&c.length>0&&(!t?.requirePaymentIntentClientSecret||Zo(c)))return c;let d=o.gateways;if(d&&typeof d=="object"){let c=d.stripe;if(c&&typeof c=="object"){let P=c,y=[P.stripeClientSecret,P.clientSecret];for(let h of y)if(typeof h=="string"&&h.length>0&&(!t?.requirePaymentIntentClientSecret||Zo(h)))return h}}}}async function Pl({billingApiUrl:e,sessionId:t,nonce:n,responseJson:r}){let o=Qi(r,{requirePaymentIntentClientSecret:!0});if(typeof o=="string"&&o.length>0)return{type:"3ds_required",threeDSecureToken:o};if(!t)return null;try{let c=(await new Gr.PaymentAPI(e,{telemetry:!1}).getUnifiedCheckoutSession(t,n)).data.stripe?.clientSecret;if(Zo(c))return{type:"3ds_required",threeDSecureToken:c}}catch{}return null}async function Jr({billingApiUrl:e,sessionId:t,session:n,nonce:r,tokenizedData:o,returnUrl:i,telemetry:d}){let c=e.replace(/\/+$/,""),P=t??n.id,y=r??n.clientSecret,h=n.customer?.id??n.accountData?.userId??"",v=n.customer?.email??n.accountData?.email??"",B=n.customer?.firstName??n.accountData?.firstName??"",M=n.customer?.lastName??n.accountData?.lastName??"",m=n.customer?.country??n.accountData?.country??void 0,S=n.customer?.zip??n.accountData?.zip??void 0,U=await new Gr.PaymentAPI(c,d===!1?{telemetry:!1}:void 0).processPayment(h,{sessionId:P,nonce:y,paymentMethodCategory:"saved",tokenizedData:o,accountData:{userId:h,email:v,firstName:B,lastName:M,country:m,zip:S},returnUrl:i??Fa(n)});if(U.ok){let q=typeof U.json=="function"?await U.json().catch(()=>null):null;return(0,Ue.isAuthorizationOnlySession)(n)||q?.status==="authorized"?{type:"success",result:{status:"authorized",paymentId:typeof q?.paymentId=="string"?q.paymentId:n.paymentId,sessionId:typeof q?.sessionId=="string"?q.sessionId:P,authorizationExpiresAt:typeof q?.authorizationExpiresAt=="string"?q.authorizationExpiresAt:n.authorizationExpiresAt,paymentMethodId:yo(o),checkoutMethod:o?o.isPaypal?"paypal":"card":void 0}}:{type:"success",result:{status:"succeeded",paymentIntentId:o?.threeDSecureActionResultTokenId,paymentMethodId:yo(o),checkoutMethod:o?o.isPaypal?"paypal":"card":void 0}}}let w;try{w=await U.json()}catch{throw new Ue.FloPayError("Payment failed. Please try again.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:U.status})}if(w?.type==="paypal_redirect_required"||w?.type==="3ds_required"){let q=Qi(w);if(!q)throw new Ue.FloPayError("Authentication is required but no redirect token was provided.","api_error",{code:"InvalidPaymentProcessResponse",statusCode:U.status});return{type:w.type,threeDSecureToken:q,paymentMethodId:w.paymentMethodId}}if(w?.gatewayErrorCode==="authentication_required"){let q=await Pl({billingApiUrl:c,sessionId:P,nonce:y,responseJson:w});if(q)return q;throw Da(new Ue.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card")}let ue=new Ue.FloPayError(w?.message??"Payment failed. Please try again.","api_error",{code:w?.code??w?.gatewayErrorCode,declineCode:w?.declineCode??w?.gatewayDeclineReason,statusCode:U.status});throw Object.assign(ue,{telemetryOutcome:(0,Ue.classifyPaymentRejection)(U.status,w)})}async function Qo(e,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:i,session:d,returnUrl:c,telemetry:P}){let y=t?.getRawProvider();if(!y)throw lr(new Ue.FloPayError("Payment provider is not available.","api_error"),"card");if(e.type==="3ds_required"){if(!r||!e.threeDSecureToken)throw Da(new Ue.FloPayError("Your card requires authentication. Please enter your payment details below.","api_error",{code:"authentication_required"}),"card");let h=(0,Ue.isSetupIntentClientSecret)(e.threeDSecureToken),v=null,B=e.paymentMethodId,M=await Co(()=>gl(y,e.threeDSecureToken,h),"card");if(M){if(M.error)throw lr(new Ue.FloPayError(M.error.message??`Failed to retrieve 3DS ${h?"setup":"payment"} status.`,"api_error",{code:M.error.code}),"card");let S=M.intent;!B&&S?.payment_method&&(typeof S.payment_method=="string"?B=S.payment_method:"id"in S.payment_method&&(B=S.payment_method.id??void 0))}let m=B?await Co(()=>hl(y,e.threeDSecureToken,{payment_method:B,return_url:c??Fa(d)??window.location.href},h),"card"):null;if(m){if(m.error)throw lr(new Ue.FloPayError(m.error.message??"3DS authentication failed.","api_error",{code:m.error.code}),"card");v=m.intent}else{let S=await Co(()=>y.handleNextAction({clientSecret:e.threeDSecureToken}),"card");if(S.error)throw lr(new Ue.FloPayError(S.error.message??"3DS authentication failed.","api_error",{code:S.error.code}),"card");v=(h?S.setupIntent:S.paymentIntent)??null}if(v&&(v.status==="requires_capture"||v.status==="succeeded"||v.status==="processing")){let S=await Jr({billingApiUrl:o,sessionId:i,session:d,telemetry:P,tokenizedData:{id:v.id,type:"card",threeDSecureActionResultTokenId:v.id},returnUrl:c});return S.type==="success"?{...S.result,paymentIntentId:S.result.paymentIntentId??v.id,paymentMethodId:S.result.paymentMethodId??B}:Qo(S,{flopay:t,paypalFlopay:n,attempt3DS:r,billingApiUrl:o,sessionId:i,session:d,returnUrl:c,telemetry:P})}throw lr(new Ue.FloPayError("3DS authentication did not complete successfully.","api_error"),"card")}if(e.type==="paypal_redirect_required"){let h=(n??t)?.getRawProvider();if(!h)throw lr(new Ue.FloPayError("PayPal is not available.","api_error"),"paypal");if(e.paymentMethodId){let{error:B}=await Co(()=>h.handleNextAction({clientSecret:e.threeDSecureToken}),"paypal");if(B)throw lr(new Ue.FloPayError(B.message??"PayPal authorization failed.","api_error",{code:B.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}let{error:v}=await Co(()=>h.confirmPayment({clientSecret:e.threeDSecureToken,confirmParams:{return_url:c??Fa(d)??window.location.href,payment_method_data:{type:"paypal"}},redirect:"if_required"}),"paypal");if(v)throw lr(new Ue.FloPayError(v.message??"PayPal authorization failed.","api_error",{code:v.code}),"paypal");return{status:"succeeded",checkoutMethod:"paypal"}}throw new Ue.FloPayError("Unsupported payment redirect state.","api_error")}function wo(e){if(e instanceof Ue.FloPayError){let r=br(e.message);return r&&r!==e.message?Object.assign(new Ue.FloPayError(r,e.type,{code:e.code,declineCode:e.declineCode,param:e.param,statusCode:e.statusCode}),{checkoutMethod:e.checkoutMethod,telemetryFailureCategory:e.telemetryFailureCategory,telemetryOutcome:e.telemetryOutcome,telemetryRequestCategory:e.telemetryRequestCategory}):e}let t=e instanceof Error?e.message:"Payment failed. Please try again.",n=br(t)??t;return new Ue.FloPayError(n,"api_error")}function ea(e){let t=e.data.stripe?.publishableKey,n=!!e.data.paypal?.publishableKey;if(!t&&!n)throw new Ue.FloPayError("Session advertises no supported gateways (expected `gateways.stripe` and/or `gateways.paypal`).","validation_error");return t?{publishableKey:t,paypalPublishableKey:e.data.stripe?.paypalPublishableKey??t}:{}}async function ta({publishableKey:e,paypalPublishableKey:t,billingApiUrl:n,locale:r,telemetry:o}){if(!e)return{flopay:null,paypalFlopay:null};let i=!!t&&t!==e,[d,c]=await Promise.all([(0,Gr.loadFloPay)(e,{billingApiUrl:n,locale:r,telemetry:o}),i?(0,Gr.loadFloPay)(t,{billingApiUrl:n,locale:r,telemetry:o}).catch(P=>(console.warn("[FloPay] Failed to load PayPal Stripe instance:",P),null)):Promise.resolve(null)]);return{flopay:d,paypalFlopay:t?i?c:d:null}}var dr=require("@flopay/js"),u=require("@flopay/shared"),Tt=require("@stripe/react-stripe-js"),a=Bi(require("react"),1);function es(e){let t=e??(typeof navigator<"u"?navigator.userAgent:"");return t?!!(/FBAN|FBAV|FB_IAB|FBIOS|Instagram|musical_ly|BytedanceWebview|TikTok/i.test(t)||/Twitter|Snapchat|Pinterest|LinkedInApp|Line\/|MicroMessenger|GSA\//i.test(t)||/Android.*;\s?wv\)/.test(t)||/(iPhone|iPad|iPod).*AppleWebKit(?!.*Safari)/.test(t)):!1}var ts={alipay:"https://cdn.flopay.com/sdk-logos/v1/alipay.svg",bancontact:"https://cdn.flopay.com/sdk-logos/v1/bancontact.svg",blik:"https://cdn.flopay.com/sdk-logos/v1/blik.svg",eps:"https://cdn.flopay.com/sdk-logos/v1/eps.svg",giropay:"https://cdn.flopay.com/sdk-logos/v1/giropay.svg",ideal:"https://cdn.flopay.com/sdk-logos/v1/ideal.svg",klarna:"https://cdn.flopay.com/sdk-logos/v1/klarna.svg",p24:"https://cdn.flopay.com/sdk-logos/v1/p24.svg",sepa_debit:"https://cdn.flopay.com/sdk-logos/v1/sepa_debit.svg",wechat_pay:"https://cdn.flopay.com/sdk-logos/v1/wechat_pay.svg"};var cr=require("react"),ns=require("react/jsx-runtime");function Xr({capture:e,html:t,messageToken:n,expectedOrigin:r,theme:o,containerStyle:i,onReady:d,onError:c,onValidation:P}){let y=(0,cr.useRef)(null),h=(0,cr.useRef)(d),v=(0,cr.useRef)(c),B=(0,cr.useRef)(P);h.current=d,v.current=c,B.current=P;let M=(0,cr.useRef)(o);return M.current=o,(0,cr.useEffect)(()=>{let m=y.current;if(!m)return;let S=!0,he=!1,U=()=>{!S||he||(he=!0,h.current?.())},w=e.on("ready",()=>{U()}),ue=e.on("error",H=>{v.current?.(H.message??"There was a problem loading the secure card form.")}),q=e.on("validation",H=>{B.current?.(H.message??null)}),ce={html:t,...n?{messageToken:n}:{},...r?{expectedOrigin:r}:{},...M.current?{theme:M.current}:{}};return e.mount(m,ce).then(()=>{U()}).catch(H=>{S&&v.current?.(H instanceof Error?H.message:"Failed to load the secure card form.")}),()=>{S=!1,w(),ue(),q(),e.unmount()}},[e,t,n,r]),(0,cr.useEffect)(()=>{o&&e.applyTheme?.(o)},[e,o]),(0,ns.jsx)("div",{ref:y,"data-testid":"flopay-vault-card-fields",style:i})}function Zr(e,t=.12){let n=/^#?([0-9a-fA-F]{6})$/.exec(e.trim());if(!n)return e;let r=parseInt(n[1],16),o=Math.max(0,Math.min(1,1-t)),i=Math.round((r>>16&255)*o),d=Math.round((r>>8&255)*o),c=Math.round((r&255)*o);return`#${(1<<24|i<<16|d<<8|c).toString(16).slice(1)}`}function La(e){if(typeof e=="number"||typeof e=="string")return e}function na({appearance:e,buttonsStyles:t,layout:n="default"}){let r=e?.variables,o=y=>typeof y=="string"&&y?y:void 0,i=t.submitButton,d=o(r?.colorPrimary)??o(i?.backgroundColor)??"#4A49FF",c=n==="buttons",P=t.nameInput;return{primaryColor:d,primaryHoverColor:o(r?.colorPrimaryHover)??Zr(d,.12),inputBackgroundColor:o(t.cardInputBackground)??o(r?.colorBackground)??"#ffffff",textColor:o(t.cardInputColor)??o(P?.color)??o(r?.colorText)??"#262833",borderColor:o(t.cardInputBorder)??(c?"#e5e7eb":"#A4A4FF"),placeholderColor:o(t.cardInputPlaceholderColor)??"#9ca3af",errorColor:o(r?.colorDanger)??"#dc2626",successColor:"#16a34a",fontFamily:o(P?.fontFamily)??o(r?.fontFamily)??"Poppins, sans-serif",fontSize:o(t.cardInputFontSize)??o(r?.fontSizeBase)??"16px",fontWeight:String(La(P?.fontWeight)??400),borderRadius:o(r?.borderRadius)??"8px"}}var l=require("react/jsx-runtime"),er="flopay_stripe_resume",rs="flopay_wallet_resume";function us(e){return e instanceof u.FloPayError&&(e.type==="validation_error"||e.statusCode===400||e.statusCode===422)}async function oa(e,t,...n){let r=n[2].provider;t?.({class:"lifecycle",name:"payment.intent.started",provider:r});try{return await new dr.PaymentAPI(e).createSessionIntent(...n)}catch(o){throw us(o)||t?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"intent_create",provider:r}),o}}var ko="flopay_paypal_resume",Cl=250,os="Just a moment \u2014 we are finalizing your order. Please press pay again.";function qa(e,t,n){e?.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:"provider_runtime",stage:"provider_load",provider:t,paymentMethodCategory:n,requestCategory:"provider_sdk"})}async function aa({billingApiUrl:e,sessionId:t,nonce:n,request:r}){if(!(!t||!n))try{await new dr.PaymentAPI(e,{telemetry:!1}).reportSessionIntentDecline(t,n,r)}catch{}}function Sl(e){return e instanceof u.FloPayError&&typeof e.statusCode=="number"&&e.statusCode>=400&&e.statusCode<500}function Na(e){return e?.html?{html:e.html,...e.messageToken?{messageToken:e.messageToken}:{},...e.expectedOrigin?{expectedOrigin:e.expectedOrigin}:{}}:null}function wl({event:e,fallbackEmail:t,fallbackName:n}){let r=e.billingDetails,o=Rr(r?.name),i=Rr(n);return pn({email:((0,u.isValidEmail)(t?.trim())?t?.trim():void 0)??r?.email?.trim(),firstName:i.firstName??o.firstName,lastName:i.lastName??o.lastName})}async function ps({event:e,prepared:t,email:n,billingName:r,methodLabel:o,collect:i}){let d=wl({event:e,fallbackEmail:t?.accountPatch?.email??n,fallbackName:[t?.accountPatch?.firstName,t?.accountPatch?.lastName].filter(Boolean).join(" ")||r});return(0,u.isValidEmail)(d.email)?d:i(o,d)}var kl=`
|
|
10
10
|
.paypal-buttons { margin: 0 !important; vertical-align: top !important; }
|
|
11
11
|
@keyframes flopay-spin { to { transform: rotate(360deg); } }
|
|
12
12
|
@keyframes flopay-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }
|
|
@@ -27,7 +27,7 @@ ${zt.join(`
|
|
|
27
27
|
0% { opacity: 1; transform: translateX(0) scale(1); }
|
|
28
28
|
100% { opacity: 0; transform: translateX(16px) scale(0.97); }
|
|
29
29
|
}
|
|
30
|
-
`,ra=44,Tr=280;function $a(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 Rl={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"},ms={width:"100%",minHeight:ra,margin:"0 0 0.5rem",padding:"0.75rem 0.875rem",border:"1px solid #2563eb",borderRadius:8,background:"#eff6ff",color:"#1d4ed8",fontSize:"0.95rem",fontWeight:700,cursor:"pointer"};function El(e){switch(e){case"paypal":return"PayPal";case"apple_pay":return"Apple Pay";case"google_pay":return"Google Pay";default:return"Card"}}function as(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function za(e){return e==="paypal"?"PayPal":(0,u.getStripeMethodDisplayName)(e)}function _l(e,t){let n=`We couldn't open ${za(e)}. Try again or choose another payment method.`;return t?`${n} Allow pop-ups for this site, then try again.`:n}function ys(e){let t=(0,a.useRef)(0),n=(0,a.useRef)(null),r=(0,a.useRef)(null),o=(0,a.useCallback)((m=r.current)=>{let S=m;S?.timer&&(clearTimeout(S.timer),S.timer=null)},[]),i=(0,a.useCallback)((m,S)=>{typeof document<"u"&&document.visibilityState!=="visible"||(o(m),m.timer=setTimeout(()=>{m.timer=null,r.current?.generation===m.generation&&(r.current=null,n.current=m.generation,e(m.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}))},S))},[o,e]),d=(0,a.useCallback)(m=>{m.yieldedControl&&i(m,600)},[i]),c=(0,a.useCallback)(m=>{o();let S=t.current+1;t.current=S,n.current=null;let fe={generation:S,method:m,timer:null,yieldedControl:!1};return r.current=fe,S},[o]),P=(0,a.useCallback)(m=>{let S=r.current;return typeof m=="number"&&S?.generation!==m?!1:(o(S),r.current=null,(typeof m!="number"||n.current===m)&&(n.current=null),!0)},[o]),y=(0,a.useCallback)(m=>{let S=r.current,fe=m??S?.generation??t.current;(!m||S?.generation===m)&&(o(S),r.current=null),n.current=fe},[o]),h=(0,a.useCallback)(m=>n.current===(m??t.current),[]),v=(0,a.useCallback)(m=>r.current?.generation===m&&n.current!==m,[]),B=(0,a.useCallback)(()=>{let m=r.current;m&&d(m)},[d]),M=(0,a.useCallback)(()=>{let m=r.current;m&&(m.yieldedControl=!0,o(m))},[o]);return(0,a.useEffect)(()=>{let m=()=>{document.visibilityState==="visible"?B():M()},S=()=>{M()};return document.addEventListener("visibilitychange",m),window.addEventListener("blur",S),window.addEventListener("focus",B),()=>{document.removeEventListener("visibilitychange",m),window.removeEventListener("blur",S),window.removeEventListener("focus",B),o()}},[o,M,B]),{startAttempt:c,finishAttempt:P,invalidateAttempt:y,isAttemptInvalidated:h,isAttemptCurrent:v}}function xl(e){let t=(0,u.getPostalCodeExample)(e);return`Enter a valid ${(0,u.getPostalCodeLabel)(e)}${t?` (e.g. ${t})`:""}`}function Tl(e,t,n){let r=(0,u.isPostalCodeSupported)(e),o=t.trim(),i=n&&r,d=i&&!o,c=i&&!!o&&!(0,u.isValidPostalCode)(e,o);return{visible:n,supported:r,required:i,empty:d,malformed:c}}function Ml(e,t){let n=e.trim(),r=t&&!n,o=t&&!!n&&!(0,u.isValidEmail)(n);return{required:t,empty:r,malformed:o,value:n}}function is(e,t){return t instanceof u.FloPayError?t:new u.FloPayError(t instanceof Error?t.message:`${El(e)} before-click hook failed.`,"validation_error")}function Oa(){return(0,l.jsx)("style",{children:Il})}function Al(e){return typeof e=="number"?`${e}px`:e}function fs(e,t){let n=e.availablePaymentMethods;return n&&t.some(r=>n[r])?"ready":"unavailable"}function gs({state:e,placeholderTestId:t,borderRadius:n=8,children:r}){return e==="unavailable"||e==="load_error"?null:(0,l.jsxs)("div",{style:{position:"relative",minHeight:44},children:[(0,l.jsx)("div",{"data-testid":t,"aria-hidden":e==="ready",style:{position:"absolute",inset:0,height:44,borderRadius:n,background:"#e5e7eb",animation:e==="ready"?void 0:"flopay-pulse 1.5s ease-in-out infinite",opacity:e==="ready"?0:1,transform:e==="ready"?"scale(0.985)":"scale(1)",transition:"opacity 140ms ease-out, transform 140ms ease-out",pointerEvents:"none"}}),(0,l.jsx)("div",{style:{minHeight:44,opacity:e==="ready"?1:0,transform:e==="ready"?"translateY(0)":"translateY(2px)",transition:"opacity 140ms ease-out, transform 140ms ease-out",pointerEvents:e==="ready"?"auto":"none"},children:r})]})}function ss(e){return e!=="unavailable"&&e!=="load_error"}function ia(e){return(0,l.jsx)(Fl,{...e})}function ls({sessionId:e,nonce:t,email:n,billingApiUrl:r,onTokenizedBody:o,onErrorChange:i,isProcessing:d=!1,onButtonClick:c,onDecline:P,onTechnicalFailure:y,runBeforeButtonClick:h,billingName:v,onBuyerIdentityReady:B,onLoadStateChange:M,placeholderBorderRadius:m}){let S=sr(),{emitInstrument:fe}=(0,a.useContext)(_n),U=(0,Tt.useStripe)(),w=(0,Tt.useElements)(),[ue,q]=(0,a.useState)("loading");(0,a.useEffect)(()=>{M?.(ue)},[ue,M]);let[ce,H]=(0,a.useState)(!1),ge=!(0,u.isValidEmail)(n?.trim())||!v?.trim(),{request:$e,collect:Se,finish:Pt}=jr(),ze=(0,a.useRef)(!1),Ie=(0,a.useRef)(null),Re=(0,a.useRef)(null),[ne,re]=(0,a.useState)(0),[L,Ee]=(0,a.useState)(!1),_e=(0,a.useRef)(!1),J=(0,a.useRef)(new Map),{startAttempt:we,finishAttempt:ve,invalidateAttempt:T,isAttemptInvalidated:O,isAttemptCurrent:Ae}=ys((ee,W,V)=>{y?.(ee,W,{...V,popupBlocked:V?.popupBlocked??vr(W)}),Ee(!0),re(Be=>Be+1)});(0,a.useEffect)(()=>{L&&Re.current?.focus()},[L,ne]);let ye=(0,a.useCallback)(()=>{re(ee=>ee+1)},[]),Q=(0,a.useCallback)((ee,W,V)=>{T(V),y?.("paypal",ee,{code:W,popupBlocked:vr(ee)}),Ee(!0),ye()},[T,y,ye]),Le=(0,a.useCallback)(()=>{window.setTimeout(()=>{(Ie.current?.querySelector("iframe")??Ie.current)?.focus()},0)},[]);(0,a.useEffect)(()=>{_e.current&&(_e.current=!1,Le())},[Le,ne]);let rt=(0,a.useCallback)(()=>{Ee(!1),i?.(null),Le()},[Le,i]);(0,a.useEffect)(()=>{if(!U||ze.current)return;let ee=new URLSearchParams(window.location.search),W=ee.get("payment_intent"),V=ee.get("payment_intent_client_secret"),Be=ee.get("redirect_status");if(!W||!V)return;ze.current=!0;let Je;try{let oe=localStorage.getItem(ko);if(oe){let F=JSON.parse(oe);F.clientSecret===V&&(Je={...F.accountPatch?{accountPatch:F.accountPatch}:{},...F.sessionId?{sessionId:F.sessionId}:{},...F.nonce?{nonce:F.nonce}:{}})}}catch{}try{localStorage.removeItem(ko)}catch{}let A=new URL(window.location.href);A.searchParams.delete("payment_intent"),A.searchParams.delete("payment_intent_client_secret"),A.searchParams.delete("redirect_status"),window.history.replaceState({},"",A.toString()),(async()=>{try{if(H(!0),Be==="failed"){let R="PayPal payment was declined. Please try again.";i?.(R),P?.(jt("paypal",R));return}let{paymentIntent:oe,error:F}=await U.retrievePaymentIntent(V);if(F){i?.(F.message??"Failed to retrieve PayPal payment status.");return}if(oe&&(oe.status==="requires_capture"||oe.status==="succeeded")){let R=typeof oe.payment_method=="string"?oe.payment_method:oe.payment_method?.id;o({id:R??oe.id,type:"card",threeDSecureActionResultTokenId:oe.id,isPaypal:!0},Je)}else{let R="PayPal payment was not completed. Please try again.";i?.(R),P?.(jt("paypal",R))}}catch(oe){i?.(oe instanceof Error?oe.message:"Failed to complete PayPal payment.")}finally{H(!1)}})()},[U,o,i,P]);let ct=(0,a.useCallback)(async ee=>{if(d||ce){ee.reject();return}let W=h?await h("paypal"):{proceed:!0};if(!W.proceed){J.current.delete(ne),ee.reject();return}let V=we("paypal");J.current.set(ne,{generation:V,accountPatch:W.accountPatch,sessionId:W.sessionId,nonce:W.nonce}),Ee(!1),c?.("paypal"),ee.resolve()},[d,c,h,we,ce,ne]),Oe=(0,a.useCallback)(async ee=>{if(!U||!w)return;let W=J.current.get(ne);if(W&&!Ae(W.generation)){J.current.delete(ne);return}if(!W&&O()||W&&!ve(W.generation))return;W||ve();let V=W??null;if(J.current.delete(ne),!V&&h){let R=await h("paypal");if(!R.proceed){ee.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}V={accountPatch:R.accountPatch,sessionId:R.sessionId,nonce:R.nonce}}let Be=V?.sessionId??e,Je=V?.nonce??t,A=await ps({event:ee,prepared:V,email:n,billingName:v,methodLabel:"PayPal",collect:Se});if(!A){ee.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let oe=A.email,F=pn({...V?.accountPatch,...A});try{if(H(!0),i?.(null),!Be||!(0,u.isValidEmail)(oe))throw new Error("Missing sessionId or email for PayPal payment");await B?.(A);let R=U.createPaymentMethod,{error:at,paymentMethod:Ct}=await R({type:"paypal"});if(at){Q(at,"stripe_paypal_create_payment_method_failed",W?.generation),ee.paymentFailed({reason:"fail"});return}let ke=await oa(r,fe,Be,Je??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:Ct?.id??null,intentKind:"payment"});if(ke.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let pt=ke.clientSecret,Fe={return_url:window.location.href};if(Ct?.id&&(Fe.payment_method=Ct.id),typeof window<"u")try{localStorage.setItem(ko,JSON.stringify({clientSecret:pt,sessionId:Be,nonce:Je,accountPatch:F}))}catch{}let{error:mt,paymentIntent:Et}=await U.confirmPayment({clientSecret:pt,confirmParams:Fe,redirect:"if_required"});if(mt){if(typeof window<"u")try{localStorage.removeItem(ko)}catch{}if(fo(mt)){let te=mt.message??"Your payment was declined.";i?.(te),P?.(jt("paypal",te,{code:ir(mt),declineCode:Kr(mt)})),await aa({billingApiUrl:r,sessionId:Be,nonce:Je,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:ir(mt)??"provider_declined"}})}else Q(mt,"stripe_paypal_confirm_failed",W?.generation);return}if(typeof window<"u")try{localStorage.removeItem(ko)}catch{}let C=typeof Et?.payment_method=="string"?Et.payment_method:Et?.payment_method?.id;o({id:C??Et?.id,type:"card",threeDSecureActionResultTokenId:Et?.id,isPaypal:!0},{accountPatch:F,sessionId:Be,nonce:Je});return}catch(R){Q(R,"stripe_paypal_failed",W?.generation)}finally{H(!1)}},[U,w,e,t,n,v,Se,B,r,fe,o,i,P,h,Q,ve,Ae,O,ne]);return(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(gs,{state:ue,placeholderTestId:"flopay-paypal-placeholder",borderRadius:m,children:(0,l.jsxs)("div",{ref:Ie,tabIndex:-1,"data-testid":"flopay-paypal-focus-target",role:"group","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[L&&(0,l.jsx)("button",{ref:Re,type:"button","data-testid":"flopay-paypal-retry-button",onClick:rt,style:ms,children:"Try PayPal again"}),$e&&(0,l.jsx)(Vr,{identity:$e.identity,methodLabel:$e.methodLabel,onComplete:Pt,onCancel:()=>Pt(null)},$e.id),(0,l.jsx)("div",{style:{display:$e?"none":void 0},children:(0,l.jsx)(Tt.ExpressCheckoutElement,{onReady:ee=>q(fs(ee,["paypal"])),onLoadError:()=>{q("load_error"),qa(Vt(S),"paypal","paypal")},onClick:ct,onConfirm:Oe,onCancel:()=>{let ee=J.current.get(ne);J.current.delete(ne),Vt(S)?.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),T(ee?.generation),Ee(!1),_e.current=!0,ye()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:ge,emailRequired:ge,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},ne)})]})}),ce&&(0,l.jsx)(Tn,{status:"processing"})]})}function cs({sessionId:e,nonce:t,email:n,billingApiUrl:r,intentKind:o,expressMethods:i,onTokenizedBody:d,onErrorChange:c,onButtonClick:P,onDecline:y,onTechnicalFailure:h,runBeforeButtonClick:v,billingName:B,onBuyerIdentityReady:M,onLoadStateChange:m,placeholderBorderRadius:S}){let fe=sr(),{emitInstrument:U}=(0,a.useContext)(_n),w=(0,Tt.useStripe)(),ue=(0,Tt.useElements)(),[q,ce]=(0,a.useState)("loading");(0,a.useEffect)(()=>{m?.(q)},[q,m]);let[H,ge]=(0,a.useState)(!1),$e=!(0,u.isValidEmail)(n?.trim())||!B?.trim(),{request:Se,collect:Pt,finish:ze}=jr(),Ie=(0,a.useRef)(null),Re=(0,a.useRef)(null),[ne,re]=(0,a.useState)(0),[L,Ee]=(0,a.useState)(!1),[_e,J]=(0,a.useState)("google_pay"),we=(0,a.useRef)(!1),ve=(0,a.useRef)("google_pay"),T=(0,a.useRef)("google_pay"),O=(0,a.useRef)(new Map),{startAttempt:Ae,finishAttempt:ye,invalidateAttempt:Q,isAttemptInvalidated:Le,isAttemptCurrent:rt}=ys((A,oe,F)=>{h?.(A,oe,{...F,popupBlocked:F?.popupBlocked??vr(oe)}),J(A),Ee(!0),re(R=>R+1)});(0,a.useEffect)(()=>{L&&Re.current?.focus()},[L,ne]);let ct=(0,a.useCallback)(()=>{re(A=>A+1)},[]),Oe=(0,a.useCallback)((A,oe,F,R)=>{Q(R),h?.(A,oe,{code:F,popupBlocked:vr(oe)}),J(A),Ee(!0),ct()},[Q,h,ct]),ee=(0,a.useCallback)(()=>{window.setTimeout(()=>{(Ie.current?.querySelector("iframe")??Ie.current)?.focus()},0)},[]);(0,a.useEffect)(()=>{we.current&&(we.current=!1,ee())},[ee,ne]);let W=(0,a.useCallback)(()=>{Ee(!1),c?.(null),ee()},[ee,c]),V=(0,a.useCallback)(async A=>{if(!w||!ue)return;let oe=O.current.get(ne);if(oe&&!rt(oe.generation)){O.current.delete(ne);return}if(!oe&&Le()||oe&&!ye(oe.generation))return;oe||ye();let F=A.expressPaymentType??oe?.method??ve.current,R=oe??null;O.current.delete(ne);let at=as(F);if(!R&&v){let C=await v(at);if(!C.proceed){A.paymentFailed({reason:"fail",message:"Wallet checkout was cancelled."});return}R={accountPatch:C.accountPatch,sessionId:C.sessionId,nonce:C.nonce}}let Ct=at,ke=R?.sessionId??e,pt=R?.nonce??t,Fe=await ps({event:A,prepared:R,email:n,billingName:B,methodLabel:za(F),collect:Pt});if(!Fe){A.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let mt=Fe.email,Et=pn({...R?.accountPatch,...Fe});try{if(ge(!0),c?.(null),!(0,u.isValidEmail)(mt))throw new Error("Missing sessionId or email for wallet payment");await M?.(Fe);let{error:C}=await ue.submit();if(C){Oe(F,C,"stripe_wallet_submit_failed",oe?.generation);return}let{error:te,paymentMethod:Xe}=await w.createPaymentMethod({elements:ue});if(te||!Xe){Oe(F,te??new Error("Failed to create payment method."),"stripe_wallet_create_payment_method_failed",oe?.generation);return}if(!ke)throw new Error("Missing sessionId or email for wallet payment");let He=await oa(r,U,ke,pt??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:F??at,paymentMethodId:Xe.id,intentKind:o});if(He.provider!=="stripe")throw new Error("Invalid provider returned for wallet intent");let zt=He.clientSecret,{error:Lt,intentId:G}=(0,u.isSetupIntentClientSecret)(zt)?await w.confirmCardSetup(zt,{payment_method:Xe.id}).then(dt=>({error:dt.error,intentId:dt.setupIntent?.id})):await w.confirmCardPayment(zt,{payment_method:Xe.id}).then(dt=>({error:dt.error,intentId:dt.paymentIntent?.id}));if(Lt){if(fo(Lt)){let dt=Lt.message??"Your payment was declined.";c?.(dt),y?.(jt(Ct,dt,{code:ir(Lt),declineCode:Kr(Lt)})),await aa({billingApiUrl:r,sessionId:ke,nonce:pt,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:F??at,providerDeclineReason:ir(Lt)??"provider_declined"}})}else Oe(F,Lt,"stripe_wallet_confirm_failed",oe?.generation);return}d({id:Xe.id,type:"card",threeDSecureActionResultTokenId:G},{accountPatch:Et,sessionId:ke,nonce:pt})}catch(C){Oe(F,C,"stripe_wallet_failed",oe?.generation)}finally{ge(!1)}},[w,ue,e,t,n,B,Pt,M,r,U,o,d,c,y,v,Oe,ye,rt,Le,ne]),Be=(0,a.useMemo)(()=>{let A=["applePay","googlePay","paypal","link","amazonPay","klarna"],oe=new Set(["applePay","googlePay"]),F=new Set(i.map(u.stripeExpressMethodToOptionKey)),R={};for(let at of A)F.has(at)?R[at]=oe.has(at)?"always":"auto":R[at]="never";return R},[i]),Je=(0,a.useMemo)(()=>i.map(u.stripeExpressMethodToOptionKey),[i]);return(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(gs,{state:q,placeholderTestId:"flopay-wallet-placeholder",borderRadius:S,children:(0,l.jsxs)("div",{ref:Ie,tabIndex:-1,"data-testid":"flopay-wallet-focus-target",role:"group","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[L&&(0,l.jsxs)("button",{ref:Re,type:"button","data-testid":"flopay-wallet-retry-button",onClick:W,style:ms,children:["Try ",za(_e)," again"]}),Se&&(0,l.jsx)(Vr,{identity:Se.identity,methodLabel:Se.methodLabel,onComplete:ze,onCancel:()=>ze(null)},Se.id),(0,l.jsx)("div",{style:{display:Se?"none":void 0},children:(0,l.jsx)(Tt.ExpressCheckoutElement,{onReady:A=>{ce(fs(A,Je))},onLoadError:A=>{ce("load_error"),qa(Vt(fe),"stripe","wallet")},onClick:async A=>{ve.current=A.expressPaymentType,T.current=as(A.expressPaymentType);let oe=v?await v(T.current):{proceed:!0};if(!oe.proceed){O.current.delete(ne),A.reject();return}let F=Ae(A.expressPaymentType);O.current.set(ne,{generation:F,method:A.expressPaymentType,accountPatch:oe.accountPatch,sessionId:oe.sessionId,nonce:oe.nonce}),Ee(!1),P?.(T.current),A.resolve()},onConfirm:V,onCancel:()=>{let A=O.current.get(ne);O.current.delete(ne),Vt(fe)?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet"}),Q(A?.generation),Ee(!1),we.current=!0,ct()},options:{buttonType:{applePay:"plain",googlePay:"plain"},paymentMethods:Be,emailRequired:$e,billingAddressRequired:$e,layout:{maxColumns:1,overflow:"never"}}},ne)})]})}),H&&(0,l.jsx)(Tn,{status:"processing"})]})}function Bl({method:e,themeId:t,submitting:n=!1,disabled:r=!1,highlighted:o=!1,hasNextStep:i=!1,onClick:d,backgroundColor:c,borderColor:P,textColor:y,borderRadius:h,fontFamily:v}){let B=(0,u.resolveStripeMethodBrandVariant)(e,t),M=ts[e],[m,S]=(0,a.useState)(!1),fe=B?.backgroundColor??c??"#ffffff",U=B?.borderColor??P??"#d1d5db",w=B?.textColor??y??"#262833";return(0,l.jsx)("button",{type:"button","data-testid":`flopay-stripe-method-button-${e}`,"data-method":e,onClick:()=>{!n&&!r&&d()},disabled:n||r,"aria-busy":n||void 0,style:{position:"relative",width:"100%",boxSizing:"border-box",height:ra,padding:"0 1rem",backgroundColor:fe,color:w,border:`1px solid ${U}`,borderRadius:h??8,fontSize:"0.95rem",fontWeight:600,fontFamily:v,cursor:n||r?"not-allowed":"pointer",opacity:r&&!n?.55:1,animation:n?"flopay-pulse 1.5s ease-in-out infinite":void 0,display:"flex",alignItems:"center",justifyContent:"center",gap:8,transition:"transform 0.1s, opacity 140ms ease-out, border-color 140ms ease-out",boxShadow:o?"0 0 0 2px rgba(74, 73, 255, 0.15)":void 0},children:n?(0,l.jsx)("span",{style:{margin:"0 auto"},children:`Connecting to ${(0,u.getStripeMethodDisplayName)(e)}\u2026`}):(0,l.jsxs)(l.Fragment,{children:[(0,l.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:(0,u.hasVendoredStripeMethodLogo)(e)?8:0},children:[M&&!m?(0,l.jsx)("img",{src:M,alt:"","aria-hidden":"true",onError:()=>S(!0),loading:"lazy",decoding:"async",width:30,height:20,style:{width:30,height:20,flexShrink:0,borderRadius:3,objectFit:"contain",display:"inline-flex"}}):B?.logoSvg?(0,l.jsx)("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:B.logoSvg}}):null,(0,l.jsx)("span",{children:(0,u.getStripeMethodDisplayName)(e)})]}),i&&(0,l.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:w,strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{position:"absolute",right:"1rem",top:"50%",transform:"translateY(-50%)",flexShrink:0,opacity:.7},"aria-hidden":"true",children:(0,l.jsx)("path",{d:"M9 18l6-6-6-6"})})]})})}function Ua({method:e,sessionId:t,nonce:n,email:r,billingName:o,onBuyerIdentityReady:i,billingApiUrl:d,onTokenizedBody:c,onErrorChange:P,onDecline:y,onCancel:h,runBeforeButtonClick:v,onButtonClick:B,isProcessing:M,submitButtonColor:m,submitButtonBorderRadius:S,submitButtonStyle:fe,errorText:U}){let w=sr(),{emitInstrument:ue}=(0,a.useContext)(_n),q=(0,Tt.useStripe)(),ce=(0,Tt.useElements)(),[H,ge]=(0,a.useState)(!1),$e=(0,a.useRef)(!1),[Se,Pt]=(0,a.useState)(!1),[ze,Ie]=(0,a.useState)("loading"),[Re,ne]=(0,a.useState)(""),re=!(0,u.isValidEmail)(r?.trim()),L=!re||(0,u.isValidEmail)(Re.trim()),Ee=(0,a.useCallback)(async()=>{if(!q||!ce||M||$e.current||!Se)return;$e.current=!0,ge(!0);let _e=v?await v("card"):{proceed:!0};if(!_e.proceed){$e.current=!1,ge(!1);return}B?.("card");let J=_e.sessionId??t,we=_e.nonce??n,ve=Rr(o?.trim()),T=pn({email:_e.accountPatch?.email?.trim()||r?.trim()||Re.trim(),firstName:_e.accountPatch?.firstName?.trim()||ve.firstName,lastName:_e.accountPatch?.lastName?.trim()||ve.lastName}),O=T.email,Ae=pn({..._e.accountPatch,...T});try{if(P?.(null),!(0,u.isValidEmail)(O))throw new Error("A valid email address is required for payment.");await i?.(T);let ye=await ce.submit();if(ye.error){P?.(ye.error.message??"Payment failed.");return}let Q=[T.firstName,T.lastName].filter(Boolean).join(" "),Le=await q.createPaymentMethod({elements:ce,params:{billing_details:{email:O,...Q?{name:Q}:{}}}});if(Le.error||!Le.paymentMethod){P?.(Le.error?.message??"Failed to create payment method.");return}let rt=Le.paymentMethod;if(!J||!O)throw new Error("Missing sessionId or email for payment.");let ct=rt.type||e,Oe=await oa(d,ue,J,we??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:ct,paymentMethodId:null,intentKind:"payment"});if(Oe.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let ee=Oe.clientSecret;if(typeof window<"u")try{localStorage.setItem(er,JSON.stringify({clientSecret:ee,sessionId:J,nonce:we,accountPatch:Ae,paymentMethodId:rt.id,paymentMethodType:rt.type??e,gateway:"stripe"}))}catch{}let{error:W,paymentIntent:V}=await q.confirmPayment({clientSecret:ee,confirmParams:{return_url:window.location.href,payment_method:rt.id},redirect:"if_required"});if(W){if(typeof window<"u")try{localStorage.removeItem(er)}catch{}let A=W.message??"Payment failed.";P?.(A),y?.(jt("card",A,{code:W.code})),await aa({billingApiUrl:d,sessionId:J,nonce:we,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:W.code??"provider_declined"}});return}let Be=V?.status;if(!Ko(Be)){if(typeof window<"u")try{localStorage.removeItem(er)}catch{}let A=Be==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";P?.(A),y?.(jt("card",A,{code:Be??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(er)}catch{}let Je=typeof V?.payment_method=="string"?V.payment_method:V?.payment_method?.id;c({id:Je??rt.id,type:"card",threeDSecureActionResultTokenId:V?.id,gateway:"stripe",paymentMethodType:rt.type??e},{accountPatch:Ae,sessionId:J,nonce:we})}catch(ye){P?.(ye instanceof Error?ye.message:"Payment failed. Please try again.")}finally{$e.current=!1,ge(!1)}},[q,ce,M,Se,v,B,t,n,r,o,Re,i,d,ue,e,c,P,y]);return(0,l.jsxs)("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[re&&(0,l.jsx)("div",{"data-testid":"flopay-apm-identity-fields",style:{display:"flex",flexDirection:"column",gap:"0.75rem",marginBottom:"0.75rem"},children:re&&(0,l.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",(0,l.jsx)("input",{type:"email",autoComplete:"email",required:!0,value:Re,onChange:_e=>ne(_e.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]})}),(0,l.jsx)(Tt.PaymentElement,{onReady:()=>Ie("ready"),onLoadError:()=>{Ie("load_error"),qa(Vt(w),"stripe","apm")},onChange:_e=>{Pt(!!_e.complete)},options:{layout:{type:"accordion",defaultCollapsed:!1,radios:"never"},fields:{billingDetails:{email:"never"}},defaultValues:{billingDetails:{...o?.trim()?{name:o.trim()}:{},...(0,u.isValidEmail)(r?.trim())?{email:r?.trim()}:{}}}}}),(0,l.jsx)("button",{type:"button","data-testid":`flopay-stripe-method-pay-${e}`,onClick:()=>{Ee()},disabled:!Se||!L||H||M||ze!=="ready",style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:m,color:"white",border:"none",borderRadius:S,fontSize:"1rem",fontWeight:600,cursor:!Se||!L||H||M||ze!=="ready"?"not-allowed":"pointer",opacity:!Se||!L||H||M||ze!=="ready"?.5:1,transition:"opacity 120ms ease-out",...fe??{}},children:H?"Processing\u2026":`Pay with ${(0,u.getStripeMethodDisplayName)(e)}`}),U&&(0,l.jsx)(Yr,{margin:"0.75rem 0 0",children:U})]})}function ds({sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:i,paymentElementMethods:d,stripeInstance:c,paymentElementBaseOptions:P,onTokenizedBody:y,onErrorChange:h,onButtonClick:v,onDecline:B,runBeforeButtonClick:M,onLoadStateChange:m,isProcessing:S=!1,submitButtonColor:fe="#4A49FF",submitButtonBorderRadius:U=8,submitButtonStyle:w,buttonAppearance:ue,themeId:q,onExpandApm:ce,expandedApmMethod:H}){let{emitInstrument:ge}=(0,a.useContext)(_n),[$e,Se]=(0,a.useState)(null),[Pt,ze]=(0,a.useState)(null),Ie=(0,a.useRef)(!1),{request:Re,collect:ne,finish:re}=jr();(0,a.useEffect)(()=>{d.length>0&&c?m?.("ready"):c||m?.("loading")},[d.length,c,m]);let L=(0,a.useCallback)(async T=>{if(!c||Ie.current||S)return;Ie.current=!0,ze(T);let O=M?await M("card"):{proceed:!0};if(!O.proceed){Ie.current=!1,ze(null);return}v?.("card");let Ae=O.sessionId??e,ye=O.nonce??t,Q=Rr([O.accountPatch?.firstName,O.accountPatch?.lastName].filter(Boolean).join(" ")||r),Le=pn({email:O.accountPatch?.email?.trim()||n?.trim(),firstName:O.accountPatch?.firstName?.trim()||Q.firstName,lastName:O.accountPatch?.lastName?.trim()||Q.lastName});if(!(0,u.isValidEmail)(Le.email)){ze(null);let Oe=await ne((0,u.getStripeMethodDisplayName)(T),Le);if(!Oe){Ie.current=!1;return}Le=Oe,ze(T)}let rt=Le.email,ct=pn({...O.accountPatch,...Le});try{if(h?.(null),!Ae||!(0,u.isValidEmail)(rt))throw new Error("Missing sessionId or email for payment.");await o?.(Le);let Oe=await oa(i,ge,Ae,ye??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:T,paymentMethodId:null,intentKind:"payment"});if(Oe.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let ee=Oe.clientSecret;if(typeof window<"u")try{localStorage.setItem(er,JSON.stringify({clientSecret:ee,sessionId:Ae,nonce:ye,accountPatch:ct,paymentMethodType:T,gateway:"stripe"}))}catch{}let{error:W,paymentIntent:V}=await c.confirmPayment({clientSecret:ee,confirmParams:{return_url:window.location.href,payment_method_data:{type:T,billing_details:{name:[Le.firstName,Le.lastName].filter(Boolean).join(" "),...rt?{email:rt}:{}}}},redirect:"if_required"});if(W){if(typeof window<"u")try{localStorage.removeItem(er)}catch{}let A=W.message??"Payment failed.";h?.(A),B?.(jt("card",A,{code:W.code})),await aa({billingApiUrl:i,sessionId:Ae,nonce:ye,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:T,providerDeclineReason:W.code??"provider_declined"}});return}let Be=V?.status;if(!Ko(Be)){if(typeof window<"u")try{localStorage.removeItem(er)}catch{}let A=Be==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";h?.(A),B?.(jt("card",A,{code:Be??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(er)}catch{}let Je=typeof V?.payment_method=="string"?V.payment_method:V?.payment_method?.id;y({id:Je??V?.id,type:"card",threeDSecureActionResultTokenId:V?.id,gateway:"stripe",paymentMethodType:T},{accountPatch:ct,sessionId:Ae,nonce:ye})}catch(Oe){h?.(Oe instanceof Error?Oe.message:"Payment failed. Please try again.")}finally{Ie.current=!1,ze(null)}},[c,S,M,v,e,t,n,ne,i,ge,r,o,y,h,B]),[Ee,_e]=(0,a.useState)(null),J=ce?H??null:Ee,we=(0,a.useCallback)(T=>{Ie.current||S||J&&J!==T||((0,u.needsStripeMethodExplicitConfirm)(T)?ce?ce(T):_e(T):L(T))},[J,S,L,ce]),ve=(0,a.useMemo)(()=>Ee?{...P,paymentMethodTypes:[Ee]}:null,[Ee,P]);return(0,l.jsx)("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:Re?(0,l.jsx)(Vr,{identity:Re.identity,methodLabel:Re.methodLabel,onComplete:re,onCancel:()=>re(null)},Re.id):d.map(T=>{let O=H===T,Ae=Pt===T,ye=Pt!==null&&Pt!==T||H!=null&&H!==T;return(0,l.jsxs)(a.default.Fragment,{children:[(0,l.jsx)(Bl,{method:T,themeId:q,submitting:Ae,disabled:ye,highlighted:O,hasNextStep:(0,u.needsStripeMethodExplicitConfirm)(T),onClick:()=>we(T),backgroundColor:ue?.backgroundColor,borderColor:ue?.borderColor,textColor:ue?.textColor,borderRadius:ue?.borderRadius,fontFamily:ue?.fontFamily}),!ce&&Ee===T&&ve&&c&&(0,l.jsx)(Tt.Elements,{stripe:c,options:ve,children:(0,l.jsx)(Ua,{method:T,sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:i,onTokenizedBody:y,onErrorChange:h,onDecline:B,onCancel:()=>_e(null),runBeforeButtonClick:M,onButtonClick:v,isProcessing:S,submitButtonColor:fe,submitButtonBorderRadius:U,submitButtonStyle:w})},T)]},T)})})}function Fl({sessionId:e,nonce:t,billingApiUrl:n,email:r,userId:o,onComplete:i,onError:d,onDecline:c,onTokenizedBody:P,firstName:y,lastName:h,chv:v,className:B,isProcessing:M,error:m,onErrorChange:S,showPayPal:fe=!0,showStripe:U=!0,enabledPaymentMethods:w,enabledPaymentMethodCountries:ue,showApplePay:q=!0,showGooglePay:ce=!0,layout:H="default",theme:ge,buttonsTheme:$e,buttonsStyles:Se,appearance:Pt,cardButtonContent:ze,cardBackButtonContent:Ie,cardTitleContent:Re,showSecurityFooter:ne,onButtonClick:re,onBeforeButtonClick:L,onBuyerIdentityReady:Ee,enableAVS:_e,cardFieldOrder:J,cardPreFormSlot:we,avsLayout:ve="row",country:T,zip:O,addressLine1:Ae,addressLine2:ye,city:Q,state:Le,onCountryChange:rt,onZipChange:ct,avsCheck:Oe,checkoutType:ee,checkoutLayout:W,totalAmount:V=0,currency:Be="usd",initialCardOpen:Je=!1,directPaypal:A,isSubscription:oe=!1,session:F,dataAttachmentPending:R=!1,dataAttachmentRequiresIdentity:at=!1,debug:Ct=!1}){let ke=sr(),pt=Ho(),Fe=(0,a.useContext)(Kn),{emitInstrument:mt}=(0,a.useContext)(_n),Et=F??Fe.session,C=Et?.gateways?.paypal?.providerObjectType??A?.providerObjectType,te=R||Fe.claimPending===!0,Xe=at||Fe.claimRequiresIdentity===!0,He=te&&!Xe,zt=$i(),[Lt,G]=(0,a.useState)(!1),[dt,Qt]=(0,a.useState)(null),[gt,Ut]=(0,a.useState)(T??"US"),[An,Bn]=(0,a.useState)(O??""),[Fn,Jt]=(0,a.useState)(Ae??""),[Wn,mn]=(0,a.useState)(ye??""),[qt,rr]=(0,a.useState)(Q??""),[wt,Dn]=(0,a.useState)(Le??""),[it,pr]=(0,a.useState)(""),[kt,Pn]=(0,a.useState)({}),It=(0,a.useRef)(O??""),Kt=(0,a.useRef)(T??"US"),yn=(0,a.useRef)(Ae??""),on=(0,a.useRef)(ye??""),Cn=(0,a.useRef)(Q??""),en=(0,a.useRef)(Le??""),Sn=(0,a.useRef)(""),Nt=(0,a.useRef)({});(0,a.useEffect)(()=>{let s=(x,j,Ne,Y,De)=>{if(Nt.current[x])return;let Ke=j?.trim();!Ke||Ke===Ne.current||(Ne.current=Ke,Y(Ke),De?.(Ke))};s("country",T,Kt,Ut,rt),s("zip",O,It,Bn,ct),s("addressLine1",Ae,yn,Jt),s("addressLine2",ye,on,mn),s("city",Q,Cn,rr),s("state",Le,en,Dn)},[T,O,Ae,ye,Q,Le,rt,ct]);let se=(0,a.useMemo)(()=>(0,u.resolveAVSConfig)(_e),[_e]),an=se!==null,Ln=(0,a.useMemo)(()=>(0,u.isAuthorizationOnlySession)(F),[F]),Gn=!!F?.vault?.html,Cr=!!F?.gateways?.pcivault,mr=!!(F?.gateways?.stripe?.enabledPaymentMethods??w)?.includes("card"),Mt=Gn||mr||Cr,Ye=!!(U&&Mt&&ke&&e),[yr,E]=(0,a.useState)(()=>H!=="buttons"||Je?e??null:null),[ot,$t]=(0,a.useState)(0),fn=H!=="buttons"||Je||!!e&&yr===e,Pe=(0,a.useMemo)(()=>!ke||!Ye||!e||!fn?null:ke.cardCapture({sessionId:e,captureMethod:F?.captureMethod}),[ke,Ye,e,fn,F?.captureMethod]),tn=(0,a.useMemo)(()=>{let s=gt,x=se?(0,u.isAVSFieldVisible)(se.postal_code,s):!1;return Tl(s,An,x)},[se,gt,An]),{avsInvalid:wr,invalidAvsFields:Br}=(0,a.useMemo)(()=>{let s={line1:!1,city:!1,state:!1,zip:!1};if(!Ye||!se)return{avsInvalid:!1,invalidAvsFields:s};let x=gt,j=(De,Ke)=>(0,u.isAVSFieldVisible)(De,x)&&!Ke.trim(),Ne={line1:j(se.address_line_1,Fn),city:j(se.city,qt),state:j(se.state,wt),zip:tn.empty||tn.malformed};return{avsInvalid:Ne.line1||Ne.city||Ne.state||Ne.zip,invalidAvsFields:Ne}},[Ye,se,gt,Fn,qt,wt,tn]),[sn,fr]=(0,a.useState)(!1),[Jn,Nn]=(0,a.useState)(!1),[At,On]=(0,a.useState)(!1),[Xn,ln]=(0,a.useState)({line1:!1,city:!1,state:!1}),Xt=(0,a.useRef)(!1),zn=(0,a.useRef)({email:!1,line1:!1,city:!1,state:!1,zip:!1}),Un=(0,a.useRef)(!1),st=(0,a.useCallback)(s=>{zn.current[s]=!0,Un.current=!0},[]),cn=(0,a.useCallback)(s=>!Xt.current&&zn.current[s],[]),dn=(0,a.useCallback)(s=>{cn(s)&&ln(x=>x[s]?x:{...x,[s]:!0})},[cn]),[qn,wn]=(0,a.useState)(()=>Na(F?.vault)),[xe,Zt]=(0,a.useState)(Je&&Mt?"card":"buttons"),[Bt,gr]=(0,a.useState)(null),$n=xe==="expanding"||xe==="card",hr=F?.gateways?.stripe?"stripe":void 0,gn=(0,a.useCallback)(()=>{mt?.({class:"card_surface",provider:hr})},[hr,mt]),kn=(0,a.useRef)(null),Ft=(0,a.useCallback)(s=>{kn.current&&clearTimeout(kn.current),kn.current=setTimeout(()=>{kn.current=null,s()},Tr)},[]);(0,a.useEffect)(()=>()=>{kn.current&&clearTimeout(kn.current)},[]);let N=(0,a.useCallback)(()=>{gn(),E(e??null),$t(s=>s+1),Zt("expanding"),Ft(()=>Zt("card"))},[Ft,gn,e]),$=(0,a.useCallback)(()=>{Zt("collapsing"),Ft(()=>Zt("buttons"))},[Ft]),ae=(0,a.useCallback)(s=>{gr(s),Zt("apm-expanding"),Ft(()=>Zt("apm-form"))},[Ft]),ie=(0,a.useCallback)(()=>{Zt("apm-collapsing"),Ft(()=>{Zt("buttons"),gr(null)})},[Ft]);(0,a.useEffect)(()=>{H==="buttons"&&Je&&Mt&&(E(e??null),Zt("card"))},[H,Je,Mt,e]);let[Te,z]=(0,a.useState)(null),X=(0,a.useRef)(!1),f=(0,a.useRef)(null),K=(0,a.useRef)("idle"),[Z,ut]=(0,a.useState)(null),yt=(0,a.useRef)(Z);(0,a.useEffect)(()=>{yt.current=Z},[Z]);let de=n||zt,Me=(0,a.useRef)(null),Ht=(0,a.useMemo)(()=>{if(Ee||Fe.claimBuyerIdentity||F?.buyerIdentified!==!1||!e||!t)return;let s=`${de}|${e}|${t}`;Me.current?.key!==s&&(Me.current={key:s,claim:qr(new dr.PaymentAPI(de,{telemetry:!1}),e,t,{...o?{userId:o}:{},...y?{firstName:y}:{},...h?{lastName:h}:{}})});let x=Me.current.claim;return async j=>{await x(j)}},[Ee,Fe.claimBuyerIdentity,F?.buyerIdentified,e,t,de,o,y,h]),tt=Ee??Fe.claimBuyerIdentity??Ht,g=m??dt,p=(0,a.useMemo)(()=>(0,u.resolveTheme)(ge),[ge]),b=(0,a.useMemo)(()=>{let s=p?.buttonsLayout??(0,u.resolveButtonsLayoutTheme)($e);return Se?{...s,...Se,cardButton:{...s.cardButton,...Se.cardButton},cardFormContainer:{...s.cardFormContainer,...Se.cardFormContainer},backButton:{...s.backButton,...Se.backButton},backButtonIcon:{...s.backButtonIcon,...Se.backButtonIcon},submitButton:{...s.submitButton,...Se.submitButton},title:{...s.title,...Se.title}}:s},[p,$e,Se]),Ce=Pt??p?.appearance,pe=(0,a.useMemo)(()=>na({appearance:Ce,buttonsStyles:b,layout:H}),[Ce,b,H]),We=Fe.inlineSessionPatchProcessing??!1,Ze=(M??Lt)||We,le=de.replace(/\/+$/,""),D=(0,a.useMemo)(()=>xa({userId:o,email:r,firstName:y,lastName:h,country:T,zip:O},kt),[o,r,y,h,T,O,kt]),me=[D.firstName,D.lastName].filter(s=>!!s?.trim()).join(" "),Ge=!(0,u.isValidEmail)(D.email?.trim()),je=(0,a.useRef)(null);Ye&&je.current===null&&(je.current=Ge);let ft=Ye&&(je.current??Ge),Ve=(0,a.useMemo)(()=>Ml(it,ft),[it,ft]),Ot=Ve.empty||Ve.malformed,hn=(0,a.useMemo)(()=>ke?ke.getRawProvider():null,[ke]),Fr=(0,a.useMemo)(()=>pt?pt.getRawProvider():null,[pt]),Qr=V||100,xo=(0,a.useMemo)(()=>Ce?(0,dr.toStripeAppearance)(Ce):null,[Ce]),To=xo?{appearance:xo}:null,ei=(0,a.useMemo)(()=>{let s=xo??{},x=s.rules??{};return{...s,rules:{...x,".AccordionItem":{padding:"10px 14px",boxShadow:"none",...x[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",...x[".AccordionItemContents"]??{}}}}},[xo]),ti=(0,a.useMemo)(()=>{let s=Oi(V);return{...s,currency:Be.toLowerCase(),paymentMethodCreation:"manual",...s.mode==="payment"?{captureMethod:"manual"}:{},...To}},[V,Be,To]),ni=(0,a.useMemo)(()=>({mode:"payment",amount:Qr,currency:Be.toLowerCase(),captureMethod:"manual",setupFutureUsage:"off_session",...To}),[Qr,Be,To]),he=(0,a.useCallback)(s=>{Qt(s),S?.(s)},[S]),ma=(0,a.useRef)(""),[ri,Es]=(0,a.useState)(!1),ya=(0,a.useCallback)(()=>{Es(!0)},[]);(0,a.useEffect)(()=>{if(!Ye||!ft||!tt||!ri||Ot||ma.current)return;let s=pn({email:(0,u.isValidEmail)(D.email?.trim())?D.email?.trim():Sn.current.trim(),firstName:D.firstName?.trim(),lastName:D.lastName?.trim()});ma.current=JSON.stringify(s),Pn(x=>({...x,...s})),Promise.resolve(tt(s)).catch(x=>{ma.current="",he(x instanceof Error?x.message:"Failed to attach buyer details.")})},[Ye,ft,tt,ri,Ot,D.email,D.firstName,D.lastName,he]),(0,a.useEffect)(()=>{!Ye||!Pe||Pe.setCardFieldOrder?.(J??null,se==null&&!ft)},[Ye,Pe,J,se,ft]),(0,a.useEffect)(()=>{(xe==="expanding"||xe==="collapsing"||xe==="apm-expanding"||xe==="apm-collapsing")&&he(null)},[xe,he]);let jn=(0,a.useCallback)((s,x,j)=>{c?.(jt(s,x,j))},[c]),Dr=(0,a.useCallback)((s,x,j)=>{let Ne=j?.popupBlocked??vr(x),Y=_l(s,Ne),De=_r(j?.code)??ir(x)??"external_payment_method_failed",Ke=new u.FloPayError(Y,"api_error",{code:"external_payment_method_failed",param:s});z(null),H==="buttons"&&(Zt("buttons"),gr(null)),he(Y),d?.(Ke),console.error("[FloPay] External payment method failed:",{method:s,code:De,popupBlocked:Ne})},[H,d,he]);(0,a.useEffect)(()=>{if(!Ye||!e){wn(null);return}let s=Na(F?.vault);if(s){wn(s);return}if(!fn){wn(null);return}wn(null);let x=!0;return new dr.PaymentAPI(le).getVaultCapture(e,t).then(j=>{if(!x)return;let Ne=Na(j);Ne?wn(Ne):he("Failed to load the secure card form.")}).catch(j=>{x&&he(j instanceof Error?j.message:"Failed to load the secure card form.")}),()=>{x=!1}},[Ye,fn,ot,e,F?.vault,le,t,he]);let Zn=(0,a.useRef)({onComplete:i,onError:d,updateError:he,emitDecline:jn,resolvedAccount:D,avsConfig:se,avsCheckProp:Oe,sessionId:e,nonce:t,baseUrl:le,captureMethod:F?.captureMethod,paymentId:F?.paymentId,authorizationExpiresAt:F?.authorizationExpiresAt});Zn.current={onComplete:i,onError:d,updateError:he,emitDecline:jn,resolvedAccount:D,avsConfig:se,avsCheckProp:Oe,sessionId:e,nonce:t,baseUrl:le,captureMethod:F?.captureMethod,paymentId:F?.paymentId,authorizationExpiresAt:F?.authorizationExpiresAt};let fa=(0,a.useRef)(!1),oi=(0,a.useCallback)(()=>{let{resolvedAccount:s,avsConfig:x,avsCheckProp:j}=Zn.current,Ne=s.email?.trim(),Y=(0,u.isValidEmail)(Ne)?Ne:Sn.current.trim();if(!(0,u.isValidEmail)(Y))return null;let De=s.firstName?.trim(),Ke=s.lastName?.trim(),lt=Kt.current||s.country||"US",Yt=x?(0,u.isAVSFieldVisible)(x.state,lt):!1,ht=x?(0,u.isAVSFieldVisible)(x.address_line_1,lt):!1,bt=x?(0,u.isAVSFieldVisible)(x.postal_code,lt):!1,nt=x?(0,u.isAVSFieldVisible)(x.city,lt):!1,nn=x?(0,u.isAVSFieldVisible)(x.address_line_2,lt):!1,Qe=ht&&!Yt&&bt?(0,u.getStateFromPostalCode)(lt,(It.current??"").trim()):null,rn=Yt?en.current:Qe;return{accountData:{userId:s.userId??"",email:Y,...De?{firstName:De}:{},...Ke?{lastName:Ke}:{},...bt&&It.current?{zip:It.current}:{},...nt&&Cn.current?{city:Cn.current}:{},...rn?{state:rn}:{},...ht&&yn.current?{addressLine1:yn.current}:{},...nn&&on.current?{addressLine2:on.current}:{},country:lt},...j!==void 0?{avsCheck:j}:{},...x?{avsConfig:{country:(0,u.isAVSFieldVisible)(x.country,lt),postal_code:bt,address_line_1:ht,address_line_2:nn,city:nt,state:Yt}}:{}}},[]),ai=(0,a.useRef)(te);ai.current=te,(0,a.useEffect)(()=>{te||g!==os||Zn.current.updateError(null)},[te,g]),(0,a.useEffect)(()=>{!Ye||!Pe||Pe.setSubmitGate?.(wr||te||Ot)},[Ye,Pe,wr,te,Ot]),(0,a.useEffect)(()=>{if(!Ye||!Pe)return;fa.current=!1;let s=!1,x=Pe.on("submitting",()=>{fr(!0),f.current&&clearTimeout(f.current),K.current="validation-window",f.current=setTimeout(()=>{f.current=null,K.current==="validation-window"&&(K.current="processing")},Sl),z("processing");let{baseUrl:Ke,sessionId:lt,nonce:Yt,updateError:ht,onError:bt}=Zn.current;if(!lt||!Yt)return;let nt=oi();if(!nt){ht("Enter a valid email address."),K.current="idle",z(null);return}new dr.PaymentAPI(Ke).patchAccountSnapshot(lt,Yt,nt,{telemetryMode:"best_effort"}).catch(nn=>{if(!wl(nn))return;let Qe=nn instanceof Error?nn.message:"Please check your billing address and try again.";ht(Qe),K.current="idle",z(null),bt?.(nn instanceof u.FloPayError?nn:new u.FloPayError(Qe,"api_error"))})}),j=Pe.on("complete",async Ke=>{if(Wr(Ke.sessionId??Zn.current.sessionId),K.current="terminal",z("success"),await new Promise(ht=>setTimeout(ht,1200)),fa.current)return;fa.current=!0;let lt=Zn.current,Yt=(0,u.isAuthorizationOnlySession)(lt)||Ke.outcome==="authorized";Zn.current.onComplete?.(Yt?{status:"authorized",paymentIntentId:Ke.intentId,paymentId:Ke.paymentId??lt.paymentId,sessionId:Ke.sessionId??lt.sessionId,authorizationExpiresAt:Ke.authorizationExpiresAt??lt.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",paymentIntentId:Ke.intentId,checkoutMethod:"card"})}),Ne=Pe.on("decline",async Ke=>{let{updateError:lt,emitDecline:Yt}=Zn.current,ht=Ke.message??"Your payment was declined. Please try another card or contact your bank.";K.current="terminal",lt(ht),z("error");let bt=Ke.failureOutcome??(0,u.normalizeCheckoutFailureOutcome)(Ke.declineReason)??"authorization_declined";Yt("card",ht,{code:bt,declineCode:bt}),await new Promise(nt=>setTimeout(nt,1500)),!s&&(K.current="idle",z(null))}),Y=Pe.on("error",async Ke=>{let{updateError:lt,onError:Yt}=Zn.current,ht=Ke.message??"There was a problem processing your payment. Please try again.";K.current="terminal",lt(ht),z("error"),Yt?.(new u.FloPayError(ht,"api_error",{code:Ke.failureOutcome??"capture_failed"})),await new Promise(bt=>setTimeout(bt,1500)),!s&&(K.current="idle",z(null))}),De=Pe.on("blocked",()=>{if(!ai.current){fr(!0);return}ya(),Zn.current.updateError(os)});return()=>{s=!0,f.current&&(clearTimeout(f.current),f.current=null),K.current="idle",x(),j(),Ne(),Y(),De()}},[Ye,Pe,ya,oi]);let Qn=!!A?.clientId,eo=Array.isArray(w),Mo=eo&&w.length>0,_s=eo&&w.includes("paypal"),{expressMethods:Ao,paymentElementMethods:to}=(0,a.useMemo)(()=>(0,u.partitionStripeMethods)(w,{excludePaypal:Qn}),[w,Qn]),ii=Qn||!!pt,xs=(0,a.useMemo)(()=>ii?Ao.filter(s=>s!=="paypal"):Ao,[Ao,ii]),Ts=(0,a.useMemo)(()=>{let s=[];return q&&s.push("apple_pay"),ce&&s.push("google_pay"),s},[q,ce]),Bo=eo?xs:Ts,Ms=U&&Bo.length>0,ga=an?gt:T,Fo=(0,a.useMemo)(()=>{let s=ga?.trim().toUpperCase();return s?ue?to.filter(x=>{let j=ue[x];return!j||j.length===0||j.includes(s)}):(0,u.filterStripeMethodsByCountry)(to,ga):to},[to,ga,ue]),ha=(0,a.useMemo)(()=>({mode:"payment",amount:Qr,currency:Be.toLowerCase(),paymentMethodCreation:"manual",appearance:ei}),[Qr,Be,ei]),[si,li]=(0,a.useState)("loading"),[ci,di]=(0,a.useState)("loading"),[ui,pi]=(0,a.useState)("loading"),[As,ba]=(0,a.useState)(!1),[mi,va]=(0,a.useState)("loading"),[Do,Bs]=(0,a.useState)();(0,a.useEffect)(()=>{Bs(es())},[]);let yi=fe&&(Qn||(eo?_s:Do===!1)),fi=U&&Ms,no=!He&&yi&&Qn,gi=mi==="retrying"||mi==="exhausted",ro=!He&&yi&&!!Fr&&(!Qn||gi),oo=!He&&fi&&!!hn,ao=!He&&U&&Mo&&Fo.length>0&&!!hn,Fs=no&&!gi?As:ro&&ss(si),Ds=oo&&ss(ci),Ls=ao&&ui!=="load_error",hi=s=>s==="loading"||s==="ready",bi=no||ro&&hi(si)||oo&&hi(ci)||ao&&ui!=="load_error",Lo=(0,a.useRef)(!1);(0,a.useEffect)(()=>{if(!Lo.current){if(!U&&!fe){Lo.current=!0;let s=new u.FloPayError("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");d?.(s),he(s.message)}else if(!U&&fe&&!Qn&&!Fr){Lo.current=!0;let s=new u.FloPayError("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");d?.(s),he(s.message)}else if(Do!==void 0&&!He&&!Mt&&!bi){Lo.current=!0;let s=new u.FloPayError("FloPay: this checkout session has no vault card capability and no usable supported non-card payment methods. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});d?.(s),he(s.message)}}},[U,fe,Qn,Fr,Do,He,Mt,bi,d,he]);let vi=(0,a.useRef)(!1);(0,a.useEffect)(()=>{if(vi.current||!Mo)return;let s=[];q!==!0&&s.push("showApplePay"),ce!==!0&&s.push("showGooglePay"),s.length!==0&&(vi.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.`))},[Mo,q,ce]);let Pi=(0,a.useCallback)((s,x)=>Fe.applyInlineSessionPatch?Fe.applyInlineSessionPatch(s).then(j=>({error:null,sessionId:j.sessionId||e,nonce:j.session?.clientSecret||t})).catch(j=>{let Ne=is(x,j);return he(Ne.message),d?.(Ne),{error:Ne,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[Fe.applyInlineSessionPatch,t,d,e,he]),Vn=(0,a.useCallback)(async s=>{if(!L)return{proceed:!0};try{let x=await L({method:s,sessionId:e||void 0,createSession:Fe.inlineSessionDraft});if(x===!1)return{proceed:!1};if(x&&typeof x=="object"){x.account&&Pn(Ne=>({...Ne??{},...x.account}));let j=await Pi(x,s);return j.error?{proceed:!1,accountPatch:x.account}:{proceed:!0,accountPatch:x.account,sessionId:j.sessionId,nonce:j.nonce}}return{proceed:!0}}catch(x){let j=is(s,x);return he(j.message),d?.(j),{proceed:!1}}},[Pi,Fe.inlineSessionDraft,L,d,e,he]),Ci=(0,a.useCallback)(async(s,x)=>{if(X.current)return;X.current=!0,G(!0),z("processing"),he(null);let j=x?.sessionId??e,Ne=x?.nonce??t,Y=xa(D,x?.accountPatch),De=x?.completionPaymentMethodId??yo(s),Ke=s.originalPaymentMethodId?{...s,originalPaymentMethodId:void 0}:s,lt=s.gateway==="stripe"?"stripe":s.gateway==="paypal"||s.isPaypal?"paypal":void 0,Yt=()=>{mt?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"process_payment",provider:lt})};try{let bt=await new dr.PaymentAPI(le).processPayment(Y.userId??"",{sessionId:j,nonce:Ne,tokenizedData:Ke,accountData:{userId:Y.userId??"",email:Y.email??"",...Y.firstName?{firstName:Y.firstName}:{},...Y.lastName?{lastName:Y.lastName}:{},...se?(()=>{let Qe=Kt.current,rn=(0,u.isAVSFieldVisible)(se.state,Qe),En=(0,u.isAVSFieldVisible)(se.address_line_1,Qe),Wt=(0,u.isAVSFieldVisible)(se.postal_code,Qe),uo=En&&!rn&&Wt?(0,u.getStateFromPostalCode)(Qe,(It.current??"").trim()):null,po=rn?en.current:uo;return{country:Qe,...Wt&&It.current?{zip:It.current}:{},...(0,u.isAVSFieldVisible)(se.city,Qe)&&Cn.current?{city:Cn.current}:{},...po?{state:po}:{},...En&&yn.current?{addressLine1:yn.current}:{},...(0,u.isAVSFieldVisible)(se.address_line_2,Qe)&&on.current?{addressLine2:on.current}:{}}})():{}},chv:v,avsCheck:Oe??!1,checkoutType:ee,checkoutLayout:W,avsConfig:se?{country:(0,u.isAVSFieldVisible)(se.country,Kt.current),postal_code:(0,u.isAVSFieldVisible)(se.postal_code,Kt.current),address_line_1:(0,u.isAVSFieldVisible)(se.address_line_1,Kt.current),address_line_2:(0,u.isAVSFieldVisible)(se.address_line_2,Kt.current),city:(0,u.isAVSFieldVisible)(se.city,Kt.current),state:(0,u.isAVSFieldVisible)(se.state,Kt.current)}:void 0});if(bt.ok){let Qe=bt.status===204?null:await bt.json().catch(()=>null),rn=(0,u.isAuthorizationOnlySession)(F)||Qe?.status==="authorized";Wr(j),z("success"),ut(null),await new Promise(En=>setTimeout(En,1200)),i?.(rn?{status:"authorized",...typeof Qe?.paymentId=="string"?{paymentId:Qe.paymentId}:F?.paymentId?{paymentId:F.paymentId}:{},sessionId:typeof Qe?.sessionId=="string"?Qe.sessionId:j,...typeof Qe?.authorizationExpiresAt=="string"?{authorizationExpiresAt:Qe.authorizationExpiresAt}:F?.authorizationExpiresAt?{authorizationExpiresAt:F.authorizationExpiresAt}:{},paymentIntentId:s.threeDSecureActionResultTokenId,paymentMethodId:De,checkoutMethod:s.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:s.threeDSecureActionResultTokenId,paymentMethodId:De,checkoutMethod:s.isPaypal?"paypal":"card"});return}let nt=await bt.json().catch(()=>null);if(nt?.type==="paypal_redirect_required"){let Qe=nt.threeDSecureToken,rn=nt.paymentMethodId||s.id||"";if(!ke||!Qe){z("error"),he("PayPal authorization required but no token provided.");return}try{let En=pt?.getRawProvider();if(!En){he("PayPal is not available.");return}let Wt={return_url:window.location.href};rn&&(Wt.payment_method=rn);let{error:uo}=await En.confirmPayment({clientSecret:Qe,confirmParams:Wt,redirect:"if_required"});if(uo){z("error");let po=uo.message??"PayPal payment failed.";he(po),jn("paypal",po,{code:uo.code})}}catch(En){z("error"),he(En instanceof Error?En.message:"PayPal authorization failed.")}return}if(nt?.type==="paypal_direct_required"){let Qe=nt.orderId;if(!Qe){z("error"),he("PayPal retry required but no order id provided.");return}let rn=yt.current?.attempts??0;if(rn>=2){z("error"),he("PayPal payment could not be completed after multiple attempts."),jn("paypal","paypal_direct_required retry limit exceeded");return}ba(!1),va("loading"),ut({orderId:Qe,attempts:rn+1}),z(null);return}(0,u.classifyPaymentRejection)(bt.status,nt)||Yt(),z("error");let nn=nt?.message??"Payment failed. Please try again.";he(nn),jn(s.isPaypal?"paypal":"card",nn,{code:nt?.code??nt?.gatewayErrorCode,declineCode:nt?.declineCode??nt?.gatewayDeclineReason}),await new Promise(Qe=>setTimeout(Qe,1500))}catch(ht){us(ht)||Yt(),z("error"),he(ht instanceof Error?ht.message:"An unexpected error occurred"),await new Promise(bt=>setTimeout(bt,1500))}finally{G(!1),z(null),X.current=!1}},[le,e,t,D,se,Oe,ee,W,v,ke,pt,F,i,he,jn,mt]),In=(0,a.useCallback)((s,x)=>{P?P(s):Ci(s,x)},[P,Ci]),Si=(0,a.useRef)(!1);(0,a.useEffect)(()=>{if(typeof window>"u"||Si.current)return;let s=new URLSearchParams(window.location.search),x=s.get("payment_intent"),j=s.get("payment_intent_client_secret"),Ne=s.get("redirect_status");if(!x||!j)return;let Y=bt=>{let nt=localStorage.getItem(bt);if(!nt)return null;try{return JSON.parse(nt)}catch{return localStorage.removeItem(bt),null}},De=Y(er)??Y(rs),Ke;if(De?.clientSecret){if(De.clientSecret!==j)return;Ke={...De.accountPatch?{accountPatch:De.accountPatch}:{},...De.sessionId?{sessionId:De.sessionId}:{},...De.nonce?{nonce:De.nonce}:{}}}else if(De?.sessionId&&De.sessionId!==e)return;Si.current=!0,localStorage.removeItem(er),localStorage.removeItem(rs);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 Yt=De?.paymentMethodType??De?.tokenType??"card",ht="card";(async()=>{let bt=ke?.getRawProvider();if(!bt){let Wt="Payment is not available \u2014 please refresh and try again.";he(Wt),jn(ht,Wt);return}if(Ne==="failed"){let Wt="Payment was declined. Please try again.";he(Wt),jn(ht,Wt);return}let{paymentIntent:nt,error:nn}=await bt.retrievePaymentIntent(j);if(nn){let Wt=nn.message??"Failed to retrieve payment status.";he(Wt),jn(ht,Wt,{code:nn.code});return}let Qe=nt?.status,rn=Ko(Qe);if(!nt||!rn){let Wt=Qe==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";he(Wt),jn(ht,Wt,{code:Qe??"missing_payment_intent"});return}let En=typeof nt.payment_method=="string"?nt.payment_method:nt.payment_method?.id;In({id:En??De?.paymentMethodId??De?.tokenId??nt.id,type:"card",threeDSecureActionResultTokenId:nt.id,gateway:De?.gateway??"stripe",paymentMethodType:Yt},Ke)})()},[e,In,ke,he,jn]);let Pa=(0,a.useCallback)(s=>{s.preventDefault()},[]);if(!(ke!==null))return(0,l.jsx)("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let io=H==="buttons",un=Ce?.variables,Ns=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),Ca=un?.colorBackground,Os=Ca&&!Ns.has(Ca)?Ca:void 0,so=b.cardInputBorder??(io?"#e5e7eb":"#A4A4FF"),wi=un?.colorDanger??"#dc2626",Rt=s=>Br[s]&&(Xn[s]||sn),No=Ot&&(At||sn),Rn=s=>s?wi:so,Oo=(tn.malformed||tn.empty)&&(Jn||sn),zs=Rn(Oo),Sa=b.cardFormContainer?.backgroundColor??Os??(io?"white":"#EDEDFF"),Lr=b.cardInputBackground??un?.colorBackground??"white",wa=Or(Ie),ki=Or(Re),Nr=b.nameInput,Ii=b.cardInputFontSize??Al(Nr?.fontSize)??un?.fontSizeBase??"16px",Ri=typeof Nr?.fontFamily=="string"?Nr.fontFamily:un?.fontFamily??"Poppins, sans-serif",Ei=La(Nr?.fontWeight)??400,Us=b.cardInputColor??(typeof Nr?.color=="string"?Nr.color:void 0)??un?.colorText??"#262833",qs=b.cardInputPlaceholderColor??"#9ca3af",_t=un?.borderRadius??"8px",kr=un?.borderRadius??b.cardButton?.borderRadius??_t,Ir=un?.colorPrimary??"#4A49FF",$s=un?.colorPrimaryHover??Zr(Ir,.12),ka=un?.colorText??"#262833",Ia={fontSize:Ii,fontFamily:Ri,fontWeight:Ei,color:Us,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},lo={marginTop:"0.375rem",...Ia,fontSize:"0.75rem",lineHeight:1.4,color:wi},js={"--flopay-input-placeholder-color":qs,"--flopay-input-font-size":Ii,"--flopay-input-font-family":Ri,"--flopay-input-font-weight":String(Ei)},co=b.cardFormContainer??{},Ra=co.padding??(io?"0":"1rem"),Ea=co.borderRadius??_t,Vs=Pe&&qn?(0,l.jsx)(Xr,{capture:Pe,html:qn.html,messageToken:qn.messageToken,expectedOrigin:qn.expectedOrigin,theme:pe,onReady:()=>{if(!ft&&!se||typeof document>"u")return;let s=()=>{let j=(document.querySelector('[data-testid="flopay-vault-identity-fields"]')??document.querySelector('[data-testid="flopay-avs-fields"]'))?.querySelector("input:not([disabled]), select:not([disabled])");if(j){Xt.current=!0;try{j.focus()}finally{Xt.current=!1}}};Un.current||s()},onError:s=>he(s),onValidation:s=>{let x=K.current;(x==="idle"||x==="validation-window")&&(he(s),s&&K.current==="validation-window"&&(f.current&&(clearTimeout(f.current),f.current=null),K.current="idle",z(null)))}}):(0,l.jsx)("div",{"data-testid":"flopay-vault-loading",style:{minHeight:120,display:"flex",alignItems:"center",justifyContent:"center",color:"#6b7280",fontSize:14},children:"Loading secure card form\u2026"}),_i=(0,l.jsxs)("div",{onFocusCapture:s=>{["INPUT","SELECT","TEXTAREA","IFRAME"].includes(s.target.tagName)&&gn()},style:{backgroundColor:Sa,borderRadius:Ea,...co,padding:Ra,...js,display:"flex",flexDirection:"column"},children:[(0,l.jsx)("style",{children:`
|
|
30
|
+
`,ra=44,Tr=280;function $a(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 Il={visibility:"hidden",position:"absolute",pointerEvents:"none",width:"100%",height:0,overflow:"hidden"};function Rl(e){return e.isPaypal||e.gateway==="paypal"||e.paymentMethodType==="paypal"?"paypal":e.paymentMethodType==="apple_pay"||e.paymentMethodType==="google_pay"?"wallet":e.paymentMethodType&&e.paymentMethodType!=="card"?"apm":"card"}var ms={width:"100%",minHeight:ra,margin:"0 0 0.5rem",padding:"0.75rem 0.875rem",border:"1px solid #2563eb",borderRadius:8,background:"#eff6ff",color:"#1d4ed8",fontSize:"0.95rem",fontWeight:700,cursor:"pointer"};function El(e){switch(e){case"paypal":return"PayPal";case"apple_pay":return"Apple Pay";case"google_pay":return"Google Pay";default:return"Card"}}function as(e){return e==="paypal"?"paypal":e==="apple_pay"?"apple_pay":"google_pay"}function za(e){return e==="paypal"?"PayPal":(0,u.getStripeMethodDisplayName)(e)}function _l(e,t){let n=`We couldn't open ${za(e)}. Try again or choose another payment method.`;return t?`${n} Allow pop-ups for this site, then try again.`:n}function ys(e){let t=(0,a.useRef)(0),n=(0,a.useRef)(null),r=(0,a.useRef)(null),o=(0,a.useCallback)((m=r.current)=>{let S=m;S?.timer&&(clearTimeout(S.timer),S.timer=null)},[]),i=(0,a.useCallback)((m,S)=>{typeof document<"u"&&document.visibilityState!=="visible"||(o(m),m.timer=setTimeout(()=>{m.timer=null,r.current?.generation===m.generation&&(r.current=null,n.current=m.generation,e(m.method,new Error("External payment method returned without a terminal callback."),{code:"external_method_missing_terminal_callback"}))},S))},[o,e]),d=(0,a.useCallback)(m=>{m.yieldedControl&&i(m,600)},[i]),c=(0,a.useCallback)(m=>{o();let S=t.current+1;t.current=S,n.current=null;let he={generation:S,method:m,timer:null,yieldedControl:!1};return r.current=he,S},[o]),P=(0,a.useCallback)(m=>{let S=r.current;return typeof m=="number"&&S?.generation!==m?!1:(o(S),r.current=null,(typeof m!="number"||n.current===m)&&(n.current=null),!0)},[o]),y=(0,a.useCallback)(m=>{let S=r.current,he=m??S?.generation??t.current;(!m||S?.generation===m)&&(o(S),r.current=null),n.current=he},[o]),h=(0,a.useCallback)(m=>n.current===(m??t.current),[]),v=(0,a.useCallback)(m=>r.current?.generation===m&&n.current!==m,[]),B=(0,a.useCallback)(()=>{let m=r.current;m&&d(m)},[d]),M=(0,a.useCallback)(()=>{let m=r.current;m&&(m.yieldedControl=!0,o(m))},[o]);return(0,a.useEffect)(()=>{let m=()=>{document.visibilityState==="visible"?B():M()},S=()=>{M()};return document.addEventListener("visibilitychange",m),window.addEventListener("blur",S),window.addEventListener("focus",B),()=>{document.removeEventListener("visibilitychange",m),window.removeEventListener("blur",S),window.removeEventListener("focus",B),o()}},[o,M,B]),{startAttempt:c,finishAttempt:P,invalidateAttempt:y,isAttemptInvalidated:h,isAttemptCurrent:v}}function xl(e){let t=(0,u.getPostalCodeExample)(e);return`Enter a valid ${(0,u.getPostalCodeLabel)(e)}${t?` (e.g. ${t})`:""}`}function Tl(e,t,n){let r=(0,u.isPostalCodeSupported)(e),o=t.trim(),i=n&&r,d=i&&!o,c=i&&!!o&&!(0,u.isValidPostalCode)(e,o);return{visible:n,supported:r,required:i,empty:d,malformed:c}}function Ml(e,t){let n=e.trim(),r=t&&!n,o=t&&!!n&&!(0,u.isValidEmail)(n);return{required:t,empty:r,malformed:o,value:n}}function is(e,t){return t instanceof u.FloPayError?t:new u.FloPayError(t instanceof Error?t.message:`${El(e)} before-click hook failed.`,"validation_error")}function Oa(){return(0,l.jsx)("style",{children:kl})}function Al(e){return typeof e=="number"?`${e}px`:e}function fs(e,t){let n=e.availablePaymentMethods;return n&&t.some(r=>n[r])?"ready":"unavailable"}function gs({state:e,placeholderTestId:t,borderRadius:n=8,children:r}){return e==="unavailable"||e==="load_error"?null:(0,l.jsxs)("div",{style:{position:"relative",minHeight:44},children:[(0,l.jsx)("div",{"data-testid":t,"aria-hidden":e==="ready",style:{position:"absolute",inset:0,height:44,borderRadius:n,background:"#e5e7eb",animation:e==="ready"?void 0:"flopay-pulse 1.5s ease-in-out infinite",opacity:e==="ready"?0:1,transform:e==="ready"?"scale(0.985)":"scale(1)",transition:"opacity 140ms ease-out, transform 140ms ease-out",pointerEvents:"none"}}),(0,l.jsx)("div",{style:{minHeight:44,opacity:e==="ready"?1:0,transform:e==="ready"?"translateY(0)":"translateY(2px)",transition:"opacity 140ms ease-out, transform 140ms ease-out",pointerEvents:e==="ready"?"auto":"none"},children:r})]})}function ss(e){return e!=="unavailable"&&e!=="load_error"}function ia(e){return(0,l.jsx)(Fl,{...e})}function ls({sessionId:e,nonce:t,email:n,billingApiUrl:r,onTokenizedBody:o,onErrorChange:i,isProcessing:d=!1,onButtonClick:c,onDecline:P,onTechnicalFailure:y,runBeforeButtonClick:h,billingName:v,onBuyerIdentityReady:B,onLoadStateChange:M,placeholderBorderRadius:m}){let S=sr(),{emitInstrument:he}=(0,a.useContext)(_n),U=(0,Tt.useStripe)(),w=(0,Tt.useElements)(),[ue,q]=(0,a.useState)("loading");(0,a.useEffect)(()=>{M?.(ue)},[ue,M]);let[ce,H]=(0,a.useState)(!1),fe=!(0,u.isValidEmail)(n?.trim())||!v?.trim(),{request:$e,collect:Se,finish:Pt}=jr(),ze=(0,a.useRef)(!1),Ie=(0,a.useRef)(null),Re=(0,a.useRef)(null),[ne,re]=(0,a.useState)(0),[L,Ee]=(0,a.useState)(!1),_e=(0,a.useRef)(!1),J=(0,a.useRef)(new Map),{startAttempt:we,finishAttempt:ve,invalidateAttempt:T,isAttemptInvalidated:O,isAttemptCurrent:Ae}=ys((ee,W,V)=>{y?.(ee,W,{...V,popupBlocked:V?.popupBlocked??vr(W)}),Ee(!0),re(Be=>Be+1)});(0,a.useEffect)(()=>{L&&Re.current?.focus()},[L,ne]);let ye=(0,a.useCallback)(()=>{re(ee=>ee+1)},[]),Q=(0,a.useCallback)((ee,W,V)=>{T(V),y?.("paypal",ee,{code:W,popupBlocked:vr(ee)}),Ee(!0),ye()},[T,y,ye]),Le=(0,a.useCallback)(()=>{window.setTimeout(()=>{(Ie.current?.querySelector("iframe")??Ie.current)?.focus()},0)},[]);(0,a.useEffect)(()=>{_e.current&&(_e.current=!1,Le())},[Le,ne]);let rt=(0,a.useCallback)(()=>{Ee(!1),i?.(null),Le()},[Le,i]);(0,a.useEffect)(()=>{if(!U||ze.current)return;let ee=new URLSearchParams(window.location.search),W=ee.get("payment_intent"),V=ee.get("payment_intent_client_secret"),Be=ee.get("redirect_status");if(!W||!V)return;ze.current=!0;let Je;try{let oe=localStorage.getItem(ko);if(oe){let F=JSON.parse(oe);F.clientSecret===V&&(Je={...F.accountPatch?{accountPatch:F.accountPatch}:{},...F.sessionId?{sessionId:F.sessionId}:{},...F.nonce?{nonce:F.nonce}:{}})}}catch{}try{localStorage.removeItem(ko)}catch{}let A=new URL(window.location.href);A.searchParams.delete("payment_intent"),A.searchParams.delete("payment_intent_client_secret"),A.searchParams.delete("redirect_status"),window.history.replaceState({},"",A.toString()),(async()=>{try{if(H(!0),Be==="failed"){let R="PayPal payment was declined. Please try again.";i?.(R),P?.(jt("paypal",R));return}let{paymentIntent:oe,error:F}=await U.retrievePaymentIntent(V);if(F){i?.(F.message??"Failed to retrieve PayPal payment status.");return}if(oe&&(oe.status==="requires_capture"||oe.status==="succeeded")){let R=typeof oe.payment_method=="string"?oe.payment_method:oe.payment_method?.id;o({id:R??oe.id,type:"card",threeDSecureActionResultTokenId:oe.id,isPaypal:!0},Je)}else{let R="PayPal payment was not completed. Please try again.";i?.(R),P?.(jt("paypal",R))}}catch(oe){i?.(oe instanceof Error?oe.message:"Failed to complete PayPal payment.")}finally{H(!1)}})()},[U,o,i,P]);let ct=(0,a.useCallback)(async ee=>{if(d||ce){ee.reject();return}let W=h?await h("paypal"):{proceed:!0};if(!W.proceed){J.current.delete(ne),ee.reject();return}let V=we("paypal");J.current.set(ne,{generation:V,accountPatch:W.accountPatch,sessionId:W.sessionId,nonce:W.nonce}),Ee(!1),c?.("paypal"),ee.resolve()},[d,c,h,we,ce,ne]),Oe=(0,a.useCallback)(async ee=>{if(!U||!w)return;let W=J.current.get(ne);if(W&&!Ae(W.generation)){J.current.delete(ne);return}if(!W&&O()||W&&!ve(W.generation))return;W||ve();let V=W??null;if(J.current.delete(ne),!V&&h){let R=await h("paypal");if(!R.proceed){ee.paymentFailed({reason:"fail",message:"PayPal checkout was cancelled."});return}V={accountPatch:R.accountPatch,sessionId:R.sessionId,nonce:R.nonce}}let Be=V?.sessionId??e,Je=V?.nonce??t,A=await ps({event:ee,prepared:V,email:n,billingName:v,methodLabel:"PayPal",collect:Se});if(!A){ee.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let oe=A.email,F=pn({...V?.accountPatch,...A});try{if(H(!0),i?.(null),!Be||!(0,u.isValidEmail)(oe))throw new Error("Missing sessionId or email for PayPal payment");await B?.(A);let R=U.createPaymentMethod,{error:at,paymentMethod:Ct}=await R({type:"paypal"});if(at){Q(at,"stripe_paypal_create_payment_method_failed",W?.generation),ee.paymentFailed({reason:"fail"});return}let ke=await oa(r,he,Be,Je??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:Ct?.id??null,intentKind:"payment"});if(ke.provider!=="stripe")throw new Error("Invalid provider returned for PayPal intent");let pt=ke.clientSecret,Fe={return_url:window.location.href};if(Ct?.id&&(Fe.payment_method=Ct.id),typeof window<"u")try{localStorage.setItem(ko,JSON.stringify({clientSecret:pt,sessionId:Be,nonce:Je,accountPatch:F}))}catch{}let{error:mt,paymentIntent:Et}=await U.confirmPayment({clientSecret:pt,confirmParams:Fe,redirect:"if_required"});if(mt){if(typeof window<"u")try{localStorage.removeItem(ko)}catch{}if(fo(mt)){let te=mt.message??"Your payment was declined.";i?.(te),P?.(jt("paypal",te,{code:ir(mt),declineCode:Kr(mt)})),await aa({billingApiUrl:r,sessionId:Be,nonce:Je,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:ir(mt)??"provider_declined"}})}else Q(mt,"stripe_paypal_confirm_failed",W?.generation);return}if(typeof window<"u")try{localStorage.removeItem(ko)}catch{}let C=typeof Et?.payment_method=="string"?Et.payment_method:Et?.payment_method?.id;o({id:C??Et?.id,type:"card",threeDSecureActionResultTokenId:Et?.id,isPaypal:!0},{accountPatch:F,paymentMethodCategory:"paypal",sessionId:Be,nonce:Je});return}catch(R){Q(R,"stripe_paypal_failed",W?.generation)}finally{H(!1)}},[U,w,e,t,n,v,Se,B,r,he,o,i,P,h,Q,ve,Ae,O,ne]);return(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(gs,{state:ue,placeholderTestId:"flopay-paypal-placeholder",borderRadius:m,children:(0,l.jsxs)("div",{ref:Ie,tabIndex:-1,"data-testid":"flopay-paypal-focus-target",role:"group","aria-label":"PayPal payment method",style:{borderRadius:8,outlineOffset:4},children:[L&&(0,l.jsx)("button",{ref:Re,type:"button","data-testid":"flopay-paypal-retry-button",onClick:rt,style:ms,children:"Try PayPal again"}),$e&&(0,l.jsx)(Vr,{identity:$e.identity,methodLabel:$e.methodLabel,onComplete:Pt,onCancel:()=>Pt(null)},$e.id),(0,l.jsx)("div",{style:{display:$e?"none":void 0},children:(0,l.jsx)(Tt.ExpressCheckoutElement,{onReady:ee=>q(fs(ee,["paypal"])),onLoadError:()=>{q("load_error"),qa(Vt(S),"paypal","paypal")},onClick:ct,onConfirm:Oe,onCancel:()=>{let ee=J.current.get(ne);J.current.delete(ne),Vt(S)?.terminal({outcome:"payment_cancelled",provider:"paypal",paymentMethodCategory:"paypal"}),T(ee?.generation),Ee(!1),_e.current=!0,ye()},options:{buttonType:{paypal:"paypal"},billingAddressRequired:fe,emailRequired:fe,phoneNumberRequired:!1,shippingAddressRequired:!1,paymentMethods:{applePay:"never",googlePay:"never",paypal:"auto",link:"never"}}},ne)})]})}),ce&&(0,l.jsx)(Tn,{status:"processing"})]})}function cs({sessionId:e,nonce:t,email:n,billingApiUrl:r,intentKind:o,expressMethods:i,onTokenizedBody:d,onErrorChange:c,onButtonClick:P,onDecline:y,onTechnicalFailure:h,runBeforeButtonClick:v,billingName:B,onBuyerIdentityReady:M,onLoadStateChange:m,placeholderBorderRadius:S}){let he=sr(),{emitInstrument:U}=(0,a.useContext)(_n),w=(0,Tt.useStripe)(),ue=(0,Tt.useElements)(),[q,ce]=(0,a.useState)("loading");(0,a.useEffect)(()=>{m?.(q)},[q,m]);let[H,fe]=(0,a.useState)(!1),$e=!(0,u.isValidEmail)(n?.trim())||!B?.trim(),{request:Se,collect:Pt,finish:ze}=jr(),Ie=(0,a.useRef)(null),Re=(0,a.useRef)(null),[ne,re]=(0,a.useState)(0),[L,Ee]=(0,a.useState)(!1),[_e,J]=(0,a.useState)("google_pay"),we=(0,a.useRef)(!1),ve=(0,a.useRef)("google_pay"),T=(0,a.useRef)("google_pay"),O=(0,a.useRef)(new Map),{startAttempt:Ae,finishAttempt:ye,invalidateAttempt:Q,isAttemptInvalidated:Le,isAttemptCurrent:rt}=ys((A,oe,F)=>{h?.(A,oe,{...F,popupBlocked:F?.popupBlocked??vr(oe)}),J(A),Ee(!0),re(R=>R+1)});(0,a.useEffect)(()=>{L&&Re.current?.focus()},[L,ne]);let ct=(0,a.useCallback)(()=>{re(A=>A+1)},[]),Oe=(0,a.useCallback)((A,oe,F,R)=>{Q(R),h?.(A,oe,{code:F,popupBlocked:vr(oe)}),J(A),Ee(!0),ct()},[Q,h,ct]),ee=(0,a.useCallback)(()=>{window.setTimeout(()=>{(Ie.current?.querySelector("iframe")??Ie.current)?.focus()},0)},[]);(0,a.useEffect)(()=>{we.current&&(we.current=!1,ee())},[ee,ne]);let W=(0,a.useCallback)(()=>{Ee(!1),c?.(null),ee()},[ee,c]),V=(0,a.useCallback)(async A=>{if(!w||!ue)return;let oe=O.current.get(ne);if(oe&&!rt(oe.generation)){O.current.delete(ne);return}if(!oe&&Le()||oe&&!ye(oe.generation))return;oe||ye();let F=A.expressPaymentType??oe?.method??ve.current,R=oe??null;O.current.delete(ne);let at=as(F);if(!R&&v){let C=await v(at);if(!C.proceed){A.paymentFailed({reason:"fail",message:"Wallet checkout was cancelled."});return}R={accountPatch:C.accountPatch,sessionId:C.sessionId,nonce:C.nonce}}let Ct=at,ke=R?.sessionId??e,pt=R?.nonce??t,Fe=await ps({event:A,prepared:R,email:n,billingName:B,methodLabel:za(F),collect:Pt});if(!Fe){A.paymentFailed({reason:"fail",message:"Buyer details are required."});return}let mt=Fe.email,Et=pn({...R?.accountPatch,...Fe});try{if(fe(!0),c?.(null),!(0,u.isValidEmail)(mt))throw new Error("Missing sessionId or email for wallet payment");await M?.(Fe);let{error:C}=await ue.submit();if(C){Oe(F,C,"stripe_wallet_submit_failed",oe?.generation);return}let{error:te,paymentMethod:Xe}=await w.createPaymentMethod({elements:ue});if(te||!Xe){Oe(F,te??new Error("Failed to create payment method."),"stripe_wallet_create_payment_method_failed",oe?.generation);return}if(!ke)throw new Error("Missing sessionId or email for wallet payment");let He=await oa(r,U,ke,pt??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:F??at,paymentMethodId:Xe.id,intentKind:o});if(He.provider!=="stripe")throw new Error("Invalid provider returned for wallet intent");let zt=He.clientSecret,{error:Lt,intentId:G}=(0,u.isSetupIntentClientSecret)(zt)?await w.confirmCardSetup(zt,{payment_method:Xe.id}).then(dt=>({error:dt.error,intentId:dt.setupIntent?.id})):await w.confirmCardPayment(zt,{payment_method:Xe.id}).then(dt=>({error:dt.error,intentId:dt.paymentIntent?.id}));if(Lt){if(fo(Lt)){let dt=Lt.message??"Your payment was declined.";c?.(dt),y?.(jt(Ct,dt,{code:ir(Lt),declineCode:Kr(Lt)})),await aa({billingApiUrl:r,sessionId:ke,nonce:pt,request:{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:F??at,providerDeclineReason:ir(Lt)??"provider_declined"}})}else Oe(F,Lt,"stripe_wallet_confirm_failed",oe?.generation);return}d({id:Xe.id,type:"card",threeDSecureActionResultTokenId:G},{accountPatch:Et,paymentMethodCategory:"wallet",sessionId:ke,nonce:pt})}catch(C){Oe(F,C,"stripe_wallet_failed",oe?.generation)}finally{fe(!1)}},[w,ue,e,t,n,B,Pt,M,r,U,o,d,c,y,v,Oe,ye,rt,Le,ne]),Be=(0,a.useMemo)(()=>{let A=["applePay","googlePay","paypal","link","amazonPay","klarna"],oe=new Set(["applePay","googlePay"]),F=new Set(i.map(u.stripeExpressMethodToOptionKey)),R={};for(let at of A)F.has(at)?R[at]=oe.has(at)?"always":"auto":R[at]="never";return R},[i]),Je=(0,a.useMemo)(()=>i.map(u.stripeExpressMethodToOptionKey),[i]);return(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(gs,{state:q,placeholderTestId:"flopay-wallet-placeholder",borderRadius:S,children:(0,l.jsxs)("div",{ref:Ie,tabIndex:-1,"data-testid":"flopay-wallet-focus-target",role:"group","aria-label":"Wallet payment methods",style:{borderRadius:8,outlineOffset:4},children:[L&&(0,l.jsxs)("button",{ref:Re,type:"button","data-testid":"flopay-wallet-retry-button",onClick:W,style:ms,children:["Try ",za(_e)," again"]}),Se&&(0,l.jsx)(Vr,{identity:Se.identity,methodLabel:Se.methodLabel,onComplete:ze,onCancel:()=>ze(null)},Se.id),(0,l.jsx)("div",{style:{display:Se?"none":void 0},children:(0,l.jsx)(Tt.ExpressCheckoutElement,{onReady:A=>{ce(fs(A,Je))},onLoadError:A=>{ce("load_error"),qa(Vt(he),"stripe","wallet")},onClick:async A=>{ve.current=A.expressPaymentType,T.current=as(A.expressPaymentType);let oe=v?await v(T.current):{proceed:!0};if(!oe.proceed){O.current.delete(ne),A.reject();return}let F=Ae(A.expressPaymentType);O.current.set(ne,{generation:F,method:A.expressPaymentType,accountPatch:oe.accountPatch,sessionId:oe.sessionId,nonce:oe.nonce}),Ee(!1),P?.(T.current),A.resolve()},onConfirm:V,onCancel:()=>{let A=O.current.get(ne);O.current.delete(ne),Vt(he)?.terminal({outcome:"payment_cancelled",provider:"stripe",paymentMethodCategory:"wallet"}),Q(A?.generation),Ee(!1),we.current=!0,ct()},options:{buttonType:{applePay:"plain",googlePay:"plain"},paymentMethods:Be,emailRequired:$e,billingAddressRequired:$e,layout:{maxColumns:1,overflow:"never"}}},ne)})]})}),H&&(0,l.jsx)(Tn,{status:"processing"})]})}function Bl({method:e,themeId:t,submitting:n=!1,disabled:r=!1,highlighted:o=!1,hasNextStep:i=!1,onClick:d,backgroundColor:c,borderColor:P,textColor:y,borderRadius:h,fontFamily:v}){let B=(0,u.resolveStripeMethodBrandVariant)(e,t),M=ts[e],[m,S]=(0,a.useState)(!1),he=B?.backgroundColor??c??"#ffffff",U=B?.borderColor??P??"#d1d5db",w=B?.textColor??y??"#262833";return(0,l.jsx)("button",{type:"button","data-testid":`flopay-stripe-method-button-${e}`,"data-method":e,onClick:()=>{!n&&!r&&d()},disabled:n||r,"aria-busy":n||void 0,style:{position:"relative",width:"100%",boxSizing:"border-box",height:ra,padding:"0 1rem",backgroundColor:he,color:w,border:`1px solid ${U}`,borderRadius:h??8,fontSize:"0.95rem",fontWeight:600,fontFamily:v,cursor:n||r?"not-allowed":"pointer",opacity:r&&!n?.55:1,animation:n?"flopay-pulse 1.5s ease-in-out infinite":void 0,display:"flex",alignItems:"center",justifyContent:"center",gap:8,transition:"transform 0.1s, opacity 140ms ease-out, border-color 140ms ease-out",boxShadow:o?"0 0 0 2px rgba(74, 73, 255, 0.15)":void 0},children:n?(0,l.jsx)("span",{style:{margin:"0 auto"},children:`Connecting to ${(0,u.getStripeMethodDisplayName)(e)}\u2026`}):(0,l.jsxs)(l.Fragment,{children:[(0,l.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:(0,u.hasVendoredStripeMethodLogo)(e)?8:0},children:[M&&!m?(0,l.jsx)("img",{src:M,alt:"","aria-hidden":"true",onError:()=>S(!0),loading:"lazy",decoding:"async",width:30,height:20,style:{width:30,height:20,flexShrink:0,borderRadius:3,objectFit:"contain",display:"inline-flex"}}):B?.logoSvg?(0,l.jsx)("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:B.logoSvg}}):null,(0,l.jsx)("span",{children:(0,u.getStripeMethodDisplayName)(e)})]}),i&&(0,l.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:w,strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{position:"absolute",right:"1rem",top:"50%",transform:"translateY(-50%)",flexShrink:0,opacity:.7},"aria-hidden":"true",children:(0,l.jsx)("path",{d:"M9 18l6-6-6-6"})})]})})}function Ua({method:e,sessionId:t,nonce:n,email:r,billingName:o,onBuyerIdentityReady:i,billingApiUrl:d,onTokenizedBody:c,onErrorChange:P,onDecline:y,onCancel:h,runBeforeButtonClick:v,onButtonClick:B,isProcessing:M,submitButtonColor:m,submitButtonBorderRadius:S,submitButtonStyle:he,errorText:U}){let w=sr(),{emitInstrument:ue}=(0,a.useContext)(_n),q=(0,Tt.useStripe)(),ce=(0,Tt.useElements)(),[H,fe]=(0,a.useState)(!1),$e=(0,a.useRef)(!1),[Se,Pt]=(0,a.useState)(!1),[ze,Ie]=(0,a.useState)("loading"),[Re,ne]=(0,a.useState)(""),re=!(0,u.isValidEmail)(r?.trim()),L=!re||(0,u.isValidEmail)(Re.trim()),Ee=(0,a.useCallback)(async()=>{if(!q||!ce||M||$e.current||!Se)return;$e.current=!0,fe(!0);let _e=v?await v("card"):{proceed:!0};if(!_e.proceed){$e.current=!1,fe(!1);return}B?.("card");let J=_e.sessionId??t,we=_e.nonce??n,ve=Rr(o?.trim()),T=pn({email:_e.accountPatch?.email?.trim()||r?.trim()||Re.trim(),firstName:_e.accountPatch?.firstName?.trim()||ve.firstName,lastName:_e.accountPatch?.lastName?.trim()||ve.lastName}),O=T.email,Ae=pn({..._e.accountPatch,...T});try{if(P?.(null),!(0,u.isValidEmail)(O))throw new Error("A valid email address is required for payment.");await i?.(T);let ye=await ce.submit();if(ye.error){P?.(ye.error.message??"Payment failed.");return}let Q=[T.firstName,T.lastName].filter(Boolean).join(" "),Le=await q.createPaymentMethod({elements:ce,params:{billing_details:{email:O,...Q?{name:Q}:{}}}});if(Le.error||!Le.paymentMethod){P?.(Le.error?.message??"Failed to create payment method.");return}let rt=Le.paymentMethod;if(!J||!O)throw new Error("Missing sessionId or email for payment.");let ct=rt.type||e,Oe=await oa(d,ue,J,we??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:ct,paymentMethodId:null,intentKind:"payment"});if(Oe.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let ee=Oe.clientSecret;if(typeof window<"u")try{localStorage.setItem(er,JSON.stringify({clientSecret:ee,sessionId:J,nonce:we,accountPatch:Ae,paymentMethodId:rt.id,paymentMethodType:rt.type??e,gateway:"stripe"}))}catch{}let{error:W,paymentIntent:V}=await q.confirmPayment({clientSecret:ee,confirmParams:{return_url:window.location.href,payment_method:rt.id},redirect:"if_required"});if(W){if(typeof window<"u")try{localStorage.removeItem(er)}catch{}let A=W.message??"Payment failed.";P?.(A),y?.(jt("card",A,{code:W.code})),await aa({billingApiUrl:d,sessionId:J,nonce:we,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:e,providerDeclineReason:W.code??"provider_declined"}});return}let Be=V?.status;if(!Ko(Be)){if(typeof window<"u")try{localStorage.removeItem(er)}catch{}let A=Be==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";P?.(A),y?.(jt("card",A,{code:Be??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(er)}catch{}let Je=typeof V?.payment_method=="string"?V.payment_method:V?.payment_method?.id;c({id:Je??rt.id,type:"card",threeDSecureActionResultTokenId:V?.id,gateway:"stripe",paymentMethodType:rt.type??e},{accountPatch:Ae,paymentMethodCategory:"apm",sessionId:J,nonce:we})}catch(ye){P?.(ye instanceof Error?ye.message:"Payment failed. Please try again.")}finally{$e.current=!1,fe(!1)}},[q,ce,M,Se,v,B,t,n,r,o,Re,i,d,ue,e,c,P,y]);return(0,l.jsxs)("div",{"data-testid":`flopay-stripe-method-form-${e}`,style:{display:"flex",flexDirection:"column"},children:[re&&(0,l.jsx)("div",{"data-testid":"flopay-apm-identity-fields",style:{display:"flex",flexDirection:"column",gap:"0.75rem",marginBottom:"0.75rem"},children:re&&(0,l.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:"0.375rem"},children:["Email address",(0,l.jsx)("input",{type:"email",autoComplete:"email",required:!0,value:Re,onChange:_e=>ne(_e.target.value),style:{minHeight:42,padding:"0 0.75rem",border:"1px solid #d1d5db",borderRadius:6}})]})}),(0,l.jsx)(Tt.PaymentElement,{onReady:()=>Ie("ready"),onLoadError:()=>{Ie("load_error"),qa(Vt(w),"stripe","apm")},onChange:_e=>{Pt(!!_e.complete)},options:{layout:{type:"accordion",defaultCollapsed:!1,radios:"never"},fields:{billingDetails:{email:"never"}},defaultValues:{billingDetails:{...o?.trim()?{name:o.trim()}:{},...(0,u.isValidEmail)(r?.trim())?{email:r?.trim()}:{}}}}}),(0,l.jsx)("button",{type:"button","data-testid":`flopay-stripe-method-pay-${e}`,onClick:()=>{Ee()},disabled:!Se||!L||H||M||ze!=="ready",style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:m,color:"white",border:"none",borderRadius:S,fontSize:"1rem",fontWeight:600,cursor:!Se||!L||H||M||ze!=="ready"?"not-allowed":"pointer",opacity:!Se||!L||H||M||ze!=="ready"?.5:1,transition:"opacity 120ms ease-out",...he??{}},children:H?"Processing\u2026":`Pay with ${(0,u.getStripeMethodDisplayName)(e)}`}),U&&(0,l.jsx)(Yr,{margin:"0.75rem 0 0",children:U})]})}function ds({sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:i,paymentElementMethods:d,stripeInstance:c,paymentElementBaseOptions:P,onTokenizedBody:y,onErrorChange:h,onButtonClick:v,onDecline:B,runBeforeButtonClick:M,onLoadStateChange:m,isProcessing:S=!1,submitButtonColor:he="#4A49FF",submitButtonBorderRadius:U=8,submitButtonStyle:w,buttonAppearance:ue,themeId:q,onExpandApm:ce,expandedApmMethod:H}){let{emitInstrument:fe}=(0,a.useContext)(_n),[$e,Se]=(0,a.useState)(null),[Pt,ze]=(0,a.useState)(null),Ie=(0,a.useRef)(!1),{request:Re,collect:ne,finish:re}=jr();(0,a.useEffect)(()=>{d.length>0&&c?m?.("ready"):c||m?.("loading")},[d.length,c,m]);let L=(0,a.useCallback)(async T=>{if(!c||Ie.current||S)return;Ie.current=!0,ze(T);let O=M?await M("card"):{proceed:!0};if(!O.proceed){Ie.current=!1,ze(null);return}v?.("card");let Ae=O.sessionId??e,ye=O.nonce??t,Q=Rr([O.accountPatch?.firstName,O.accountPatch?.lastName].filter(Boolean).join(" ")||r),Le=pn({email:O.accountPatch?.email?.trim()||n?.trim(),firstName:O.accountPatch?.firstName?.trim()||Q.firstName,lastName:O.accountPatch?.lastName?.trim()||Q.lastName});if(!(0,u.isValidEmail)(Le.email)){ze(null);let Oe=await ne((0,u.getStripeMethodDisplayName)(T),Le);if(!Oe){Ie.current=!1;return}Le=Oe,ze(T)}let rt=Le.email,ct=pn({...O.accountPatch,...Le});try{if(h?.(null),!Ae||!(0,u.isValidEmail)(rt))throw new Error("Missing sessionId or email for payment.");await o?.(Le);let Oe=await oa(i,fe,Ae,ye??"",{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:T,paymentMethodId:null,intentKind:"payment"});if(Oe.provider!=="stripe")throw new Error("Invalid provider returned for APM intent");let ee=Oe.clientSecret;if(typeof window<"u")try{localStorage.setItem(er,JSON.stringify({clientSecret:ee,sessionId:Ae,nonce:ye,accountPatch:ct,paymentMethodType:T,gateway:"stripe"}))}catch{}let{error:W,paymentIntent:V}=await c.confirmPayment({clientSecret:ee,confirmParams:{return_url:window.location.href,payment_method_data:{type:T,billing_details:{name:[Le.firstName,Le.lastName].filter(Boolean).join(" "),...rt?{email:rt}:{}}}},redirect:"if_required"});if(W){if(typeof window<"u")try{localStorage.removeItem(er)}catch{}let A=W.message??"Payment failed.";h?.(A),B?.(jt("card",A,{code:W.code})),await aa({billingApiUrl:i,sessionId:Ae,nonce:ye,request:{provider:"stripe",paymentMethodCategory:"apm",paymentMethodType:T,providerDeclineReason:W.code??"provider_declined"}});return}let Be=V?.status;if(!Ko(Be)){if(typeof window<"u")try{localStorage.removeItem(er)}catch{}let A=Be==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";h?.(A),B?.(jt("card",A,{code:Be??"missing_payment_intent"}));return}if(typeof window<"u")try{localStorage.removeItem(er)}catch{}let Je=typeof V?.payment_method=="string"?V.payment_method:V?.payment_method?.id;y({id:Je??V?.id,type:"card",threeDSecureActionResultTokenId:V?.id,gateway:"stripe",paymentMethodType:T},{accountPatch:ct,paymentMethodCategory:"apm",sessionId:Ae,nonce:ye})}catch(Oe){h?.(Oe instanceof Error?Oe.message:"Payment failed. Please try again.")}finally{Ie.current=!1,ze(null)}},[c,S,M,v,e,t,n,ne,i,fe,r,o,y,h,B]),[Ee,_e]=(0,a.useState)(null),J=ce?H??null:Ee,we=(0,a.useCallback)(T=>{Ie.current||S||J&&J!==T||((0,u.needsStripeMethodExplicitConfirm)(T)?ce?ce(T):_e(T):L(T))},[J,S,L,ce]),ve=(0,a.useMemo)(()=>Ee?{...P,paymentMethodTypes:[Ee]}:null,[Ee,P]);return(0,l.jsx)("div",{"data-testid":"flopay-stripe-payment-element-region",style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:Re?(0,l.jsx)(Vr,{identity:Re.identity,methodLabel:Re.methodLabel,onComplete:re,onCancel:()=>re(null)},Re.id):d.map(T=>{let O=H===T,Ae=Pt===T,ye=Pt!==null&&Pt!==T||H!=null&&H!==T;return(0,l.jsxs)(a.default.Fragment,{children:[(0,l.jsx)(Bl,{method:T,themeId:q,submitting:Ae,disabled:ye,highlighted:O,hasNextStep:(0,u.needsStripeMethodExplicitConfirm)(T),onClick:()=>we(T),backgroundColor:ue?.backgroundColor,borderColor:ue?.borderColor,textColor:ue?.textColor,borderRadius:ue?.borderRadius,fontFamily:ue?.fontFamily}),!ce&&Ee===T&&ve&&c&&(0,l.jsx)(Tt.Elements,{stripe:c,options:ve,children:(0,l.jsx)(Ua,{method:T,sessionId:e,nonce:t,email:n,billingName:r,onBuyerIdentityReady:o,billingApiUrl:i,onTokenizedBody:y,onErrorChange:h,onDecline:B,onCancel:()=>_e(null),runBeforeButtonClick:M,onButtonClick:v,isProcessing:S,submitButtonColor:he,submitButtonBorderRadius:U,submitButtonStyle:w})},T)]},T)})})}function Fl({sessionId:e,nonce:t,billingApiUrl:n,email:r,userId:o,onComplete:i,onError:d,onDecline:c,onTokenizedBody:P,firstName:y,lastName:h,chv:v,className:B,isProcessing:M,error:m,onErrorChange:S,showPayPal:he=!0,showStripe:U=!0,enabledPaymentMethods:w,enabledPaymentMethodCountries:ue,showApplePay:q=!0,showGooglePay:ce=!0,layout:H="default",theme:fe,buttonsTheme:$e,buttonsStyles:Se,appearance:Pt,cardButtonContent:ze,cardBackButtonContent:Ie,cardTitleContent:Re,showSecurityFooter:ne,onButtonClick:re,onBeforeButtonClick:L,onBuyerIdentityReady:Ee,enableAVS:_e,cardFieldOrder:J,cardPreFormSlot:we,avsLayout:ve="row",country:T,zip:O,addressLine1:Ae,addressLine2:ye,city:Q,state:Le,onCountryChange:rt,onZipChange:ct,avsCheck:Oe,checkoutType:ee,checkoutLayout:W,totalAmount:V=0,currency:Be="usd",initialCardOpen:Je=!1,directPaypal:A,isSubscription:oe=!1,session:F,dataAttachmentPending:R=!1,dataAttachmentRequiresIdentity:at=!1,debug:Ct=!1}){let ke=sr(),pt=Ho(),Fe=(0,a.useContext)(Kn),{emitInstrument:mt}=(0,a.useContext)(_n),Et=F??Fe.session,C=Et?.gateways?.paypal?.providerObjectType??A?.providerObjectType,te=R||Fe.claimPending===!0,Xe=at||Fe.claimRequiresIdentity===!0,He=te&&!Xe,zt=$i(),[Lt,G]=(0,a.useState)(!1),[dt,Qt]=(0,a.useState)(null),[gt,Ut]=(0,a.useState)(T??"US"),[An,Bn]=(0,a.useState)(O??""),[Fn,Jt]=(0,a.useState)(Ae??""),[Wn,mn]=(0,a.useState)(ye??""),[qt,rr]=(0,a.useState)(Q??""),[wt,Dn]=(0,a.useState)(Le??""),[it,pr]=(0,a.useState)(""),[kt,Pn]=(0,a.useState)({}),It=(0,a.useRef)(O??""),Kt=(0,a.useRef)(T??"US"),yn=(0,a.useRef)(Ae??""),on=(0,a.useRef)(ye??""),Cn=(0,a.useRef)(Q??""),en=(0,a.useRef)(Le??""),Sn=(0,a.useRef)(""),Nt=(0,a.useRef)({});(0,a.useEffect)(()=>{let s=(_,j,Ne,Y,De)=>{if(Nt.current[_])return;let Ke=j?.trim();!Ke||Ke===Ne.current||(Ne.current=Ke,Y(Ke),De?.(Ke))};s("country",T,Kt,Ut,rt),s("zip",O,It,Bn,ct),s("addressLine1",Ae,yn,Jt),s("addressLine2",ye,on,mn),s("city",Q,Cn,rr),s("state",Le,en,Dn)},[T,O,Ae,ye,Q,Le,rt,ct]);let se=(0,a.useMemo)(()=>(0,u.resolveAVSConfig)(_e),[_e]),an=se!==null,Ln=(0,a.useMemo)(()=>(0,u.isAuthorizationOnlySession)(F),[F]),Gn=!!F?.vault?.html,Cr=!!F?.gateways?.pcivault,mr=!!(F?.gateways?.stripe?.enabledPaymentMethods??w)?.includes("card"),Mt=Gn||mr||Cr,Ye=!!(U&&Mt&&ke&&e),[yr,E]=(0,a.useState)(()=>H!=="buttons"||Je?e??null:null),[ot,$t]=(0,a.useState)(0),fn=H!=="buttons"||Je||!!e&&yr===e,Pe=(0,a.useMemo)(()=>!ke||!Ye||!e||!fn?null:ke.cardCapture({sessionId:e,captureMethod:F?.captureMethod}),[ke,Ye,e,fn,F?.captureMethod]),tn=(0,a.useMemo)(()=>{let s=gt,_=se?(0,u.isAVSFieldVisible)(se.postal_code,s):!1;return Tl(s,An,_)},[se,gt,An]),{avsInvalid:wr,invalidAvsFields:Br}=(0,a.useMemo)(()=>{let s={line1:!1,city:!1,state:!1,zip:!1};if(!Ye||!se)return{avsInvalid:!1,invalidAvsFields:s};let _=gt,j=(De,Ke)=>(0,u.isAVSFieldVisible)(De,_)&&!Ke.trim(),Ne={line1:j(se.address_line_1,Fn),city:j(se.city,qt),state:j(se.state,wt),zip:tn.empty||tn.malformed};return{avsInvalid:Ne.line1||Ne.city||Ne.state||Ne.zip,invalidAvsFields:Ne}},[Ye,se,gt,Fn,qt,wt,tn]),[sn,fr]=(0,a.useState)(!1),[Jn,Nn]=(0,a.useState)(!1),[At,On]=(0,a.useState)(!1),[Xn,ln]=(0,a.useState)({line1:!1,city:!1,state:!1}),Xt=(0,a.useRef)(!1),zn=(0,a.useRef)({email:!1,line1:!1,city:!1,state:!1,zip:!1}),Un=(0,a.useRef)(!1),st=(0,a.useCallback)(s=>{zn.current[s]=!0,Un.current=!0},[]),cn=(0,a.useCallback)(s=>!Xt.current&&zn.current[s],[]),dn=(0,a.useCallback)(s=>{cn(s)&&ln(_=>_[s]?_:{..._,[s]:!0})},[cn]),[qn,wn]=(0,a.useState)(()=>Na(F?.vault)),[xe,Zt]=(0,a.useState)(Je&&Mt?"card":"buttons"),[Bt,gr]=(0,a.useState)(null),$n=xe==="expanding"||xe==="card",hr=F?.gateways?.stripe?"stripe":void 0,gn=(0,a.useCallback)(()=>{mt?.({class:"card_surface",provider:hr})},[hr,mt]),kn=(0,a.useRef)(null),Ft=(0,a.useCallback)(s=>{kn.current&&clearTimeout(kn.current),kn.current=setTimeout(()=>{kn.current=null,s()},Tr)},[]);(0,a.useEffect)(()=>()=>{kn.current&&clearTimeout(kn.current)},[]);let N=(0,a.useCallback)(()=>{gn(),E(e??null),$t(s=>s+1),Zt("expanding"),Ft(()=>Zt("card"))},[Ft,gn,e]),$=(0,a.useCallback)(()=>{Zt("collapsing"),Ft(()=>Zt("buttons"))},[Ft]),ae=(0,a.useCallback)(s=>{gr(s),Zt("apm-expanding"),Ft(()=>Zt("apm-form"))},[Ft]),ie=(0,a.useCallback)(()=>{Zt("apm-collapsing"),Ft(()=>{Zt("buttons"),gr(null)})},[Ft]);(0,a.useEffect)(()=>{H==="buttons"&&Je&&Mt&&(E(e??null),Zt("card"))},[H,Je,Mt,e]);let[Te,z]=(0,a.useState)(null),X=(0,a.useRef)(!1),f=(0,a.useRef)(null),K=(0,a.useRef)("idle"),[Z,ut]=(0,a.useState)(null),yt=(0,a.useRef)(Z);(0,a.useEffect)(()=>{yt.current=Z},[Z]);let de=n||zt,Me=(0,a.useRef)(null),Ht=(0,a.useMemo)(()=>{if(Ee||Fe.claimBuyerIdentity||F?.buyerIdentified!==!1||!e||!t)return;let s=`${de}|${e}|${t}`;Me.current?.key!==s&&(Me.current={key:s,claim:qr(new dr.PaymentAPI(de,{telemetry:!1}),e,t,{...o?{userId:o}:{},...y?{firstName:y}:{},...h?{lastName:h}:{}})});let _=Me.current.claim;return async j=>{await _(j)}},[Ee,Fe.claimBuyerIdentity,F?.buyerIdentified,e,t,de,o,y,h]),tt=Ee??Fe.claimBuyerIdentity??Ht,g=m??dt,p=(0,a.useMemo)(()=>(0,u.resolveTheme)(fe),[fe]),b=(0,a.useMemo)(()=>{let s=p?.buttonsLayout??(0,u.resolveButtonsLayoutTheme)($e);return Se?{...s,...Se,cardButton:{...s.cardButton,...Se.cardButton},cardFormContainer:{...s.cardFormContainer,...Se.cardFormContainer},backButton:{...s.backButton,...Se.backButton},backButtonIcon:{...s.backButtonIcon,...Se.backButtonIcon},submitButton:{...s.submitButton,...Se.submitButton},title:{...s.title,...Se.title}}:s},[p,$e,Se]),Ce=Pt??p?.appearance,pe=(0,a.useMemo)(()=>na({appearance:Ce,buttonsStyles:b,layout:H}),[Ce,b,H]),We=Fe.inlineSessionPatchProcessing??!1,Ze=(M??Lt)||We,le=de.replace(/\/+$/,""),D=(0,a.useMemo)(()=>xa({userId:o,email:r,firstName:y,lastName:h,country:T,zip:O},kt),[o,r,y,h,T,O,kt]),me=[D.firstName,D.lastName].filter(s=>!!s?.trim()).join(" "),Ge=!(0,u.isValidEmail)(D.email?.trim()),je=(0,a.useRef)(null);Ye&&je.current===null&&(je.current=Ge);let ft=Ye&&(je.current??Ge),Ve=(0,a.useMemo)(()=>Ml(it,ft),[it,ft]),Ot=Ve.empty||Ve.malformed,hn=(0,a.useMemo)(()=>ke?ke.getRawProvider():null,[ke]),Fr=(0,a.useMemo)(()=>pt?pt.getRawProvider():null,[pt]),Qr=V||100,xo=(0,a.useMemo)(()=>Ce?(0,dr.toStripeAppearance)(Ce):null,[Ce]),To=xo?{appearance:xo}:null,ei=(0,a.useMemo)(()=>{let s=xo??{},_=s.rules??{};return{...s,rules:{..._,".AccordionItem":{padding:"10px 14px",boxShadow:"none",..._[".AccordionItem"]??{}},".AccordionItemContents":{padding:"6px 14px 12px",boxShadow:"none",..._[".AccordionItemContents"]??{}}}}},[xo]),ti=(0,a.useMemo)(()=>{let s=Oi(V);return{...s,currency:Be.toLowerCase(),paymentMethodCreation:"manual",...s.mode==="payment"?{captureMethod:"manual"}:{},...To}},[V,Be,To]),ni=(0,a.useMemo)(()=>({mode:"payment",amount:Qr,currency:Be.toLowerCase(),captureMethod:"manual",setupFutureUsage:"off_session",...To}),[Qr,Be,To]),ge=(0,a.useCallback)(s=>{Qt(s),S?.(s)},[S]),ma=(0,a.useRef)(""),[ri,Es]=(0,a.useState)(!1),ya=(0,a.useCallback)(()=>{Es(!0)},[]);(0,a.useEffect)(()=>{if(!Ye||!ft||!tt||!ri||Ot||ma.current)return;let s=pn({email:(0,u.isValidEmail)(D.email?.trim())?D.email?.trim():Sn.current.trim(),firstName:D.firstName?.trim(),lastName:D.lastName?.trim()});ma.current=JSON.stringify(s),Pn(_=>({..._,...s})),Promise.resolve(tt(s)).catch(_=>{ma.current="",ge(_ instanceof Error?_.message:"Failed to attach buyer details.")})},[Ye,ft,tt,ri,Ot,D.email,D.firstName,D.lastName,ge]),(0,a.useEffect)(()=>{!Ye||!Pe||Pe.setCardFieldOrder?.(J??null,se==null&&!ft)},[Ye,Pe,J,se,ft]),(0,a.useEffect)(()=>{(xe==="expanding"||xe==="collapsing"||xe==="apm-expanding"||xe==="apm-collapsing")&&ge(null)},[xe,ge]);let jn=(0,a.useCallback)((s,_,j)=>{c?.(jt(s,_,j))},[c]),Dr=(0,a.useCallback)((s,_,j)=>{let Ne=j?.popupBlocked??vr(_),Y=_l(s,Ne),De=_r(j?.code)??ir(_)??"external_payment_method_failed",Ke=new u.FloPayError(Y,"api_error",{code:"external_payment_method_failed",param:s});z(null),H==="buttons"&&(Zt("buttons"),gr(null)),ge(Y),d?.(Ke),console.error("[FloPay] External payment method failed:",{method:s,code:De,popupBlocked:Ne})},[H,d,ge]);(0,a.useEffect)(()=>{if(!Ye||!e){wn(null);return}let s=Na(F?.vault);if(s){wn(s);return}if(!fn){wn(null);return}wn(null);let _=!0;return new dr.PaymentAPI(le).getVaultCapture(e,t).then(j=>{if(!_)return;let Ne=Na(j);Ne?wn(Ne):ge("Failed to load the secure card form.")}).catch(j=>{_&&ge(j instanceof Error?j.message:"Failed to load the secure card form.")}),()=>{_=!1}},[Ye,fn,ot,e,F?.vault,le,t,ge]);let Zn=(0,a.useRef)({onComplete:i,onError:d,updateError:ge,emitDecline:jn,resolvedAccount:D,avsConfig:se,avsCheckProp:Oe,sessionId:e,nonce:t,baseUrl:le,captureMethod:F?.captureMethod,paymentId:F?.paymentId,authorizationExpiresAt:F?.authorizationExpiresAt});Zn.current={onComplete:i,onError:d,updateError:ge,emitDecline:jn,resolvedAccount:D,avsConfig:se,avsCheckProp:Oe,sessionId:e,nonce:t,baseUrl:le,captureMethod:F?.captureMethod,paymentId:F?.paymentId,authorizationExpiresAt:F?.authorizationExpiresAt};let fa=(0,a.useRef)(!1),oi=(0,a.useCallback)(()=>{let{resolvedAccount:s,avsConfig:_,avsCheckProp:j}=Zn.current,Ne=s.email?.trim(),Y=(0,u.isValidEmail)(Ne)?Ne:Sn.current.trim();if(!(0,u.isValidEmail)(Y))return null;let De=s.firstName?.trim(),Ke=s.lastName?.trim(),lt=Kt.current||s.country||"US",Yt=_?(0,u.isAVSFieldVisible)(_.state,lt):!1,ht=_?(0,u.isAVSFieldVisible)(_.address_line_1,lt):!1,bt=_?(0,u.isAVSFieldVisible)(_.postal_code,lt):!1,nt=_?(0,u.isAVSFieldVisible)(_.city,lt):!1,nn=_?(0,u.isAVSFieldVisible)(_.address_line_2,lt):!1,Qe=ht&&!Yt&&bt?(0,u.getStateFromPostalCode)(lt,(It.current??"").trim()):null,rn=Yt?en.current:Qe;return{accountData:{userId:s.userId??"",email:Y,...De?{firstName:De}:{},...Ke?{lastName:Ke}:{},...bt&&It.current?{zip:It.current}:{},...nt&&Cn.current?{city:Cn.current}:{},...rn?{state:rn}:{},...ht&&yn.current?{addressLine1:yn.current}:{},...nn&&on.current?{addressLine2:on.current}:{},country:lt},...j!==void 0?{avsCheck:j}:{},..._?{avsConfig:{country:(0,u.isAVSFieldVisible)(_.country,lt),postal_code:bt,address_line_1:ht,address_line_2:nn,city:nt,state:Yt}}:{}}},[]),ai=(0,a.useRef)(te);ai.current=te,(0,a.useEffect)(()=>{te||g!==os||Zn.current.updateError(null)},[te,g]),(0,a.useEffect)(()=>{!Ye||!Pe||Pe.setSubmitGate?.(wr||te||Ot)},[Ye,Pe,wr,te,Ot]),(0,a.useEffect)(()=>{if(!Ye||!Pe)return;fa.current=!1;let s=!1,_=Pe.on("submitting",()=>{fr(!0),f.current&&clearTimeout(f.current),K.current="validation-window",f.current=setTimeout(()=>{f.current=null,K.current==="validation-window"&&(K.current="processing")},Cl),z("processing");let{baseUrl:Ke,sessionId:lt,nonce:Yt,updateError:ht,onError:bt}=Zn.current;if(!lt||!Yt)return;let nt=oi();if(!nt){ht("Enter a valid email address."),K.current="idle",z(null);return}new dr.PaymentAPI(Ke).patchAccountSnapshot(lt,Yt,nt,{telemetryMode:"best_effort"}).catch(nn=>{if(!Sl(nn))return;let Qe=nn instanceof Error?nn.message:"Please check your billing address and try again.";ht(Qe),K.current="idle",z(null),bt?.(nn instanceof u.FloPayError?nn:new u.FloPayError(Qe,"api_error"))})}),j=Pe.on("complete",async Ke=>{if(Wr(Ke.sessionId??Zn.current.sessionId),K.current="terminal",z("success"),await new Promise(ht=>setTimeout(ht,1200)),fa.current)return;fa.current=!0;let lt=Zn.current,Yt=(0,u.isAuthorizationOnlySession)(lt)||Ke.outcome==="authorized";Zn.current.onComplete?.(Yt?{status:"authorized",paymentIntentId:Ke.intentId,paymentId:Ke.paymentId??lt.paymentId,sessionId:Ke.sessionId??lt.sessionId,authorizationExpiresAt:Ke.authorizationExpiresAt??lt.authorizationExpiresAt,checkoutMethod:"card"}:{status:"succeeded",paymentIntentId:Ke.intentId,checkoutMethod:"card"})}),Ne=Pe.on("decline",async Ke=>{let{updateError:lt,emitDecline:Yt}=Zn.current,ht=Ke.message??"Your payment was declined. Please try another card or contact your bank.";K.current="terminal",lt(ht),z("error");let bt=Ke.failureOutcome??(0,u.normalizeCheckoutFailureOutcome)(Ke.declineReason)??"authorization_declined";Yt("card",ht,{code:bt,declineCode:bt}),await new Promise(nt=>setTimeout(nt,1500)),!s&&(K.current="idle",z(null))}),Y=Pe.on("error",async Ke=>{let{updateError:lt,onError:Yt}=Zn.current,ht=Ke.message??"There was a problem processing your payment. Please try again.";K.current="terminal",lt(ht),z("error"),Yt?.(new u.FloPayError(ht,"api_error",{code:Ke.failureOutcome??"capture_failed"})),await new Promise(bt=>setTimeout(bt,1500)),!s&&(K.current="idle",z(null))}),De=Pe.on("blocked",()=>{if(!ai.current){fr(!0);return}ya(),Zn.current.updateError(os)});return()=>{s=!0,f.current&&(clearTimeout(f.current),f.current=null),K.current="idle",_(),j(),Ne(),Y(),De()}},[Ye,Pe,ya,oi]);let Qn=!!A?.clientId,eo=Array.isArray(w),Mo=eo&&w.length>0,_s=eo&&w.includes("paypal"),{expressMethods:Ao,paymentElementMethods:to}=(0,a.useMemo)(()=>(0,u.partitionStripeMethods)(w,{excludePaypal:Qn}),[w,Qn]),ii=Qn||!!pt,xs=(0,a.useMemo)(()=>ii?Ao.filter(s=>s!=="paypal"):Ao,[Ao,ii]),Ts=(0,a.useMemo)(()=>{let s=[];return q&&s.push("apple_pay"),ce&&s.push("google_pay"),s},[q,ce]),Bo=eo?xs:Ts,Ms=U&&Bo.length>0,ga=an?gt:T,Fo=(0,a.useMemo)(()=>{let s=ga?.trim().toUpperCase();return s?ue?to.filter(_=>{let j=ue[_];return!j||j.length===0||j.includes(s)}):(0,u.filterStripeMethodsByCountry)(to,ga):to},[to,ga,ue]),ha=(0,a.useMemo)(()=>({mode:"payment",amount:Qr,currency:Be.toLowerCase(),paymentMethodCreation:"manual",appearance:ei}),[Qr,Be,ei]),[si,li]=(0,a.useState)("loading"),[ci,di]=(0,a.useState)("loading"),[ui,pi]=(0,a.useState)("loading"),[As,ba]=(0,a.useState)(!1),[mi,va]=(0,a.useState)("loading"),[Do,Bs]=(0,a.useState)();(0,a.useEffect)(()=>{Bs(es())},[]);let yi=he&&(Qn||(eo?_s:Do===!1)),fi=U&&Ms,no=!He&&yi&&Qn,gi=mi==="retrying"||mi==="exhausted",ro=!He&&yi&&!!Fr&&(!Qn||gi),oo=!He&&fi&&!!hn,ao=!He&&U&&Mo&&Fo.length>0&&!!hn,Fs=no&&!gi?As:ro&&ss(si),Ds=oo&&ss(ci),Ls=ao&&ui!=="load_error",hi=s=>s==="loading"||s==="ready",bi=no||ro&&hi(si)||oo&&hi(ci)||ao&&ui!=="load_error",Lo=(0,a.useRef)(!1);(0,a.useEffect)(()=>{if(!Lo.current){if(!U&&!he){Lo.current=!0;let s=new u.FloPayError("FloPay: both `showStripe` and `showPayPal` are false \u2014 nothing to render.","validation_error");d?.(s),ge(s.message)}else if(!U&&he&&!Qn&&!Fr){Lo.current=!0;let s=new u.FloPayError("FloPay: `showStripe` is false and no PayPal gateway is configured for this session \u2014 nothing to render.","validation_error");d?.(s),ge(s.message)}else if(Do!==void 0&&!He&&!Mt&&!bi){Lo.current=!0;let s=new u.FloPayError("FloPay: this checkout session has no vault card capability and no usable supported non-card payment methods. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});d?.(s),ge(s.message)}}},[U,he,Qn,Fr,Do,He,Mt,bi,d,ge]);let vi=(0,a.useRef)(!1);(0,a.useEffect)(()=>{if(vi.current||!Mo)return;let s=[];q!==!0&&s.push("showApplePay"),ce!==!0&&s.push("showGooglePay"),s.length!==0&&(vi.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.`))},[Mo,q,ce]);let Pi=(0,a.useCallback)((s,_)=>Fe.applyInlineSessionPatch?Fe.applyInlineSessionPatch(s).then(j=>({error:null,sessionId:j.sessionId||e,nonce:j.session?.clientSecret||t})).catch(j=>{let Ne=is(_,j);return ge(Ne.message),d?.(Ne),{error:Ne,sessionId:e,nonce:t}}):Promise.resolve({error:null,sessionId:e,nonce:t}),[Fe.applyInlineSessionPatch,t,d,e,ge]),Vn=(0,a.useCallback)(async s=>{if(!L)return{proceed:!0};try{let _=await L({method:s,sessionId:e||void 0,createSession:Fe.inlineSessionDraft});if(_===!1)return{proceed:!1};if(_&&typeof _=="object"){_.account&&Pn(Ne=>({...Ne??{},..._.account}));let j=await Pi(_,s);return j.error?{proceed:!1,accountPatch:_.account}:{proceed:!0,accountPatch:_.account,sessionId:j.sessionId,nonce:j.nonce}}return{proceed:!0}}catch(_){let j=is(s,_);return ge(j.message),d?.(j),{proceed:!1}}},[Pi,Fe.inlineSessionDraft,L,d,e,ge]),Ci=(0,a.useCallback)(async(s,_)=>{if(X.current)return;X.current=!0,G(!0),z("processing"),ge(null);let j=_?.sessionId??e,Ne=_?.nonce??t,Y=xa(D,_?.accountPatch),De=_?.completionPaymentMethodId??yo(s),Ke=s.originalPaymentMethodId?{...s,originalPaymentMethodId:void 0}:s,lt=s.gateway==="stripe"?"stripe":s.gateway==="paypal"||s.isPaypal?"paypal":void 0,Yt=()=>{mt?.({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:"process_payment",provider:lt})};try{let bt=await new dr.PaymentAPI(le).processPayment(Y.userId??"",{sessionId:j,nonce:Ne,paymentMethodCategory:_?.paymentMethodCategory??Rl(s),tokenizedData:Ke,accountData:{userId:Y.userId??"",email:Y.email??"",...Y.firstName?{firstName:Y.firstName}:{},...Y.lastName?{lastName:Y.lastName}:{},...se?(()=>{let Qe=Kt.current,rn=(0,u.isAVSFieldVisible)(se.state,Qe),En=(0,u.isAVSFieldVisible)(se.address_line_1,Qe),Wt=(0,u.isAVSFieldVisible)(se.postal_code,Qe),uo=En&&!rn&&Wt?(0,u.getStateFromPostalCode)(Qe,(It.current??"").trim()):null,po=rn?en.current:uo;return{country:Qe,...Wt&&It.current?{zip:It.current}:{},...(0,u.isAVSFieldVisible)(se.city,Qe)&&Cn.current?{city:Cn.current}:{},...po?{state:po}:{},...En&&yn.current?{addressLine1:yn.current}:{},...(0,u.isAVSFieldVisible)(se.address_line_2,Qe)&&on.current?{addressLine2:on.current}:{}}})():{}},chv:v,avsCheck:Oe??!1,checkoutType:ee,checkoutLayout:W,avsConfig:se?{country:(0,u.isAVSFieldVisible)(se.country,Kt.current),postal_code:(0,u.isAVSFieldVisible)(se.postal_code,Kt.current),address_line_1:(0,u.isAVSFieldVisible)(se.address_line_1,Kt.current),address_line_2:(0,u.isAVSFieldVisible)(se.address_line_2,Kt.current),city:(0,u.isAVSFieldVisible)(se.city,Kt.current),state:(0,u.isAVSFieldVisible)(se.state,Kt.current)}:void 0});if(bt.ok){let Qe=bt.status===204?null:await bt.json().catch(()=>null),rn=(0,u.isAuthorizationOnlySession)(F)||Qe?.status==="authorized";Wr(j),z("success"),ut(null),await new Promise(En=>setTimeout(En,1200)),i?.(rn?{status:"authorized",...typeof Qe?.paymentId=="string"?{paymentId:Qe.paymentId}:F?.paymentId?{paymentId:F.paymentId}:{},sessionId:typeof Qe?.sessionId=="string"?Qe.sessionId:j,...typeof Qe?.authorizationExpiresAt=="string"?{authorizationExpiresAt:Qe.authorizationExpiresAt}:F?.authorizationExpiresAt?{authorizationExpiresAt:F.authorizationExpiresAt}:{},paymentIntentId:s.threeDSecureActionResultTokenId,paymentMethodId:De,checkoutMethod:s.isPaypal?"paypal":"card"}:{status:"succeeded",paymentIntentId:s.threeDSecureActionResultTokenId,paymentMethodId:De,checkoutMethod:s.isPaypal?"paypal":"card"});return}let nt=await bt.json().catch(()=>null);if(nt?.type==="paypal_redirect_required"){let Qe=nt.threeDSecureToken,rn=nt.paymentMethodId||s.id||"";if(!ke||!Qe){z("error"),ge("PayPal authorization required but no token provided.");return}try{let En=pt?.getRawProvider();if(!En){ge("PayPal is not available.");return}let Wt={return_url:window.location.href};rn&&(Wt.payment_method=rn);let{error:uo}=await En.confirmPayment({clientSecret:Qe,confirmParams:Wt,redirect:"if_required"});if(uo){z("error");let po=uo.message??"PayPal payment failed.";ge(po),jn("paypal",po,{code:uo.code})}}catch(En){z("error"),ge(En instanceof Error?En.message:"PayPal authorization failed.")}return}if(nt?.type==="paypal_direct_required"){let Qe=nt.orderId;if(!Qe){z("error"),ge("PayPal retry required but no order id provided.");return}let rn=yt.current?.attempts??0;if(rn>=2){z("error"),ge("PayPal payment could not be completed after multiple attempts."),jn("paypal","paypal_direct_required retry limit exceeded");return}ba(!1),va("loading"),ut({orderId:Qe,attempts:rn+1}),z(null);return}(0,u.classifyPaymentRejection)(bt.status,nt)||Yt(),z("error");let nn=nt?.message??"Payment failed. Please try again.";ge(nn),jn(s.isPaypal?"paypal":"card",nn,{code:nt?.code??nt?.gatewayErrorCode,declineCode:nt?.declineCode??nt?.gatewayDeclineReason}),await new Promise(Qe=>setTimeout(Qe,1500))}catch(ht){us(ht)||Yt(),z("error"),ge(ht instanceof Error?ht.message:"An unexpected error occurred"),await new Promise(bt=>setTimeout(bt,1500))}finally{G(!1),z(null),X.current=!1}},[le,e,t,D,se,Oe,ee,W,v,ke,pt,F,i,ge,jn,mt]),In=(0,a.useCallback)((s,_)=>{P?P(s):Ci(s,_)},[P,Ci]),Si=(0,a.useRef)(!1);(0,a.useEffect)(()=>{if(typeof window>"u"||Si.current)return;let s=new URLSearchParams(window.location.search),_=s.get("payment_intent"),j=s.get("payment_intent_client_secret"),Ne=s.get("redirect_status");if(!_||!j)return;let Y=bt=>{let nt=localStorage.getItem(bt);if(!nt)return null;try{return JSON.parse(nt)}catch{return localStorage.removeItem(bt),null}},De=Y(er)??Y(rs),Ke;if(De?.clientSecret){if(De.clientSecret!==j)return;Ke={...De.accountPatch?{accountPatch:De.accountPatch}:{},...De.sessionId?{sessionId:De.sessionId}:{},...De.nonce?{nonce:De.nonce}:{}}}else if(De?.sessionId&&De.sessionId!==e)return;Si.current=!0,localStorage.removeItem(er),localStorage.removeItem(rs);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 Yt=De?.paymentMethodType??De?.tokenType??"card",ht="card";(async()=>{let bt=ke?.getRawProvider();if(!bt){let Wt="Payment is not available \u2014 please refresh and try again.";ge(Wt),jn(ht,Wt);return}if(Ne==="failed"){let Wt="Payment was declined. Please try again.";ge(Wt),jn(ht,Wt);return}let{paymentIntent:nt,error:nn}=await bt.retrievePaymentIntent(j);if(nn){let Wt=nn.message??"Failed to retrieve payment status.";ge(Wt),jn(ht,Wt,{code:nn.code});return}let Qe=nt?.status,rn=Ko(Qe);if(!nt||!rn){let Wt=Qe==="canceled"?"Payment was canceled.":"Payment was not completed. Please try again.";ge(Wt),jn(ht,Wt,{code:Qe??"missing_payment_intent"});return}let En=typeof nt.payment_method=="string"?nt.payment_method:nt.payment_method?.id;In({id:En??De?.paymentMethodId??De?.tokenId??nt.id,type:"card",threeDSecureActionResultTokenId:nt.id,gateway:De?.gateway??"stripe",paymentMethodType:Yt},Ke)})()},[e,In,ke,ge,jn]);let Pa=(0,a.useCallback)(s=>{s.preventDefault()},[]);if(!(ke!==null))return(0,l.jsx)("div",{"data-testid":"flopay-loading","aria-busy":"true",children:"Loading payment form..."});let io=H==="buttons",un=Ce?.variables,Ns=new Set(["#FFFFFF","#ffffff","#fff","#FFF","white"]),Ca=un?.colorBackground,Os=Ca&&!Ns.has(Ca)?Ca:void 0,so=b.cardInputBorder??(io?"#e5e7eb":"#A4A4FF"),wi=un?.colorDanger??"#dc2626",Rt=s=>Br[s]&&(Xn[s]||sn),No=Ot&&(At||sn),Rn=s=>s?wi:so,Oo=(tn.malformed||tn.empty)&&(Jn||sn),zs=Rn(Oo),Sa=b.cardFormContainer?.backgroundColor??Os??(io?"white":"#EDEDFF"),Lr=b.cardInputBackground??un?.colorBackground??"white",wa=Or(Ie),ki=Or(Re),Nr=b.nameInput,Ii=b.cardInputFontSize??Al(Nr?.fontSize)??un?.fontSizeBase??"16px",Ri=typeof Nr?.fontFamily=="string"?Nr.fontFamily:un?.fontFamily??"Poppins, sans-serif",Ei=La(Nr?.fontWeight)??400,Us=b.cardInputColor??(typeof Nr?.color=="string"?Nr.color:void 0)??un?.colorText??"#262833",qs=b.cardInputPlaceholderColor??"#9ca3af",_t=un?.borderRadius??"8px",kr=un?.borderRadius??b.cardButton?.borderRadius??_t,Ir=un?.colorPrimary??"#4A49FF",$s=un?.colorPrimaryHover??Zr(Ir,.12),ka=un?.colorText??"#262833",Ia={fontSize:Ii,fontFamily:Ri,fontWeight:Ei,color:Us,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"},lo={marginTop:"0.375rem",...Ia,fontSize:"0.75rem",lineHeight:1.4,color:wi},js={"--flopay-input-placeholder-color":qs,"--flopay-input-font-size":Ii,"--flopay-input-font-family":Ri,"--flopay-input-font-weight":String(Ei)},co=b.cardFormContainer??{},Ra=co.padding??(io?"0":"1rem"),Ea=co.borderRadius??_t,Vs=Pe&&qn?(0,l.jsx)(Xr,{capture:Pe,html:qn.html,messageToken:qn.messageToken,expectedOrigin:qn.expectedOrigin,theme:pe,onReady:()=>{if(!ft&&!se||typeof document>"u")return;let s=()=>{let j=(document.querySelector('[data-testid="flopay-vault-identity-fields"]')??document.querySelector('[data-testid="flopay-avs-fields"]'))?.querySelector("input:not([disabled]), select:not([disabled])");if(j){Xt.current=!0;try{j.focus()}finally{Xt.current=!1}}};Un.current||s()},onError:s=>ge(s),onValidation:s=>{let _=K.current;(_==="idle"||_==="validation-window")&&(ge(s),s&&K.current==="validation-window"&&(f.current&&(clearTimeout(f.current),f.current=null),K.current="idle",z(null)))}}):(0,l.jsx)("div",{"data-testid":"flopay-vault-loading",style:{minHeight:120,display:"flex",alignItems:"center",justifyContent:"center",color:"#6b7280",fontSize:14},children:"Loading secure card form\u2026"}),_i=(0,l.jsxs)("div",{onFocusCapture:s=>{["INPUT","SELECT","TEXTAREA","IFRAME"].includes(s.target.tagName)&&gn()},style:{backgroundColor:Sa,borderRadius:Ea,...co,padding:Ra,...js,display:"flex",flexDirection:"column"},children:[(0,l.jsx)("style",{children:`
|
|
31
31
|
.flopay-shared-input::placeholder {
|
|
32
32
|
color: var(--flopay-input-placeholder-color);
|
|
33
33
|
opacity: 1;
|
|
@@ -35,13 +35,13 @@ ${zt.join(`
|
|
|
35
35
|
font-family: var(--flopay-input-font-family);
|
|
36
36
|
font-weight: var(--flopay-input-font-weight);
|
|
37
37
|
}
|
|
38
|
-
`}),io&&$n&&(0,l.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:Ye?-2:0},children:[(0,l.jsxs)("button",{type:"button",onClick:$,style:{display:"inline-flex",alignItems:"center",gap:wa?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:b.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...b.backButton},"aria-label":"Back to payment methods",children:[(0,l.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...b.backButtonIcon},children:(0,l.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,l.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,l.jsx)(Ur,{content:Ie})]}),ki?(0,l.jsx)("div",{style:{flex:1}}):(0,l.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:b.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...b.title},children:(0,l.jsx)(mo,{content:Re})})]}),!io&&!ki&&(0,l.jsx)("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:ka,order:Ye?-3:0,...b.title},children:(0,l.jsx)(mo,{content:Re})}),Ye&&we&&(0,l.jsx)("div",{style:{order:-2,width:"100%"},children:we}),Ye&&ft&&(0,l.jsxs)("div",{"data-testid":"flopay-vault-identity-fields",style:{order:-1,marginTop:"0.5rem"},children:[(0,l.jsx)("div",{style:{backgroundColor:Lr,border:`1px solid ${Rn(No)}`,borderRadius:_t,padding:"10px"},children:(0,l.jsx)("input",{className:"flopay-shared-input",id:"flopay-buyer-email",name:"email",type:"email",autoComplete:"email","aria-label":"Email address",placeholder:"Email address",value:it,onChange:s=>{st("email"),Sn.current=s.target.value,pr(s.target.value)},onPointerDown:()=>st("email"),onKeyDown:()=>st("email"),onBlur:()=>{cn("email")&&On(!0),Ot||ya()},disabled:Ze,required:!0,"aria-invalid":No||void 0,"aria-describedby":No?"flopay-buyer-email-error":void 0,"data-testid":"flopay-email",style:{width:"100%",border:"none",outline:"none",background:"transparent",...Ia}})}),No&&(0,l.jsx)("div",{id:"flopay-buyer-email-error",role:"alert","data-testid":"flopay-email-error",style:lo,children:Ve.empty?"Email address is required":"Enter a valid email address"})]}),se&&(0,l.jsx)("div",{style:{order:Ye?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let s=gt,
|
|
38
|
+
`}),io&&$n&&(0,l.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem",order:Ye?-2:0},children:[(0,l.jsxs)("button",{type:"button",onClick:$,style:{display:"inline-flex",alignItems:"center",gap:wa?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:b.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...b.backButton},"aria-label":"Back to payment methods",children:[(0,l.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...b.backButtonIcon},children:(0,l.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,l.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,l.jsx)(Ur,{content:Ie})]}),ki?(0,l.jsx)("div",{style:{flex:1}}):(0,l.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:b.titleFontSize??"1.05rem",color:"#262833",paddingRight:80,...b.title},children:(0,l.jsx)(mo,{content:Re})})]}),!io&&!ki&&(0,l.jsx)("div",{style:{textAlign:"center",fontWeight:600,fontSize:"1.1rem",padding:"0.5rem 0",color:ka,order:Ye?-3:0,...b.title},children:(0,l.jsx)(mo,{content:Re})}),Ye&&we&&(0,l.jsx)("div",{style:{order:-2,width:"100%"},children:we}),Ye&&ft&&(0,l.jsxs)("div",{"data-testid":"flopay-vault-identity-fields",style:{order:-1,marginTop:"0.5rem"},children:[(0,l.jsx)("div",{style:{backgroundColor:Lr,border:`1px solid ${Rn(No)}`,borderRadius:_t,padding:"10px"},children:(0,l.jsx)("input",{className:"flopay-shared-input",id:"flopay-buyer-email",name:"email",type:"email",autoComplete:"email","aria-label":"Email address",placeholder:"Email address",value:it,onChange:s=>{st("email"),Sn.current=s.target.value,pr(s.target.value)},onPointerDown:()=>st("email"),onKeyDown:()=>st("email"),onBlur:()=>{cn("email")&&On(!0),Ot||ya()},disabled:Ze,required:!0,"aria-invalid":No||void 0,"aria-describedby":No?"flopay-buyer-email-error":void 0,"data-testid":"flopay-email",style:{width:"100%",border:"none",outline:"none",background:"transparent",...Ia}})}),No&&(0,l.jsx)("div",{id:"flopay-buyer-email-error",role:"alert","data-testid":"flopay-email-error",style:lo,children:Ve.empty?"Email address is required":"Enter a valid email address"})]}),se&&(0,l.jsx)("div",{style:{order:Ye?-1:0},"data-testid":"flopay-avs-fields",children:(()=>{let s=gt,_=(Y=!1)=>({backgroundColor:Lr,border:`1px solid ${Rn(Y)}`,borderRadius:_t,marginTop:"0.5rem",padding:"10px"}),j=()=>({width:"100%",border:"none",outline:"none",background:"transparent",...Ia}),Ne=(0,u.getStateOptions)(s);return(0,l.jsxs)(l.Fragment,{children:[(0,u.isAVSFieldVisible)(se.address_line_1,s)&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)("div",{style:_(Rt("line1")),children:(0,l.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-address-line1",name:"billing-address-line1",placeholder:"Street Address (e.g. 123 Main St)",autoComplete:"billing address-line1",value:Fn,onChange:Y=>{st("line1"),Nt.current.addressLine1=!0,yn.current=Y.target.value,Jt(Y.target.value)},onPointerDown:()=>st("line1"),onKeyDown:()=>st("line1"),onBlur:()=>dn("line1"),disabled:Ze,required:!0,"aria-invalid":Rt("line1")||void 0,"aria-describedby":Rt("line1")?"flopay-billing-address-line1-error":void 0,"data-testid":"flopay-address-line1",style:j()})}),Rt("line1")&&(0,l.jsx)("div",{id:"flopay-billing-address-line1-error",role:"alert","data-testid":"flopay-address-line1-error",style:lo,children:"Street address is required"})]}),(0,u.isAVSFieldVisible)(se.address_line_2,s)&&(0,l.jsx)("div",{style:_(),children:(0,l.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-address-line2",name:"billing-address-line2",placeholder:"Apt, Suite, Unit (optional)",autoComplete:"billing address-line2",value:Wn,onChange:Y=>{Nt.current.addressLine2=!0,on.current=Y.target.value,mn(Y.target.value)},disabled:Ze,"data-testid":"flopay-address-line2",style:j()})}),((0,u.isAVSFieldVisible)(se.city,s)||(0,u.isAVSFieldVisible)(se.state,s))&&(0,l.jsxs)("div",{style:{display:"flex",gap:"0",marginTop:"0.5rem"},children:[(0,u.isAVSFieldVisible)(se.city,s)&&(0,l.jsx)("div",{style:{flex:1,backgroundColor:Lr,borderTop:`1px solid ${Rn(Rt("city"))}`,borderRight:`1px solid ${Rn(Rt("city"))}`,borderBottom:`1px solid ${Rn(Rt("city"))}`,borderLeft:`1px solid ${Rn(Rt("city"))}`,padding:"10px",borderTopLeftRadius:_t,borderBottomLeftRadius:_t,...(0,u.isAVSFieldVisible)(se.state,s)?{borderRight:"none",borderTopRightRadius:0,borderBottomRightRadius:0}:{borderRadius:_t}},children:(0,l.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-city",name:"billing-city",placeholder:"City",autoComplete:"billing address-level2",value:qt,onChange:Y=>{st("city"),Nt.current.city=!0,Cn.current=Y.target.value,rr(Y.target.value)},onPointerDown:()=>st("city"),onKeyDown:()=>st("city"),onBlur:()=>dn("city"),disabled:Ze,required:!0,"aria-invalid":Rt("city")||void 0,"aria-describedby":Rt("city")?"flopay-billing-city-error":void 0,"data-testid":"flopay-city",style:j()})}),(0,u.isAVSFieldVisible)(se.state,s)&&(0,l.jsx)("div",{style:{flex:1,backgroundColor:Lr,borderTop:`1px solid ${Rn(Rt("state"))}`,borderRight:`1px solid ${Rn(Rt("state"))}`,borderBottom:`1px solid ${Rn(Rt("state"))}`,borderLeft:`1px solid ${Rn(Rt("state"))}`,padding:"10px",borderTopRightRadius:_t,borderBottomRightRadius:_t,...(0,u.isAVSFieldVisible)(se.city,s)?{borderTopLeftRadius:0,borderBottomLeftRadius:0,borderLeft:`1px solid ${Rn(Rt("state")||Rt("city"))}`}:{borderRadius:_t}},children:Ne?(0,l.jsxs)("select",{id:"flopay-billing-state",name:"billing-state",value:wt,onChange:Y=>{st("state"),Nt.current.state=!0,en.current=Y.target.value,Dn(Y.target.value)},onPointerDown:()=>st("state"),onKeyDown:()=>st("state"),onBlur:()=>dn("state"),disabled:Ze,autoComplete:"billing address-level1",required:!0,"aria-invalid":Rt("state")||void 0,"aria-describedby":Rt("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:{...j(),cursor:"pointer"},children:[(0,l.jsx)("option",{value:"",children:(0,u.getStateLabel)(s)}),Ne.map(Y=>(0,l.jsx)("option",{value:Y.code,children:Y.name},Y.code))]}):(0,l.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-state",name:"billing-state",placeholder:(0,u.getStateLabel)(s),autoComplete:"billing address-level1",value:wt,onChange:Y=>{st("state"),Nt.current.state=!0,en.current=Y.target.value,Dn(Y.target.value)},onPointerDown:()=>st("state"),onKeyDown:()=>st("state"),onBlur:()=>dn("state"),disabled:Ze,required:!0,"aria-invalid":Rt("state")||void 0,"aria-describedby":Rt("state")?"flopay-billing-state-error":void 0,"data-testid":"flopay-state",style:j()})})]}),Rt("city")&&(0,l.jsx)("div",{id:"flopay-billing-city-error",role:"alert","data-testid":"flopay-city-error",style:lo,children:"City is required"}),Rt("state")&&(0,l.jsxs)("div",{id:"flopay-billing-state-error",role:"alert","data-testid":"flopay-state-error",style:lo,children:[(0,u.getStateLabel)(s)," is required"]}),((0,u.isAVSFieldVisible)(se.country,s)||(0,u.isAVSFieldVisible)(se.postal_code,s))&&(0,l.jsxs)("div",{style:{display:"flex",flexDirection:ve==="column"?"column":"row",gap:ve==="column"?"0.5rem":"0",marginTop:"0.5rem"},children:[(0,u.isAVSFieldVisible)(se.country,s)&&(0,l.jsx)("div",{style:{flex:ve==="row"?1:void 0,backgroundColor:Lr,borderTop:`1px solid ${so}`,borderRight:`1px solid ${so}`,borderBottom:`1px solid ${so}`,borderLeft:`1px solid ${so}`,padding:"10px",...ve==="row"&&(0,u.isAVSFieldVisible)(se.postal_code,s)?{borderRadius:"0",borderTopLeftRadius:_t,borderBottomLeftRadius:_t,borderRight:"none"}:{borderRadius:_t}},children:(0,l.jsx)("select",{id:"flopay-billing-country",name:"billing-country",value:gt,onChange:Y=>{Nt.current.country=!0,Kt.current=Y.target.value,Ut(Y.target.value),rt?.(Y.target.value),en.current="",Dn("")},disabled:Ze,autoComplete:"billing country","data-testid":"flopay-country",style:{...j(),cursor:"pointer"},children:u.COUNTRY_OPTIONS.map(Y=>(0,l.jsxs)("option",{value:Y.code,children:[Y.flag," ",Y.name]},Y.code))})}),(0,u.isAVSFieldVisible)(se.postal_code,s)&&(0,l.jsx)("div",{style:{flex:ve==="row"?1:void 0,backgroundColor:Lr,border:`1px solid ${zs}`,padding:"10px",...ve==="row"&&(0,u.isAVSFieldVisible)(se.country,s)?{borderRadius:"0",borderTopRightRadius:_t,borderBottomRightRadius:_t}:{borderRadius:_t}},children:(0,l.jsx)("input",{className:"flopay-shared-input",id:"flopay-billing-postal-code",name:"billing-postal-code",placeholder:(0,u.getPostalCodeLabel)(gt),autoComplete:"billing postal-code",value:An,onChange:Y=>{st("zip"),Nt.current.zip=!0,It.current=Y.target.value,Bn(Y.target.value),ct?.(Y.target.value)},onPointerDown:()=>st("zip"),onKeyDown:()=>st("zip"),onBlur:()=>{cn("zip")&&Nn(!0)},disabled:Ze,required:tn.required,"aria-invalid":Oo||void 0,"aria-describedby":Oo?"flopay-billing-postal-code-error":void 0,"data-testid":"flopay-zip",style:j()})})]}),Oo&&(0,l.jsx)("div",{id:"flopay-billing-postal-code-error",role:"alert","data-testid":"flopay-zip-error",style:lo,children:tn.empty?`${(0,u.getPostalCodeLabel)(s)} is required`:xl(s)})]})})()}),Ye&&Vs,g&&(0,l.jsx)(Yr,{margin:"0.75rem 0",styleOverride:b.errorBanner,children:g})]}),zo={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"},xi=s=>Ct?!he||!Qn?(0,l.jsx)("pre",{"data-testid":s,style:zo,children:"FloPay/DirectPayPal-debug - not enabled"}):(0,l.jsx)("pre",{"data-testid":s,style:zo,children:["FloPay/DirectPayPal-debug (parent gate)",` showPayPal=${he}`,` directPaypalConfigured=${Qn}`,` inAppBrowserDetected=${String(Do)}`,` shouldRenderDirectPayPal=${no}`,` shouldRenderStripePayPal=${ro}`,` hasPaypalStripeInstance=${!!Fr}`].join(`
|
|
39
39
|
`)}):null,Ti=s=>Ct?!U||!hn?(0,l.jsx)("pre",{"data-testid":s,style:zo,children:"FloPay/Stripe-debug - not enabled"}):(0,l.jsx)("pre",{"data-testid":s,style:zo,children:["FloPay/Stripe-debug (parent gate)",` showStripe=${U}`,` currency=${Be}`,` amountInCents=${Qr}`,` enabledPaymentMethods: ${JSON.stringify(w??[])}`,` enabledPaymentMethodsProvided=${eo}`,` hasEnabledMethods=${Mo}`,` expressMethods: ${JSON.stringify(Ao)}`,` walletExpressMethods: ${JSON.stringify(Bo)}`,` paymentElementMethods: ${JSON.stringify(to)}`,` paymentElementMethodsForCurrency: ${JSON.stringify(Fo)}`,` hasStripeInstance=${!!hn}`,` shouldRenderWallets=${oo}`,` shouldRenderPaymentElement=${ao}`].join(`
|
|
40
|
-
`)}):null,Mi=xe==="apm-expanding"||xe==="apm-form"||xe==="apm-collapsing",Uo=xe==="apm-expanding"?`flopay-card-enter ${Tr}ms cubic-bezier(0, 0, 0.2, 1) both`:xe==="apm-collapsing"?`flopay-card-exit ${Tr}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0,qo=Bt?{...ha,paymentMethodTypes:[Bt]}:null;if(H==="buttons"){let s=xe==="buttons"||xe==="expanding"||xe==="apm-expanding",x=xe==="expanding"||xe==="card"||xe==="collapsing",j=ze===void 0?{boxSizing:"border-box",height:ra,padding:"0 1rem"}:{padding:"0.9rem 1rem"},Ne=xe==="expanding"||xe==="apm-expanding"?`flopay-buttons-exit ${Tr}ms cubic-bezier(0.4, 0, 0.2, 1) both`:xe==="collapsing"||xe==="apm-collapsing"?`flopay-buttons-enter ${Tr}ms cubic-bezier(0, 0, 0.2, 1) both`:void 0,Y=xe==="expanding"?`flopay-card-enter ${Tr}ms cubic-bezier(0, 0, 0.2, 1) both`:xe==="collapsing"?`flopay-card-exit ${Tr}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0;return(0,l.jsxs)("form",{onSubmit:Pa,className:B,noValidate:!0,style:{position:"relative"},children:[(0,l.jsx)(Oa,{}),Te&&(0,l.jsx)(Tn,{status:Te,errorMessage:g,authorized:Ln}),(0,l.jsxs)("div",{style:{display:"grid"},children:[(0,l.jsxs)("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!s&&!Ne?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!s&&!Ne?Rl:{},...Ne?{animation:Ne,pointerEvents:"none"}:{}},children:[xi("flopay-direct-paypal-gate-debug"),Ti("flopay-stripe-gate-debug"),no&&A&&(0,l.jsxs)(l.Fragment,{children:[Z&&(0,l.jsx)("div",{"data-testid":"flopay-paypal-direct-retry-notice",style:{padding:"8px 10px",background:"#fef3c7",border:"1px solid #fcd34d",borderRadius:6,color:"#78350f",fontSize:13,lineHeight:1.4},children:"Please confirm your PayPal payment to complete checkout."}),(0,l.jsx)(bo,{sessionId:e,nonce:t,billingApiUrl:de,email:D.email,billingName:me||void 0,onBuyerIdentityReady:tt,clientId:A.clientId,environment:A.environment,currency:Be.toUpperCase(),isSubscription:oe,providerObjectType:C,onTokenizedBody:In,onComplete:i,onErrorChange:he,onDecline:c,onTechnicalFailure:Dr,onButtonClick:re,runBeforeButtonClick:Vn,isProcessing:Ze,onLoadStateChange:ba,onInitializationStateChange:va,session:Et,existingOrderId:Z?.orderId,debug:Ct},Z?.orderId??"fresh")]}),ro&&(0,l.jsx)(Tt.Elements,{stripe:Fr,options:ni,children:(0,l.jsx)(ls,{sessionId:e,nonce:t,email:D.email,billingName:me||void 0,onBuyerIdentityReady:tt,billingApiUrl:de,onTokenizedBody:In,onErrorChange:he,isProcessing:Ze,onButtonClick:re,onDecline:c,onTechnicalFailure:Dr,runBeforeButtonClick:Vn,onLoadStateChange:li,placeholderBorderRadius:kr})}),oo?(0,l.jsx)(Tt.Elements,{stripe:hn,options:ti,children:(0,l.jsx)(cs,{sessionId:e,nonce:t,email:D.email,billingName:me||void 0,onBuyerIdentityReady:tt,billingApiUrl:de,intentKind:V>0?"payment":"setup",expressMethods:Bo,onTokenizedBody:In,onErrorChange:he,onButtonClick:re,onDecline:c,onTechnicalFailure:Dr,runBeforeButtonClick:Vn,onLoadStateChange:di,placeholderBorderRadius:kr})}):fi?(0,l.jsx)("div",{style:{height:ra,borderRadius:kr,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,ao&&(0,l.jsx)(ds,{sessionId:e,nonce:t,email:D.email,billingName:[D.firstName,D.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:tt,billingApiUrl:de,paymentElementMethods:Fo,stripeInstance:hn,paymentElementBaseOptions:ha,onTokenizedBody:In,onErrorChange:he,onButtonClick:re,onDecline:c,runBeforeButtonClick:Vn,onLoadStateChange:pi,isProcessing:Ze,submitButtonColor:Ir,submitButtonBorderRadius:_t,submitButtonStyle:b.submitButton,onExpandApm:ae,expandedApmMethod:Bt,themeId:ge,buttonAppearance:{backgroundColor:b.cardButton?.backgroundColor,borderColor:b.cardInputBorder,textColor:b.cardButton?.color,borderRadius:kr}}),Ye&&(0,l.jsx)("button",{type:"button",onClick:async()=>{Ze||!(await Vn("card")).proceed||(re?.("card"),N())},disabled:Ze,style:{width:"100%",...j,...b.cardButton,...$a({themeBundle:p,resolvedPrimaryColor:Ir,resolvedBorderRadius:_t,submitButtonStyle:b.submitButton,explicitPrimaryColor:un?.colorPrimary}),fontSize:b.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:Ze?"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:Ze?.6:1},onMouseEnter:De=>{!Ze&&(p||un?.colorPrimary)&&(De.currentTarget.style.backgroundColor=$s)},onMouseLeave:De=>{(p||un?.colorPrimary)&&(De.currentTarget.style.backgroundColor=Ir)},onMouseDown:De=>{De.currentTarget.style.transform="scale(0.985)"},onMouseUp:De=>{De.currentTarget.style.transform="scale(1)"},children:(0,l.jsx)(zr,{content:ze})}),g&&xe==="buttons"&&(0,l.jsx)(Yr,{margin:"0.25rem 0",styleOverride:b.errorBanner,children:g})]}),Ye&&x&&(0,l.jsx)("div",{style:{gridArea:"1 / 1",...Y?{animation:Y}:{},...xe==="collapsing"?{pointerEvents:"none"}:{}},children:_i}),U&&Mi&&Bt&&qo&&hn&&(0,l.jsx)("div",{style:{gridArea:"1 / 1",...Uo?{animation:Uo}:{},...xe==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,l.jsxs)("div",{style:{backgroundColor:Sa,borderRadius:Ea,...co,padding:Ra},children:[(0,l.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,l.jsxs)("button",{type:"button","data-testid":"flopay-apm-back-button",onClick:ie,style:{display:"inline-flex",alignItems:"center",gap:wa?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:b.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...b.backButton},"aria-label":"Back to payment methods",children:[(0,l.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...b.backButtonIcon},children:(0,l.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,l.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,l.jsx)(Ur,{content:Ie})]}),(0,l.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:b.titleFontSize??"1.05rem",color:ka,paddingRight:80,...b.title},children:`Pay with ${(0,u.getStripeMethodDisplayName)(Bt)}`})]}),(0,l.jsx)(Tt.Elements,{stripe:hn,options:qo,children:(0,l.jsx)(Ua,{method:Bt,sessionId:e,nonce:t,email:D.email,billingName:[D.firstName,D.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:tt,billingApiUrl:de,onTokenizedBody:In,onErrorChange:he,onDecline:c,onCancel:ie,runBeforeButtonClick:Vn,onButtonClick:re,isProcessing:Ze,submitButtonColor:Ir,submitButtonBorderRadius:_t,submitButtonStyle:b.submitButton,errorText:g})},Bt)]})})]})]})}return Mi&&Bt&&qo&&hn&&U?(0,l.jsxs)("form",{onSubmit:Pa,className:B,noValidate:!0,style:{position:"relative"},children:[(0,l.jsx)(Oa,{}),Te&&(0,l.jsx)(Tn,{status:Te,errorMessage:g,authorized:Ln}),(0,l.jsx)("div",{style:{...Uo?{animation:Uo}:{},...xe==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,l.jsxs)("div",{style:{backgroundColor:Sa,borderRadius:Ea,...co,padding:Ra},children:[(0,l.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,l.jsxs)("button",{type:"button","data-testid":"flopay-apm-back-button-default",onClick:ie,style:{display:"inline-flex",alignItems:"center",gap:wa?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:b.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...b.backButton},"aria-label":"Back to payment methods",children:[(0,l.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...b.backButtonIcon},children:(0,l.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,l.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,l.jsx)(Ur,{content:Ie})]}),(0,l.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:b.titleFontSize??"1.05rem",color:ka,paddingRight:80,...b.title},children:`Pay with ${(0,u.getStripeMethodDisplayName)(Bt)}`})]}),(0,l.jsx)(Tt.Elements,{stripe:hn,options:qo,children:(0,l.jsx)(Ua,{method:Bt,sessionId:e,nonce:t,email:D.email,billingName:[D.firstName,D.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:tt,billingApiUrl:de,onTokenizedBody:In,onErrorChange:he,onDecline:c,onCancel:ie,runBeforeButtonClick:Vn,onButtonClick:re,isProcessing:Ze,submitButtonColor:Ir,submitButtonBorderRadius:_t,submitButtonStyle:b.submitButton,errorText:g})},Bt)]})})]}):(0,l.jsxs)("form",{onSubmit:Pa,className:B,noValidate:!0,style:{position:"relative"},children:[(0,l.jsx)(Oa,{}),Te&&(0,l.jsx)(Tn,{status:Te,errorMessage:g,authorized:Ln}),(0,l.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[xi("flopay-direct-paypal-gate-debug-default"),Ti("flopay-stripe-gate-debug-default"),no&&A&&(0,l.jsxs)(l.Fragment,{children:[Z&&(0,l.jsx)("div",{"data-testid":"flopay-paypal-direct-retry-notice-default",style:{padding:"8px 10px",background:"#fef3c7",border:"1px solid #fcd34d",borderRadius:6,color:"#78350f",fontSize:13,lineHeight:1.4},children:"Please confirm your PayPal payment to complete checkout."}),(0,l.jsx)(bo,{sessionId:e,nonce:t,billingApiUrl:de,email:D.email,billingName:me||void 0,onBuyerIdentityReady:tt,clientId:A.clientId,environment:A.environment,currency:Be.toUpperCase(),isSubscription:oe,providerObjectType:C,onTokenizedBody:In,onComplete:i,onErrorChange:he,onDecline:c,onTechnicalFailure:Dr,onButtonClick:re,runBeforeButtonClick:Vn,isProcessing:Ze,onLoadStateChange:ba,onInitializationStateChange:va,session:Et,existingOrderId:Z?.orderId,debug:Ct},Z?.orderId??"fresh")]}),ro&&(0,l.jsx)(Tt.Elements,{stripe:Fr,options:ni,children:(0,l.jsx)(ls,{sessionId:e,nonce:t,email:D.email,billingName:me||void 0,onBuyerIdentityReady:tt,billingApiUrl:de,onTokenizedBody:In,onErrorChange:he,isProcessing:Ze,onButtonClick:re,onDecline:c,onTechnicalFailure:Dr,runBeforeButtonClick:Vn,onLoadStateChange:li,placeholderBorderRadius:kr})}),oo&&(0,l.jsx)(Tt.Elements,{stripe:hn,options:ti,children:(0,l.jsx)(cs,{sessionId:e,nonce:t,email:D.email,billingName:me||void 0,onBuyerIdentityReady:tt,billingApiUrl:de,intentKind:V>0?"payment":"setup",expressMethods:Bo,onTokenizedBody:In,onErrorChange:he,onButtonClick:re,onDecline:c,onTechnicalFailure:Dr,runBeforeButtonClick:Vn,onLoadStateChange:di,placeholderBorderRadius:kr})}),ao&&(0,l.jsx)(ds,{sessionId:e,nonce:t,email:D.email,billingName:[D.firstName,D.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:de,paymentElementMethods:Fo,stripeInstance:hn,paymentElementBaseOptions:ha,onTokenizedBody:In,onErrorChange:he,onButtonClick:re,onDecline:c,runBeforeButtonClick:Vn,onLoadStateChange:pi,isProcessing:Ze,submitButtonColor:Ir,submitButtonBorderRadius:_t,submitButtonStyle:b.submitButton,themeId:ge,onExpandApm:ae,expandedApmMethod:Bt,buttonAppearance:{backgroundColor:b.cardButton?.backgroundColor,borderColor:b.cardInputBorder,textColor:b.cardButton?.color,borderRadius:kr}})]}),Ye&&(Ds||Fs||Ls)&&(0,l.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem",margin:"0.5rem 0 0.75rem",color:"#999",fontSize:"0.85rem"},children:[(0,l.jsx)("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}}),(0,l.jsx)("span",{children:"or pay with card"}),(0,l.jsx)("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}})]}),Ye&&_i]})}var I=require("react/jsx-runtime"),Ar=44,Za="flopay_checkout_saved_payment_resume",ca=new Map,sa=new Map;function hs(e,t){t.settled&&t.consumers===0&&ca.get(e)===t&&ca.delete(e)}function Dl(e,t,n){let r=sa.get(e);if(r&&(!r.sdkGeneratedIdempotencyKey||!t||r.sdkGeneratedIdempotencyKey===t))return r.attempt;let o=n(),i={attempt:o,sdkGeneratedIdempotencyKey:t};sa.set(e,i);let d=()=>{sa.get(e)===i&&sa.delete(e)};return o.then(d,d),o}function Io(e){return new Promise(t=>setTimeout(t,e))}function la(e,t,n){let r=Wo({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:be.SDK_VERSION,enabled:t!==!1});return r.beginCheckout(n),r}function Ro(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function ja(e,t,n,r,o){let i=la(e,t,n);i.error({errorCode:r,stage:o,paymentMethodCategory:"unknown",...o==="session_read"?{requestCategory:"session_read"}:{}}),Ro(i)}function Ll(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 Ja(e){let t=e?.data.paypal?.publishableKey;if(t)return{clientId:t,environment:e?.data.paypal?.environment,providerObjectType:e?.data.paypal?.providerObjectType}}function Va(e){return!e||e.data.stripe?.publishableKey?!1:!!Ja(e)?.clientId}function ur(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function Nl(){if(!ur())return null;try{let e=window.sessionStorage.getItem(Za);return e?JSON.parse(e):null}catch{return null}}function bs(e){if(ur())try{window.sessionStorage.setItem(Za,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function Ka(){if(ur())try{window.sessionStorage.removeItem(Za)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}var Qa=":idempotency-key";function Ps(e,t){if(!ur())return null;let n=window.sessionStorage.getItem(e);if(!n)return null;try{let r=JSON.parse(n);return!r||typeof r.sid!="string"||!r.sid||"canonicalIdentity"in r&&r.canonicalIdentity!==t?null:{..."canonicalIdentity"in r?{canonicalIdentity:t}:{},sid:r.sid,nonce:typeof r.nonce=="string"?r.nonce:void 0}}catch{return{sid:n}}}function Ha(e,t,n,r){if(ur())try{window.sessionStorage.setItem(e,JSON.stringify(r?{canonicalIdentity:t,sid:n,nonce:r}:{canonicalIdentity:t,sid:n}))}catch(o){console.warn("[FloPayCheckout] Failed to persist checkout session cache.",o)}}function Xa(e,t){if(ur())try{Ps(e,t)&&window.sessionStorage.removeItem(e)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout session cache.",n)}}function Cs(e,t){if(!ur())return null;try{let n=window.sessionStorage.getItem(e+Qa);if(!n)return null;try{let r=JSON.parse(n);return typeof r=="string"?r?{idempotencyKey:r}:null:!r||typeof r.idempotencyKey!="string"||!r.idempotencyKey||"canonicalIdentity"in r&&r.canonicalIdentity!==t?null:{..."canonicalIdentity"in r?{canonicalIdentity:t}:{},idempotencyKey:r.idempotencyKey}}catch{return{idempotencyKey:n}}}catch{return null}}function Ya(e,t,n){if(ur())try{window.sessionStorage.setItem(e+Qa,JSON.stringify({canonicalIdentity:t,idempotencyKey:n}))}catch(r){console.warn("[FloPayCheckout] Failed to persist checkout idempotency key.",r)}}function Wa(e,t){if(Xa(e,t),!!ur())try{Cs(e,t)&&window.sessionStorage.removeItem(e+Qa)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout idempotency key.",n)}}function Ol(){if(typeof window>"u")return;let e=new URL(window.location.href),t=["payment_intent","payment_intent_client_secret","redirect_status"],n=!1;for(let r of t)e.searchParams.has(r)&&(e.searchParams.delete(r),n=!0);n&&window.history.replaceState(window.history.state,"",e.toString())}function vs(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 zl(e){return e?!!(e.account&&Object.keys(e.account).length>0||e.couponCodes!==void 0||e.checkoutMetadata!==void 0||e.tagsData!==void 0||e.utmMetadata!==void 0):!1}function Ga(e,t){return`${e}:${t.totalAmount??""}:${t.overrideAmount??""}:${t.quantity??1}:${t.currency??""}`}function Ul(e){if(e==null)return e;let t=JSON.stringify(Object.entries(e).sort(([d],[c])=>d<c?-1:d>c?1:0)),n=1779033703,r=3144134277,o=1013904242,i=2773480762;for(let d=0;d<t.length;d++){let c=t.charCodeAt(d);n=r^Math.imul(n^c,597399067),r=o^Math.imul(r^c,2869860233),o=i^Math.imul(o^c,951274213),i=n^Math.imul(i^c,2716044179)}return n=Math.imul(o^n>>>18,597399067),r=Math.imul(i^r>>>22,2869860233),o=Math.imul(n^o>>>17,951274213),i=Math.imul(r^i>>>19,2716044179),n^=r^o^i,r^=n,o^=n,i^=n,[n,r,o,i].map(d=>(d>>>0).toString(16).padStart(8,"0")).join("")}function Eo(e,t=!1){let n=e?.account?.email?.trim().toLowerCase()??"",r={c:e?.clientId,cur:e?.currency??"",captureMethod:e?.captureMethod??"",a:{e:n,u:n?"":e?.account?.userId??"",country:e?.account?.country??""},successUrl:e?.successUrl,cancelUrl:e?.cancelUrl,p:e?.products?.map(o=>Ga(`${o.type??""}:${o.code??o.providerItemId??o.providerPlanId??""}`,o)).sort(),i:e?.items?.map(o=>Ga(o.code??o.providerItemId??"",o)).sort(),s:e?.subscriptions?.map(o=>Ga(o.code??o.providerPlanId??"",o)).sort(),couponCodes:e?.couponCodes?[...e.couponCodes].sort():void 0,checkoutMetadata:Ul(e?.checkoutMetadata),...t?{tagsData:e?.tagsData,utmMetadata:e?.utmMetadata,tokenizedData:e?.tokenizedData,checkoutMode:e?.checkoutMode??"full"}:{}};return JSON.stringify(r)}function ql(e,t=!1){let n=Eo(e,t),r=0;for(let o=0;o<n.length;o++)r=(r<<5)-r+n.charCodeAt(o)|0;return`flopay_session_${Math.abs(r).toString(36)}`}function $l(e,t){if(!e?.customer||!e.products||t.checkoutMetadata!==void 0)return!1;let n=t.account.email?.trim().toLowerCase()??"",r=e.customer.email?.trim().toLowerCase()??"";if((n?r!==n:e.customer.id!==t.account.userId)||(t.account.country??"").trim().toUpperCase()!==(e.customer.country??"").trim().toUpperCase()||e.successUrl!==t.successUrl||e.cancelUrl!==t.cancelUrl||(e.captureMethod??"automatic")!==(t.captureMethod??"automatic"))return!1;let o=(0,be.resolveSessionCurrency)(t.currency,t.items,t.subscriptions,t.products);if(!o||e.currency.toUpperCase()!==o.toUpperCase())return!1;let i=(t.products??(0,be.foldIntoProducts)(t.items,t.subscriptions)).map(y=>({type:y.type,code:y.code??y.providerItemId??y.providerPlanId??"",quantity:y.quantity??1,totalAmount:y.totalAmount,overrideAmount:y.overrideAmount??null,currency:(y.currency??o).toUpperCase()})).sort((y,h)=>`${y.code}:${y.type??""}`.localeCompare(`${h.code}:${h.type??""}`)),d=e.products.map(y=>({type:y.type,code:y.code??"",quantity:y.quantity??1,totalAmount:y.totalAmount,overrideAmount:y.overrideAmount??null,currency:(y.currency??e.currency).toUpperCase()})).sort((y,h)=>`${y.code}:${y.type??""}`.localeCompare(`${h.code}:${h.type??""}`));if(i.length!==d.length)return!1;for(let y=0;y<i.length;y+=1){let h=i[y],v=d[y];if(h.code!==v.code||h.type!==void 0&&h.type!==v.type||h.quantity!==v.quantity||h.totalAmount!==v.totalAmount||h.overrideAmount!==v.overrideAmount||h.currency!==v.currency)return!1}let c=[...t.couponCodes??[]].sort(),P=[...e.coupons??[]].sort();return c.length===P.length&&c.every((y,h)=>y===P[h])}function da({sessionId:e,nonce:t,createSession:n,billingApiUrl:r,telemetry:o,appearance:i,locale:d,loading:c,error:P,onComplete:y,onError:h,onInstrument:v,onDecline:B,onCountryChange:M,onZipChange:m,showPayPal:S=!0,showStripe:fe=!0,enabledPaymentMethods:U,showApplePay:w=!0,showGooglePay:ue=!0,debug:q=!1,layout:ce,theme:H,buttonsTheme:ge,buttonsStyles:$e,cardButtonContent:Se,cardBackButtonContent:Pt,cardTitleContent:ze,showSecurityFooter:Ie,onButtonClick:Re,onBeforeButtonClick:ne,enableAVS:re,cardFieldOrder:L,cardPreFormSlot:Ee,avsLayout:_e,className:J,initialErrorMessage:we=null,children:ve,checkoutMode:T,confirmLabel:O,renderConfirmButton:Ae,onSessionCompleted:ye}){let Q=(0,be.resolveBillingApiUrl)(r),Le=(0,k.useMemo)(()=>(0,be.resolveTheme)(H),[H]),rt=i??Le?.appearance,ct=n?"embedded_checkout":"standard_checkout",Oe=ve?"custom_layout":ce==="buttons"?"buttons_layout":"default_layout",[ee,W]=(0,k.useState)(null),[V,Be]=(0,k.useState)(null),Je=(0,k.useRef)(null),[A,oe]=(0,k.useState)(null),F=(0,k.useRef)(null),[R,at]=(0,k.useState)(null),Ct=(0,k.useMemo)(()=>n?Eo(n):"",[n]),ke=n?`create:${Ct}`:`session:${e??""}`,pt=R?.gateways?.stripe?"stripe":R?.gateways?.paypal?"paypal":void 0,Fe=(0,k.useRef)(new Set),mt=(0,k.useRef)(ke),Et=(0,k.useRef)(ke);ho(()=>{Et.current=ke,mt.current!==ke&&(mt.current=ke,Fe.current.clear())},[ke]);let C=(0,k.useCallback)(N=>{if(Et.current===ke){if(Ma.has(N.name)){if(Fe.current.has(N.name))return;Fe.current.add(N.name)}et(()=>v?.(N))}},[ke,v]),te=Hr(C,ke),Xe=(0,k.useRef)(!1),He=(0,k.useCallback)(N=>{if(Xe.current)return;let $=N.gateway||!pt?N:{...N,gateway:pt};C($)},[C,pt]);(0,k.useEffect)(()=>{te({class:"lifecycle",name:"checkout.mount"})},[te]);let[zt,Lt]=(0,k.useState)(e??""),G=e??zt,dt=n?"":G,[Qt,gt]=(0,k.useState)(!0),[Ut,An]=(0,k.useState)(null),[Bn,Fn]=(0,k.useState)("full"),[Jt,Wn]=(0,k.useState)(!1),[mn,qt]=(0,k.useState)(we),[rr,wt]=(0,k.useState)(null),[Dn,it]=(0,k.useState)(null),[pr,kt]=(0,k.useState)(!1),[Pn,It]=(0,k.useState)(void 0),[Kt,yn]=(0,k.useState)(""),[on,Cn]=(0,k.useState)(!1),[en,Sn]=(0,k.useState)(!1),[Nt,se]=(0,k.useState)(!1),an=(0,k.useRef)(0),Ln=(0,k.useRef)(void 0),[Gn,Cr]=(0,k.useState)("loading"),[Sr,mr]=(0,k.useState)(0),Mt=(0,k.useRef)(!1),Ye=(0,k.useRef)(!1),yr=(0,k.useRef)(!1),E=(0,k.useRef)(null),ot=(0,k.useMemo)(()=>({checkoutMode:T??Bn,layout:ve?"unknown":ce==="buttons"?"buttons":"embedded"}),[T,ve,Bn,ce]),$t=(0,k.useRef)(y);$t.current=y;let fn=(0,k.useRef)(h);fn.current=h;let Pe=(0,k.useRef)(B);Pe.current=B,(0,k.useEffect)(()=>{Vt(V)?.setCheckoutContext(ot),A&&A!==V&&Vt(A)?.setCheckoutContext(ot)},[V,A,ot]);let tn=(0,k.useRef)(ye);tn.current=ye;let wr=(0,k.useCallback)(N=>{Cr(N),!(N!=="exhausted"||yr.current)&&(yr.current=!0,fn.current?.(new be.FloPayError("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),Br=(0,k.useCallback)(()=>{Cr("retrying"),mr(N=>N+1)},[]);(0,k.useEffect)(()=>{Cr("loading"),mr(0),yr.current=!1},[G]),(0,k.useEffect)(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:be.SDK_VERSION,checkout_type:ct,checkout_layout:Oe,billing_api_url:Q})},[Oe,ct,Q]);let sn=(0,k.useMemo)(()=>n?Eo(n,!0):"",[n]),fr=(0,k.useMemo)(()=>Kt===sn?Pn:void 0,[Pn,Kt,sn]),Jn=(0,k.useMemo)(()=>n?_a(n,fr):void 0,[n,fr]),Nn=T??Jn?.checkoutMode??"full",At=(0,k.useMemo)(()=>Jn?{...Jn,checkoutMode:Nn}:void 0,[Jn,Nn]);(0,k.useEffect)(()=>{It(void 0),yn(sn),Ln.current=void 0,se(!1)},[sn]),(0,k.useEffect)(()=>{qt(we)},[we]);let On=(0,k.useCallback)((N,$,ae)=>{et(()=>{Pe.current?.(jt(N,$,ae))})},[]),Xn=(0,k.useCallback)(async(N,$)=>{qt(null),it(null),kt(!1),wt("processing");let ae=$?.sessionId??N.id,ie=N.gateways?.stripe?"stripe":N.gateways?.paypal?"paypal":void 0,Te=Je.current??F.current,z=Vt(Te),X=Te?null:la(Q,o,ot),f={log:g=>{z?z.log(g):X?.log(g)},error:g=>{z?z.error(g):X?.error(g)},terminal:g=>{z?z.terminal(g):X?.terminal(g)},performance:g=>{z?z.performance(g):X?.performance(g)},now:()=>z?.now()??X?.now()??0,elapsed:g=>z?.elapsed(g)??Math.max(0,(X?.now()??g)-g)},K=f.now(),Z=!!($?.initialAutoProcessingError||$?.initialAutoProcessingPending),ut=!1,yt,de=()=>{ut||(ut=!0,Z=!0,yt=f.now(),f.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),f.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},Me=!1,Ht=()=>{Me||(Me=!0,f.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),f.performance({stage:"processing",durationMs:f.elapsed(K),durationMode:"machine",paymentMethodCategory:"saved"}),yt!==void 0&&f.performance({stage:"recovery",durationMs:f.elapsed(yt),durationMode:"machine",paymentMethodCategory:"saved"}))};f.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),Xe.current=!0;try{f.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"})}finally{Xe.current=!1}te({class:"lifecycle",name:"payment.processing.started",provider:ie}),Z&&de();let tt;try{let g=Xi($?.initialAutoProcessingError),p;if(g)de(),g.type==="paypal_redirect_required"&&E.current?.publishableKey&&bs({sessionId:ae,publishableKey:E.current.publishableKey,paypalPublishableKey:E.current.paypalPublishableKey}),p=await Qo(g,{flopay:Je.current,paypalFlopay:F.current,attempt3DS:$?.attempt3DS,billingApiUrl:Q,sessionId:ae,session:N,telemetry:!1}),g.type==="paypal_redirect_required"&&Ka();else if($?.initialAutoProcessingPending){let pe=(await new Mr.PaymentAPI(Q,{telemetry:!1}).waitForCheckoutSessionCompletion($.initialAutoProcessingPending.sessionId,{initialDelayMs:$.initialAutoProcessingPending.retryAfterMs})).data.session;if(!$r(pe))throw Vo(pe);p=Er(pe,ae)}else{if($?.initialAutoProcessingError)throw Pr($.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:$.initialAutoProcessingError.checkoutMethod});if($?.fromCreateSession)return $?.fallbackToFull&&(Fn("full"),vs("full")),!1;{let b=await Jr({billingApiUrl:Q,sessionId:ae,session:N,telemetry:!1});b.type==="success"?p=b.result:(de(),b.type==="paypal_redirect_required"&&E.current?.publishableKey&&bs({sessionId:ae,publishableKey:E.current.publishableKey,paypalPublishableKey:E.current.paypalPublishableKey}),p=await Qo(b,{flopay:Je.current,paypalFlopay:F.current,attempt3DS:$?.attempt3DS,billingApiUrl:Q,sessionId:ae,session:N,telemetry:!1}),b.type==="paypal_redirect_required"&&Ka())}}ae&&Wr(ae),Ht(),Z&&(f.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),f.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),f.terminal({outcome:p.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),kt(p.status==="authorized"),wt("success"),await Io(1200),tt=()=>$t.current?.(p)}catch(g){let p=wo(g),b=p.checkoutMethod??So;qt(p.message),it(p.message),kt(!1),$?.fallbackToFull&&(f.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),Fn("full"),vs("full")),Ht();let Ce=p.statusCode!==void 0?(0,be.telemetryStatusClass)(p.statusCode,"unknown"):void 0,pe=Ce==="4xx"?{requestCategory:"process_payment",statusClass:Ce}:{},We=Ce===void 0||Ce==="4xx";if(We&&(p.telemetryOutcome==="payment_declined"||!!(p.declineCode||p.code?.toLowerCase().includes("declin"))))f.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...pe});else if(We&&(p.telemetryOutcome==="validation_rejected"||p.type==="validation_error"))f.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...pe});else{let D=(0,be.classifyTelemetryFailure)(g,Z?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown"),me=p.telemetryRequestCategory??"process_payment";Xe.current=!0;try{f.error({...D,...p.telemetryFailureCategory?{failureCategory:p.telemetryFailureCategory}:{},stage:Z?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:me})}finally{Xe.current=!1}te({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:me,provider:ie})}return et(()=>fn.current?.(p)),On(b,p,{code:p.code,declineCode:p.declineCode}),wt("error"),await Promise.allSettled([Io(1500),$?.ensureProvidersReady?$.ensureProvidersReady():Promise.resolve()]),Z&&(f.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),f.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{Ht(),X&&Ro(X),wt(null),it(null)}return et(tt),!0},[On,te,Q,o,ot]);(0,k.useEffect)(()=>{if(typeof window>"u"||Ye.current)return;let N=new URLSearchParams(window.location.search),$=N.get("payment_intent_client_secret");if(!$)return;let ae=Nl();ae&&(Ye.current=!0,(async()=>{let ie,Te=0;qt(null),it(null),wt("processing"),Wn(!0);try{if(N.get("redirect_status")==="failed")throw Object.assign(new be.FloPayError("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:z,paypalFlopay:X}=await ta({publishableKey:ae.publishableKey,paypalPublishableKey:ae.paypalPublishableKey,billingApiUrl:Q,locale:d,telemetry:o});ie=Vt(X??z),Te=ie?.now()??0,ie?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),ie?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let f=(X??z)?.getRawProvider();if(!f)throw Object.assign(new be.FloPayError("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:K,error:Z}=await f.retrievePaymentIntent($);if(Z)throw Object.assign(new be.FloPayError(Z.message??"Failed to retrieve PayPal payment status.","api_error",{code:Z.code}),{checkoutMethod:"paypal"});let ut=Ni(K?.status);if(!K||ut==="failed")throw Object.assign(new be.FloPayError("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let yt=typeof K.payment_method=="string"?K.payment_method:K.payment_method?.id,de=ut;if(ae.sessionId){let tt=(await new Mr.PaymentAPI(Q,{telemetry:!1}).getUnifiedCheckoutSession(ae.sessionId)).data.session;if(tt&&tt.status!=="complete"){let g=await Jr({billingApiUrl:Q,sessionId:ae.sessionId,session:tt,telemetry:!1,tokenizedData:{id:yt??K.id,type:"card",threeDSecureActionResultTokenId:K.id,isPaypal:!0}});if(g.type!=="success")throw Object.assign(new be.FloPayError("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});de=g.result.status}}ae.sessionId&&Wr(ae.sessionId),ie?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),ie?.performance({stage:"redirect_resume",durationMs:ie.elapsed(Te),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),ie?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),wt("success"),await Io(1200),et(()=>$t.current?.({status:de,paymentIntentId:K.id,paymentMethodId:yt,checkoutMethod:"paypal"}))}catch(z){let X=wo(z),f=X.checkoutMethod??"paypal",K=!!(X.declineCode||X.code?.toLowerCase().includes("declin"));if(ie)ie.performance({stage:"redirect_resume",durationMs:ie.elapsed(Te),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),K?ie.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):ie.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(K){let Z=la(Q,o,ot);Z.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),Ro(Z)}else ja(Q,o,ot,"REDIRECT_RESUME_FAILED","redirect_resume");qt(X.message),it(X.message),et(()=>fn.current?.(X)),On(f,X,{code:X.code,declineCode:X.declineCode}),wt("error"),await Io(1500)}finally{Ka(),Ol(),wt(null),it(null),Wn(!1)}})())},[On,d,Q,o,ot]);let ln=(0,k.useRef)(null),Xt=(0,k.useMemo)(()=>At?Eo(At):"",[At]),zn=(0,k.useRef)(At);zn.current=At,(0,k.useEffect)(()=>{Lt(e??"")},[e]),(0,k.useEffect)(()=>{Mt.current=!1,qt(we),it(null),kt(!1),wt(null)},[Xt,we,e]);async function Un(N,$,ae){let ie=la(Q,o,ot),Te=new Mr.PaymentAPI(Q,{telemetry:!1}),z=!1;try{let X=N.idempotencyKey!==void 0?(0,be.resolveIdempotencyKey)(N.idempotencyKey):void 0,f=Ps($,ae),K=Cs($,ae);f?.canonicalIdentity===ae&&K&&K.canonicalIdentity===void 0&&(Ya($,ae,K.idempotencyKey),K={...K,canonicalIdentity:ae});let Z=X??(K?.canonicalIdentity===ae?K.idempotencyKey:void 0),ut,yt=!1;ie.log({name:f?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let de=f?.sid??null,Me=null,Ht,tt,g=!1;if(de)try{Me=await Te.getUnifiedCheckoutSession(de,f?.nonce),f&&f.canonicalIdentity===void 0&&($l(Me.data.session,N)?(Ha($,ae,de,f.nonce??Me.data.session?.clientSecret),K&&K.canonicalIdentity===void 0&&(Ya($,ae,K.idempotencyKey),Z??(Z=K.idempotencyKey))):(Wa($,ae),K=null,Z=X,de=null,Me=null));let b=Me?.data.session?.status,Ce=Me?.data.session,pe=Ce?.clientSecret||f?.nonce;if(de&&Ce?.buyerIdentified===!1&&pe&&(tt=qr(Te,de,pe,N.account)),de&&Me&&b==="complete"){if(Ba(de))return{sid:de,result:Me};Wa($,ae),de=null,Me=null,yt=!0}}catch{ie.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),f?.canonicalIdentity===void 0?(Wa($,ae),Z=X):Xa($,ae),de=null}if(!de){!X&&(yt||!Z)&&(Z=(0,be.resolveIdempotencyKey)(),ut=Z),Z&&Ya($,ae,Z);let b=ie.now(),Ce=0;ie.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let pe={...N,idempotencyKey:Z,avsCheck:!!re,avsConfig:typeof re=="object"?re:void 0,checkoutType:"embedded_checkout",checkoutLayout:ve?"custom_layout":ce==="buttons"?"buttons_layout":"default_layout"};Object.defineProperty(pe,Mr.SESSION_CREATE_TELEMETRY,{configurable:!1,enumerable:!1,value:{onAttempt:le=>{Ce=Math.max(Ce,le)}}});let We=()=>{ie.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:"2xx"}),ie.performance({stage:"session_create",durationMs:ie.now()-b,durationMode:"machine",requestCategory:"session_create",attempt:Ce,statusClass:"2xx"})},Ze=le=>{let D=(0,be.classifyTelemetryFailure)(le,"CHECKOUT_SESSION_CREATE_FAILED","unknown");ie.performance({stage:"session_create",durationMs:ie.now()-b,durationMode:"machine",requestCategory:"session_create",attempt:Ce,statusClass:D.statusClass}),le instanceof be.FloPayError&&le.type==="validation_error"?ie.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown"}):D.statusClass==="4xx"?ie.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create",statusClass:"4xx"}):(ie.error({...D,stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create"}),te({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_create"}))};try{if((0,be.isDetachedSessionEligible)(pe)){let le=await Te.createDetachedSession(pe);le.claimed.catch(()=>{}),Me=le.shell,de=le.sessionId,tt=le.claim,Ht=le.claimed.then(D=>{let me=D.data.session?.id??le.sessionId;return me&&Ha($,ae,me,D.data.session?.clientSecret??le.nonce),We(),D},D=>{throw Xa($,ae),Ze(D),D}).finally(()=>Ro(ie)),Ht.catch(()=>{}),z=!0,ie.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),ie.performance({stage:"session_shell",durationMs:ie.now()-b,durationMode:"machine",requestCategory:"session_create",attempt:Ce,statusClass:"2xx",paymentMethodCategory:"card"})}else Me=await Te.createAndFetchSession(pe),We()}catch(le){throw Ze(le),le}de=Me.data.session?.id??de??"",de&&!Ht&&Ha($,ae,de,Me.data.session?.clientSecret)}let p=Me?.data.session;return!tt&&de&&p?.buyerIdentified===!1&&p.clientSecret&&(tt=qr(Te,de,p.clientSecret,N.account)),{sid:de??"",result:Me,sdkGeneratedIdempotencyKey:ut,...Ht?{claimed:Ht}:{},...tt?{claim:tt}:{},...g?{claimRequiresIdentity:!0}:{}}}finally{z||Ro(ie)}}let st=(0,k.useRef)(Un);ho(()=>{st.current=Un},[Un]);let cn=(0,k.useCallback)(async(N,$)=>{let ae=zn.current;if(!ae)throw new be.FloPayError("createSession is required to bootstrap checkout.","validation_error");let ie=_a(ae,N),Te=Eo(ie),z=ql(ie),X=ca.get(Te);if(!X){let Z={canonicalIdentity:Te,promise:st.current(ie,z,Te),consumers:0,settled:!1};X=Z,ca.set(Te,Z);let ut=()=>{Z.settled=!0,hs(Te,Z)};Z.promise.then(ut,ut)}X.consumers+=1;let f=!1,K=()=>{f||(f=!0,X.consumers-=1,hs(Te,X))};$?.(K);try{let Z=await X.promise;ln.current=Te,N&&(yn(sn),It(Ce=>Fi(Ce,N)));let{sid:ut,result:yt,claimed:de,claim:Me,claimRequiresIdentity:Ht}=Z;if(Ln.current=Me,se(Ht===!0),W(yt),yt.data.session&&at(yt.data.session),ut&&Lt(ut),de){an.current+=1;let Ce=an.current;Sn(!0),de.then(pe=>{an.current===Ce&&(W(pe),pe.data.session&&at(pe.data.session),Sn(!1),se(!1))},pe=>{an.current===Ce&&(Sn(!1),se(!1),An(pe instanceof be.FloPayError?pe:new be.FloPayError(pe instanceof Error?pe.message:"Failed to create session","api_error")))})}else an.current+=1,Sn(!1),se(!1);let{publishableKey:tt,paypalPublishableKey:g}=ea(yt),{flopay:p,paypalFlopay:b}=await ta({publishableKey:tt,paypalPublishableKey:g,billingApiUrl:Q,locale:d,telemetry:o});return Je.current=p,Be(p),F.current=b,oe(b),gt(!1),Z}catch(Z){throw ln.current===Te&&(ln.current=null),Z}finally{$||K()}},[sn,d,Q,o]),dn=(0,k.useRef)(Xn);dn.current=Xn;let qn=(0,k.useRef)(cn);qn.current=cn;let wn=(0,k.useCallback)(async N=>{if(!zl(N)||on)return{sessionId:zt,session:R};Cn(!0);try{let $=await cn(N);return{sessionId:$.sid,session:$.result.data.session??null}}finally{Cn(!1)}},[cn,on,zt,R]),xe=(0,k.useCallback)(async N=>{let $=Ln.current;if(!$)return;let ae=an.current,ie=await $(N);an.current===ae&&(W(ie),ie.data.session&&at(ie.data.session))},[]);(0,k.useEffect)(()=>{let N=!1,$;if(An(null),Xt){let Te=zn.current;return Fn(Nn),gt(!1),ln.current===Xt?()=>{N=!0}:(at(Di(Te,T)),(async()=>{let z=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),X=Nn==="auto"&&!Mt.current&&!z;X&&(qt(null),it(null),wt("processing"));try{let f=await qn.current(void 0,yt=>{$=yt}),K=f.result.data.session??null;E.current=ea(f.result);let Z=Va(f.result),ut=Ba(f.sid||K?.id);if(!N&&X&&K&&!Z&&!ut){Mt.current=!0,await Dl(Xt,f.sdkGeneratedIdempotencyKey,()=>dn.current(K,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:f.result.autoProcessingError,initialAutoProcessingPending:f.result.autoProcessingPending,autoProcessingAttempted:f.result.autoProcessingAttempted,sessionId:f.sid||K.id}));return}!N&&X&&((Z||ut)&&(Mt.current=!0),wt(null),it(null))}catch(f){if(N)return;let K=f instanceof be.FloPayError||typeof f=="object"&&f!==null&&"code"in f?f.code:void 0;if(X&&K==="session_auto_completed"){Mt.current=!0,wt("success"),await Io(1200),N||(et(()=>{$t.current?.({status:"succeeded"})}),wt(null),it(null));return}X&&(wt(null),it(null));let Z=f instanceof be.FloPayError?f:new be.FloPayError(f instanceof Error?f.message:"Failed to create session","api_error");An(Z)}finally{$?.(),$=void 0}})(),()=>{N=!0,$?.()})}gt(!0);async function ae(){let Te=!1;try{let z=new Mr.PaymentAPI(Q,{telemetry:!1}),X=await z.getUnifiedCheckoutSession(G,t);if(N)return;W(X);let f=X.data.session??null;if(at(f),!f)throw new be.FloPayError("No session data returned","api_error");let K=f.checkoutMode;if(K==="setup")throw new be.FloPayError("This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.","validation_error",{code:"InvalidCardSetupSurface",param:"sessionId"});if(f.status==="authorized"){gt(!1),et(()=>{$t.current?.(Er(f,G)),tn.current?.(f.successUrl??"")});return}if(f.status==="complete"){gt(!1),et(()=>{tn.current?.(f.successUrl??"")});return}if(f.status==="expired")throw jo(f);Te=!0;let Z=T??K??"full";Fn(Z),an.current+=1;let ut=f.clientSecret||t;Ln.current=f.buyerIdentified===!1&&ut?qr(z,G,ut,{...f.customer?.id?{userId:f.customer.id}:{}}):void 0,Sn(!1),se(!1);let yt=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),de=Va(X);if(Z==="auto"&&!Mt.current&&!yt&&!de){Mt.current=!0;let Me=ie(X);try{if(await dn.current(f,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>Me,sessionId:G||f.id}),N)return;await Me,N||gt(!1);return}catch{if(N)return;await Me,N||gt(!1);return}}await ie(X),N||gt(!1)}catch(z){if(N)return;Te&&te({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"}),z instanceof be.FloPayError?!Te&&!Ll(z)&&ja(Q,o,ot,"NETWORK_REQUEST_FAILED","session_read"):ja(Q,o,ot,"INTERNAL_SDK_ERROR","checkout_mount");let X=z instanceof be.FloPayError?z:new be.FloPayError(z instanceof Error?z.message:"Failed to initialize checkout","api_error");An(X),gt(!1)}}async function ie(Te){let{publishableKey:z,paypalPublishableKey:X}=ea(Te);E.current={publishableKey:z,paypalPublishableKey:X};let{flopay:f,paypalFlopay:K}=await ta({publishableKey:z,paypalPublishableKey:X,billingApiUrl:Q,locale:d,telemetry:o});Je.current=f,Be(f),F.current=K,oe(K)}return ae(),()=>{N=!0}},[T,Xt,Nn,dt,t]);let Zt=(0,k.useCallback)(async()=>{if(!(Jt||!R)){Wn(!0),qt(null);try{await Xn(R,{attempt3DS:!0,fallbackToFull:!0,sessionId:G||R.id})}finally{Wn(!1)}}},[G,Jt,Xn,R]),Bt=Ja(ee),gr=Va(ee),$n=(0,k.useMemo)(()=>{if(!(!ee||!R||!ee.data.stripe?.publishableKey))return{billingApiUrl:Q}},[ee,R,Q]),hr=!!(n&&!ve&&ce==="buttons"&&ne&&Nn==="full"),gn=(0,k.useMemo)(()=>({session:R,loading:Qt,error:Ut,checkoutMode:Bn,inlineSessionDraft:At,applyInlineSessionPatch:hr?wn:void 0,inlineSessionPatchProcessing:on,claimPending:en,claimRequiresIdentity:Nt,claimBuyerIdentity:xe}),[R,Qt,Ut,Bn,At,hr,wn,on,en,Nt,xe]),kn=!!n&&ce==="buttons"&&!gr&&(!V||!$n),Ft=rr?(0,I.jsx)(Tn,{status:rr,errorMessage:Dn,authorized:pr}):null;if(Qt){if(c)return(0,I.jsxs)(I.Fragment,{children:[c,Ft]});if(ce==="buttons"){let N=Le?.buttonsLayout?.cardButton?.borderRadius??Le?.appearance.variables?.borderRadius??8,$=ae=>(0,I.jsx)("div",{style:{height:ae,borderRadius:N,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return(0,I.jsxs)(I.Fragment,{children:[(0,I.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[S&&$(Ar),fe&&(w||ue)&&$(Ar),fe&&$(Ar),(0,I.jsx)("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),Ft]})}return(0,I.jsxs)(I.Fragment,{children:[(0,I.jsxs)("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[(0,I.jsx)("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),(0,I.jsx)("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),Ft]})}return Ut?P?(0,I.jsx)(Kn.Provider,{value:gn,children:P(Ut)}):(0,I.jsx)(Kn.Provider,{value:gn,children:(0,I.jsx)("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:Ut.message})}):kn?(0,I.jsxs)(I.Fragment,{children:[(0,I.jsx)(Kn.Provider,{value:gn,children:(0,I.jsx)(Vl,{onButtonClick:Re,showPayPal:S,showStripe:fe,showApplePay:w,showGooglePay:ue,theme:H,buttonsTheme:ge,buttonsStyles:$e,cardButtonContent:Se,cardBackButtonContent:Pt,cardTitleContent:ze})}),Ft]}):gr&&R&&Bt?(0,I.jsxs)(I.Fragment,{children:[(0,I.jsx)(Kn.Provider,{value:gn,children:(0,I.jsxs)("div",{className:J,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[mn&&(0,I.jsx)(Yr,{icon:!1,children:mn}),Gn==="retrying"&&(0,I.jsx)("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),Gn==="exhausted"&&(0,I.jsxs)("div",{role:"alert",children:[(0,I.jsx)("div",{children:"PayPal is temporarily unavailable. Please try again."}),(0,I.jsx)("button",{type:"button",onClick:Br,children:"Retry PayPal"})]}),en?c??(0,I.jsx)("div",{role:"status","data-testid":"flopay-paypal-catalog-loading","aria-label":"Preparing PayPal",style:{height:Ar,borderRadius:8,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"},children:(0,I.jsx)("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})}):Gn!=="exhausted"?(0,I.jsx)("div",{"aria-hidden":Gn==="retrying"?!0:void 0,style:Gn==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:(0,I.jsx)(Wi,{sessionId:G,nonce:R.clientSecret||void 0,billingApiUrl:Q,email:R.customer?.email||At?.account?.email,billingName:[R.customer?.firstName,R.customer?.lastName].filter(Boolean).join(" ")||[At?.account?.firstName,At?.account?.lastName].filter(Boolean).join(" ")||void 0,onBuyerIdentityReady:xe,clientId:Bt.clientId,environment:Bt.environment,currency:(R.currency??"usd").toUpperCase(),isSubscription:R.mode==="subscription",providerObjectType:Bt.providerObjectType,onComplete:y,onErrorChange:qt,onDecline:B,onButtonClick:Re,onInitializationStateChange:wr,allowAutomaticRetry:Sr===0,session:R,telemetry:o,telemetryContext:ot,onInstrument:He,debug:q},`${ke}:paypal-init-${Sr}`)}):null]})}),Ft]}):!V||!$n?(0,I.jsx)(I.Fragment,{children:Ft}):Bn==="confirm"?(0,I.jsxs)(I.Fragment,{children:[(0,I.jsx)(Kn.Provider,{value:gn,children:(0,I.jsx)(Po,{flopay:V,paypalFlopay:A,options:$n,onInstrument:He,children:(0,I.jsxs)("div",{className:J,children:[mn&&(0,I.jsx)("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:mn}),Ae?Ae({onConfirm:Zt,isProcessing:Jt}):(0,I.jsx)("button",{type:"button",onClick:Zt,disabled:Jt,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:Jt?"not-allowed":"pointer",opacity:Jt?.6:1},children:Jt?"Processing...":O??"Confirm Purchase"})]})},ke)}),Ft]}):(0,I.jsxs)(I.Fragment,{children:[(0,I.jsx)(Kn.Provider,{value:gn,children:(0,I.jsx)(Po,{flopay:V,paypalFlopay:A,options:$n,onInstrument:He,children:ve?(0,I.jsxs)(I.Fragment,{children:[mn&&(0,I.jsx)("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:mn}),(0,I.jsx)(jl,{sessionId:G,nonce:R?.clientSecret||void 0,billingApiUrl:Q,session:R,children:ve})]}):(0,I.jsx)(ia,{sessionId:G,nonce:R?.clientSecret||void 0,email:R?.customer?.email||At?.account?.email,userId:R?.customer?.id||At?.account?.userId,firstName:R?.customer?.firstName||At?.account?.firstName,lastName:R?.customer?.lastName||At?.account?.lastName,totalAmount:R?Math.round((0,be.buildCheckoutDisplayData)(R).total*100):0,currency:R?.currency?.toLowerCase()??"usd",onComplete:y,onError:h,onDecline:B,error:mn,onErrorChange:qt,showPayPal:S,showStripe:fe,enabledPaymentMethods:U??ee?.data.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:ee?.data.stripe?.enabledPaymentMethodCountries,showApplePay:w,showGooglePay:ue,layout:ce,theme:H,buttonsTheme:ge,buttonsStyles:$e,appearance:rt,cardButtonContent:Se,cardBackButtonContent:Pt,cardTitleContent:ze,onButtonClick:Re,onBeforeButtonClick:ne,onBuyerIdentityReady:xe,enableAVS:re,...L?{cardFieldOrder:L}:{},...Ee?{cardPreFormSlot:Ee}:{},avsLayout:_e,country:R?.customer?.country,city:R?.customer?.city,state:R?.customer?.state,onCountryChange:M,onZipChange:m,avsCheck:!!re,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:ve?"custom_layout":ce==="buttons"?"buttons_layout":"default_layout",className:J,directPaypal:Ja(ee),isSubscription:R?.mode==="subscription",session:R,dataAttachmentPending:en,dataAttachmentRequiresIdentity:Nt,debug:q})},ke)}),Ft]})}function jl({sessionId:e,nonce:t,billingApiUrl:n,session:r,children:o}){return(0,I.jsx)(I.Fragment,{children:k.default.Children.map(o,i=>{if(!k.default.isValidElement(i))return i;let d=i.props,c={};return d.sessionId||(c.sessionId=e),!d.nonce&&t&&(c.nonce=t),d.billingApiUrl||(c.billingApiUrl=n),r?.customer&&(d.email||(c.email=r.customer.email),d.userId||(c.userId=r.customer.id),d.firstName||(c.firstName=r.customer.firstName),d.lastName||(c.lastName=r.customer.lastName)),Object.keys(c).length===0?i:k.default.cloneElement(i,c)})})}function Vl({onButtonClick:e,showPayPal:t,showStripe:n=!0,showApplePay:r,showGooglePay:o,theme:i,buttonsTheme:d,buttonsStyles:c,cardButtonContent:P,cardBackButtonContent:y,cardTitleContent:h}){let[v,B]=(0,k.useState)(!1),M=(0,k.useMemo)(()=>(0,be.resolveTheme)(i),[i]),m=(0,k.useMemo)(()=>{let w=M?.buttonsLayout??(0,be.resolveButtonsLayoutTheme)(d);return c?{...w,...c,cardButton:{...w.cardButton,...c.cardButton},cardFormContainer:{...w.cardFormContainer,...c.cardFormContainer},backButton:{...w.backButton,...c.backButton},backButtonIcon:{...w.backButtonIcon,...c.backButtonIcon},submitButton:{...w.submitButton,...c.submitButton},title:{...w.title,...c.title}}:w},[M,d,c]),S=M?.buttonsLayout?.cardButton?.borderRadius??M?.appearance.variables?.borderRadius??8,fe=w=>(0,I.jsx)("div",{style:{height:w,borderRadius:S,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),U=P===void 0?{boxSizing:"border-box",height:Ar,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(v){let w=m.cardInputBorder??"#e5e7eb",ue=m.cardInputBackground??"white",q=Or(y),ce=Or(h);return(0,I.jsxs)("div",{style:{backgroundColor:m.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",...m.cardFormContainer},children:[(0,I.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,I.jsxs)("button",{type:"button",onClick:()=>B(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:q?0:"0.5rem",background:"none",border:"none",color:"#4b5563",fontSize:"0.85rem",fontWeight:500,padding:0,flexShrink:0,opacity:1,cursor:"pointer",...m.backButton},children:[(0,I.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...m.backButtonIcon},children:(0,I.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,I.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,I.jsx)(Ur,{content:y})]}),ce?(0,I.jsx)("div",{style:{flex:1}}):(0,I.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...m.title},children:(0,I.jsx)(mo,{content:h})})]}),(0,I.jsx)("div",{style:{backgroundColor:ue,border:`1px solid ${w}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:(0,I.jsx)("div",{style:{width:"60%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,I.jsxs)("div",{style:{display:"flex"},children:[(0,I.jsx)("div",{style:{flex:1,backgroundColor:ue,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${w}`,borderLeft:`1px solid ${w}`,borderBottomLeftRadius:8,padding:12,height:45},children:(0,I.jsx)("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,I.jsx)("div",{style:{flex:1,backgroundColor:ue,borderTop:"none",borderRight:`1px solid ${w}`,borderBottom:`1px solid ${w}`,borderLeft:`1px solid ${w}`,borderBottomRightRadius:8,padding:12,height:45},children:(0,I.jsx)("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),(0,I.jsx)("div",{style:{backgroundColor:ue,border:`1px solid ${w}`,borderRadius:8,marginTop:8,padding:12,height:45},children:(0,I.jsx)("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,I.jsx)("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",...m.submitButton,opacity:.5}}),(0,I.jsx)("style",{children:`
|
|
40
|
+
`)}):null,Mi=xe==="apm-expanding"||xe==="apm-form"||xe==="apm-collapsing",Uo=xe==="apm-expanding"?`flopay-card-enter ${Tr}ms cubic-bezier(0, 0, 0.2, 1) both`:xe==="apm-collapsing"?`flopay-card-exit ${Tr}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0,qo=Bt?{...ha,paymentMethodTypes:[Bt]}:null;if(H==="buttons"){let s=xe==="buttons"||xe==="expanding"||xe==="apm-expanding",_=xe==="expanding"||xe==="card"||xe==="collapsing",j=ze===void 0?{boxSizing:"border-box",height:ra,padding:"0 1rem"}:{padding:"0.9rem 1rem"},Ne=xe==="expanding"||xe==="apm-expanding"?`flopay-buttons-exit ${Tr}ms cubic-bezier(0.4, 0, 0.2, 1) both`:xe==="collapsing"||xe==="apm-collapsing"?`flopay-buttons-enter ${Tr}ms cubic-bezier(0, 0, 0.2, 1) both`:void 0,Y=xe==="expanding"?`flopay-card-enter ${Tr}ms cubic-bezier(0, 0, 0.2, 1) both`:xe==="collapsing"?`flopay-card-exit ${Tr}ms cubic-bezier(0.4, 0, 0.2, 1) both`:void 0;return(0,l.jsxs)("form",{onSubmit:Pa,className:B,noValidate:!0,style:{position:"relative"},children:[(0,l.jsx)(Oa,{}),Te&&(0,l.jsx)(Tn,{status:Te,errorMessage:g,authorized:Ln}),(0,l.jsxs)("div",{style:{display:"grid"},children:[(0,l.jsxs)("div",{"data-testid":"flopay-buttons-panel","aria-hidden":!s&&!Ne?!0:void 0,style:{gridArea:"1 / 1",display:"flex",flexDirection:"column",gap:"0.5rem",...!s&&!Ne?Il:{},...Ne?{animation:Ne,pointerEvents:"none"}:{}},children:[xi("flopay-direct-paypal-gate-debug"),Ti("flopay-stripe-gate-debug"),no&&A&&(0,l.jsxs)(l.Fragment,{children:[Z&&(0,l.jsx)("div",{"data-testid":"flopay-paypal-direct-retry-notice",style:{padding:"8px 10px",background:"#fef3c7",border:"1px solid #fcd34d",borderRadius:6,color:"#78350f",fontSize:13,lineHeight:1.4},children:"Please confirm your PayPal payment to complete checkout."}),(0,l.jsx)(bo,{sessionId:e,nonce:t,billingApiUrl:de,email:D.email,billingName:me||void 0,onBuyerIdentityReady:tt,clientId:A.clientId,environment:A.environment,currency:Be.toUpperCase(),isSubscription:oe,providerObjectType:C,onTokenizedBody:In,onComplete:i,onErrorChange:ge,onDecline:c,onTechnicalFailure:Dr,onButtonClick:re,runBeforeButtonClick:Vn,isProcessing:Ze,onLoadStateChange:ba,onInitializationStateChange:va,session:Et,existingOrderId:Z?.orderId,debug:Ct},Z?.orderId??"fresh")]}),ro&&(0,l.jsx)(Tt.Elements,{stripe:Fr,options:ni,children:(0,l.jsx)(ls,{sessionId:e,nonce:t,email:D.email,billingName:me||void 0,onBuyerIdentityReady:tt,billingApiUrl:de,onTokenizedBody:In,onErrorChange:ge,isProcessing:Ze,onButtonClick:re,onDecline:c,onTechnicalFailure:Dr,runBeforeButtonClick:Vn,onLoadStateChange:li,placeholderBorderRadius:kr})}),oo?(0,l.jsx)(Tt.Elements,{stripe:hn,options:ti,children:(0,l.jsx)(cs,{sessionId:e,nonce:t,email:D.email,billingName:me||void 0,onBuyerIdentityReady:tt,billingApiUrl:de,intentKind:V>0?"payment":"setup",expressMethods:Bo,onTokenizedBody:In,onErrorChange:ge,onButtonClick:re,onDecline:c,onTechnicalFailure:Dr,runBeforeButtonClick:Vn,onLoadStateChange:di,placeholderBorderRadius:kr})}):fi?(0,l.jsx)("div",{style:{height:ra,borderRadius:kr,background:"#e5e7eb",animation:"flopay-pulse 1.5s ease-in-out infinite"}}):null,ao&&(0,l.jsx)(ds,{sessionId:e,nonce:t,email:D.email,billingName:[D.firstName,D.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:tt,billingApiUrl:de,paymentElementMethods:Fo,stripeInstance:hn,paymentElementBaseOptions:ha,onTokenizedBody:In,onErrorChange:ge,onButtonClick:re,onDecline:c,runBeforeButtonClick:Vn,onLoadStateChange:pi,isProcessing:Ze,submitButtonColor:Ir,submitButtonBorderRadius:_t,submitButtonStyle:b.submitButton,onExpandApm:ae,expandedApmMethod:Bt,themeId:fe,buttonAppearance:{backgroundColor:b.cardButton?.backgroundColor,borderColor:b.cardInputBorder,textColor:b.cardButton?.color,borderRadius:kr}}),Ye&&(0,l.jsx)("button",{type:"button",onClick:async()=>{Ze||!(await Vn("card")).proceed||(re?.("card"),N())},disabled:Ze,style:{width:"100%",...j,...b.cardButton,...$a({themeBundle:p,resolvedPrimaryColor:Ir,resolvedBorderRadius:_t,submitButtonStyle:b.submitButton,explicitPrimaryColor:un?.colorPrimary}),fontSize:b.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:Ze?"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:Ze?.6:1},onMouseEnter:De=>{!Ze&&(p||un?.colorPrimary)&&(De.currentTarget.style.backgroundColor=$s)},onMouseLeave:De=>{(p||un?.colorPrimary)&&(De.currentTarget.style.backgroundColor=Ir)},onMouseDown:De=>{De.currentTarget.style.transform="scale(0.985)"},onMouseUp:De=>{De.currentTarget.style.transform="scale(1)"},children:(0,l.jsx)(zr,{content:ze})}),g&&xe==="buttons"&&(0,l.jsx)(Yr,{margin:"0.25rem 0",styleOverride:b.errorBanner,children:g})]}),Ye&&_&&(0,l.jsx)("div",{style:{gridArea:"1 / 1",...Y?{animation:Y}:{},...xe==="collapsing"?{pointerEvents:"none"}:{}},children:_i}),U&&Mi&&Bt&&qo&&hn&&(0,l.jsx)("div",{style:{gridArea:"1 / 1",...Uo?{animation:Uo}:{},...xe==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,l.jsxs)("div",{style:{backgroundColor:Sa,borderRadius:Ea,...co,padding:Ra},children:[(0,l.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,l.jsxs)("button",{type:"button","data-testid":"flopay-apm-back-button",onClick:ie,style:{display:"inline-flex",alignItems:"center",gap:wa?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:b.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...b.backButton},"aria-label":"Back to payment methods",children:[(0,l.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...b.backButtonIcon},children:(0,l.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,l.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,l.jsx)(Ur,{content:Ie})]}),(0,l.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:b.titleFontSize??"1.05rem",color:ka,paddingRight:80,...b.title},children:`Pay with ${(0,u.getStripeMethodDisplayName)(Bt)}`})]}),(0,l.jsx)(Tt.Elements,{stripe:hn,options:qo,children:(0,l.jsx)(Ua,{method:Bt,sessionId:e,nonce:t,email:D.email,billingName:[D.firstName,D.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:tt,billingApiUrl:de,onTokenizedBody:In,onErrorChange:ge,onDecline:c,onCancel:ie,runBeforeButtonClick:Vn,onButtonClick:re,isProcessing:Ze,submitButtonColor:Ir,submitButtonBorderRadius:_t,submitButtonStyle:b.submitButton,errorText:g})},Bt)]})})]})]})}return Mi&&Bt&&qo&&hn&&U?(0,l.jsxs)("form",{onSubmit:Pa,className:B,noValidate:!0,style:{position:"relative"},children:[(0,l.jsx)(Oa,{}),Te&&(0,l.jsx)(Tn,{status:Te,errorMessage:g,authorized:Ln}),(0,l.jsx)("div",{style:{...Uo?{animation:Uo}:{},...xe==="apm-collapsing"?{pointerEvents:"none"}:{}},children:(0,l.jsxs)("div",{style:{backgroundColor:Sa,borderRadius:Ea,...co,padding:Ra},children:[(0,l.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,l.jsxs)("button",{type:"button","data-testid":"flopay-apm-back-button-default",onClick:ie,style:{display:"inline-flex",alignItems:"center",gap:wa?0:"0.5rem",background:"none",border:"none",cursor:"pointer",color:"#4b5563",fontSize:b.backButtonFontSize??"0.85rem",fontWeight:500,padding:0,transition:"color 0.15s",flexShrink:0,...b.backButton},"aria-label":"Back to payment methods",children:[(0,l.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",transition:"background-color 0.15s",...b.backButtonIcon},children:(0,l.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,l.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,l.jsx)(Ur,{content:Ie})]}),(0,l.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:b.titleFontSize??"1.05rem",color:ka,paddingRight:80,...b.title},children:`Pay with ${(0,u.getStripeMethodDisplayName)(Bt)}`})]}),(0,l.jsx)(Tt.Elements,{stripe:hn,options:qo,children:(0,l.jsx)(Ua,{method:Bt,sessionId:e,nonce:t,email:D.email,billingName:[D.firstName,D.lastName].filter(Boolean).join(" ").trim()||void 0,onBuyerIdentityReady:tt,billingApiUrl:de,onTokenizedBody:In,onErrorChange:ge,onDecline:c,onCancel:ie,runBeforeButtonClick:Vn,onButtonClick:re,isProcessing:Ze,submitButtonColor:Ir,submitButtonBorderRadius:_t,submitButtonStyle:b.submitButton,errorText:g})},Bt)]})})]}):(0,l.jsxs)("form",{onSubmit:Pa,className:B,noValidate:!0,style:{position:"relative"},children:[(0,l.jsx)(Oa,{}),Te&&(0,l.jsx)(Tn,{status:Te,errorMessage:g,authorized:Ln}),(0,l.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[xi("flopay-direct-paypal-gate-debug-default"),Ti("flopay-stripe-gate-debug-default"),no&&A&&(0,l.jsxs)(l.Fragment,{children:[Z&&(0,l.jsx)("div",{"data-testid":"flopay-paypal-direct-retry-notice-default",style:{padding:"8px 10px",background:"#fef3c7",border:"1px solid #fcd34d",borderRadius:6,color:"#78350f",fontSize:13,lineHeight:1.4},children:"Please confirm your PayPal payment to complete checkout."}),(0,l.jsx)(bo,{sessionId:e,nonce:t,billingApiUrl:de,email:D.email,billingName:me||void 0,onBuyerIdentityReady:tt,clientId:A.clientId,environment:A.environment,currency:Be.toUpperCase(),isSubscription:oe,providerObjectType:C,onTokenizedBody:In,onComplete:i,onErrorChange:ge,onDecline:c,onTechnicalFailure:Dr,onButtonClick:re,runBeforeButtonClick:Vn,isProcessing:Ze,onLoadStateChange:ba,onInitializationStateChange:va,session:Et,existingOrderId:Z?.orderId,debug:Ct},Z?.orderId??"fresh")]}),ro&&(0,l.jsx)(Tt.Elements,{stripe:Fr,options:ni,children:(0,l.jsx)(ls,{sessionId:e,nonce:t,email:D.email,billingName:me||void 0,onBuyerIdentityReady:tt,billingApiUrl:de,onTokenizedBody:In,onErrorChange:ge,isProcessing:Ze,onButtonClick:re,onDecline:c,onTechnicalFailure:Dr,runBeforeButtonClick:Vn,onLoadStateChange:li,placeholderBorderRadius:kr})}),oo&&(0,l.jsx)(Tt.Elements,{stripe:hn,options:ti,children:(0,l.jsx)(cs,{sessionId:e,nonce:t,email:D.email,billingName:me||void 0,onBuyerIdentityReady:tt,billingApiUrl:de,intentKind:V>0?"payment":"setup",expressMethods:Bo,onTokenizedBody:In,onErrorChange:ge,onButtonClick:re,onDecline:c,onTechnicalFailure:Dr,runBeforeButtonClick:Vn,onLoadStateChange:di,placeholderBorderRadius:kr})}),ao&&(0,l.jsx)(ds,{sessionId:e,nonce:t,email:D.email,billingName:[D.firstName,D.lastName].filter(Boolean).join(" ").trim()||void 0,billingApiUrl:de,paymentElementMethods:Fo,stripeInstance:hn,paymentElementBaseOptions:ha,onTokenizedBody:In,onErrorChange:ge,onButtonClick:re,onDecline:c,runBeforeButtonClick:Vn,onLoadStateChange:pi,isProcessing:Ze,submitButtonColor:Ir,submitButtonBorderRadius:_t,submitButtonStyle:b.submitButton,themeId:fe,onExpandApm:ae,expandedApmMethod:Bt,buttonAppearance:{backgroundColor:b.cardButton?.backgroundColor,borderColor:b.cardInputBorder,textColor:b.cardButton?.color,borderRadius:kr}})]}),Ye&&(Ds||Fs||Ls)&&(0,l.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem",margin:"0.5rem 0 0.75rem",color:"#999",fontSize:"0.85rem"},children:[(0,l.jsx)("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}}),(0,l.jsx)("span",{children:"or pay with card"}),(0,l.jsx)("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}})]}),Ye&&_i]})}var I=require("react/jsx-runtime"),Ar=44,Za="flopay_checkout_saved_payment_resume",ca=new Map,sa=new Map;function hs(e,t){t.settled&&t.consumers===0&&ca.get(e)===t&&ca.delete(e)}function Dl(e,t,n){let r=sa.get(e);if(r&&(!r.sdkGeneratedIdempotencyKey||!t||r.sdkGeneratedIdempotencyKey===t))return r.attempt;let o=n(),i={attempt:o,sdkGeneratedIdempotencyKey:t};sa.set(e,i);let d=()=>{sa.get(e)===i&&sa.delete(e)};return o.then(d,d),o}function Io(e){return new Promise(t=>setTimeout(t,e))}function la(e,t,n){let r=Wo({billingApiUrl:e,sdkPackage:"@flopay/react",sdkVersion:be.SDK_VERSION,enabled:t!==!1});return r.beginCheckout(n),r}function Ro(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}function ja(e,t,n,r,o){let i=la(e,t,n);i.error({errorCode:r,stage:o,paymentMethodCategory:"unknown",...o==="session_read"?{requestCategory:"session_read"}:{}}),Ro(i)}function Ll(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 Ja(e){let t=e?.data.paypal?.publishableKey;if(t)return{clientId:t,environment:e?.data.paypal?.environment,providerObjectType:e?.data.paypal?.providerObjectType}}function Va(e){return!e||e.data.stripe?.publishableKey?!1:!!Ja(e)?.clientId}function ur(){return typeof window<"u"&&typeof window.sessionStorage<"u"}function Nl(){if(!ur())return null;try{let e=window.sessionStorage.getItem(Za);return e?JSON.parse(e):null}catch{return null}}function bs(e){if(ur())try{window.sessionStorage.setItem(Za,JSON.stringify(e))}catch(t){console.warn("[FloPayCheckout] Failed to persist PayPal resume state.",t)}}function Ka(){if(ur())try{window.sessionStorage.removeItem(Za)}catch(e){console.warn("[FloPayCheckout] Failed to clear PayPal resume state.",e)}}var Qa=":idempotency-key";function Ps(e,t){if(!ur())return null;let n=window.sessionStorage.getItem(e);if(!n)return null;try{let r=JSON.parse(n);return!r||typeof r.sid!="string"||!r.sid||"canonicalIdentity"in r&&r.canonicalIdentity!==t?null:{..."canonicalIdentity"in r?{canonicalIdentity:t}:{},sid:r.sid,nonce:typeof r.nonce=="string"?r.nonce:void 0}}catch{return{sid:n}}}function Ha(e,t,n,r){if(ur())try{window.sessionStorage.setItem(e,JSON.stringify(r?{canonicalIdentity:t,sid:n,nonce:r}:{canonicalIdentity:t,sid:n}))}catch(o){console.warn("[FloPayCheckout] Failed to persist checkout session cache.",o)}}function Xa(e,t){if(ur())try{Ps(e,t)&&window.sessionStorage.removeItem(e)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout session cache.",n)}}function Cs(e,t){if(!ur())return null;try{let n=window.sessionStorage.getItem(e+Qa);if(!n)return null;try{let r=JSON.parse(n);return typeof r=="string"?r?{idempotencyKey:r}:null:!r||typeof r.idempotencyKey!="string"||!r.idempotencyKey||"canonicalIdentity"in r&&r.canonicalIdentity!==t?null:{..."canonicalIdentity"in r?{canonicalIdentity:t}:{},idempotencyKey:r.idempotencyKey}}catch{return{idempotencyKey:n}}}catch{return null}}function Ya(e,t,n){if(ur())try{window.sessionStorage.setItem(e+Qa,JSON.stringify({canonicalIdentity:t,idempotencyKey:n}))}catch(r){console.warn("[FloPayCheckout] Failed to persist checkout idempotency key.",r)}}function Wa(e,t){if(Xa(e,t),!!ur())try{Cs(e,t)&&window.sessionStorage.removeItem(e+Qa)}catch(n){console.warn("[FloPayCheckout] Failed to clear checkout idempotency key.",n)}}function Ol(){if(typeof window>"u")return;let e=new URL(window.location.href),t=["payment_intent","payment_intent_client_secret","redirect_status"],n=!1;for(let r of t)e.searchParams.has(r)&&(e.searchParams.delete(r),n=!0);n&&window.history.replaceState(window.history.state,"",e.toString())}function vs(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 zl(e){return e?!!(e.account&&Object.keys(e.account).length>0||e.couponCodes!==void 0||e.checkoutMetadata!==void 0||e.tagsData!==void 0||e.utmMetadata!==void 0):!1}function Ga(e,t){return`${e}:${t.totalAmount??""}:${t.overrideAmount??""}:${t.quantity??1}:${t.currency??""}`}function Ul(e){if(e==null)return e;let t=JSON.stringify(Object.entries(e).sort(([d],[c])=>d<c?-1:d>c?1:0)),n=1779033703,r=3144134277,o=1013904242,i=2773480762;for(let d=0;d<t.length;d++){let c=t.charCodeAt(d);n=r^Math.imul(n^c,597399067),r=o^Math.imul(r^c,2869860233),o=i^Math.imul(o^c,951274213),i=n^Math.imul(i^c,2716044179)}return n=Math.imul(o^n>>>18,597399067),r=Math.imul(i^r>>>22,2869860233),o=Math.imul(n^o>>>17,951274213),i=Math.imul(r^i>>>19,2716044179),n^=r^o^i,r^=n,o^=n,i^=n,[n,r,o,i].map(d=>(d>>>0).toString(16).padStart(8,"0")).join("")}function Eo(e,t=!1){let n=e?.account?.email?.trim().toLowerCase()??"",r={c:e?.clientId,cur:e?.currency??"",captureMethod:e?.captureMethod??"",a:{e:n,u:n?"":e?.account?.userId??"",country:e?.account?.country??""},successUrl:e?.successUrl,cancelUrl:e?.cancelUrl,p:e?.products?.map(o=>Ga(`${o.type??""}:${o.code??o.providerItemId??o.providerPlanId??""}`,o)).sort(),i:e?.items?.map(o=>Ga(o.code??o.providerItemId??"",o)).sort(),s:e?.subscriptions?.map(o=>Ga(o.code??o.providerPlanId??"",o)).sort(),couponCodes:e?.couponCodes?[...e.couponCodes].sort():void 0,checkoutMetadata:Ul(e?.checkoutMetadata),...t?{tagsData:e?.tagsData,utmMetadata:e?.utmMetadata,tokenizedData:e?.tokenizedData,checkoutMode:e?.checkoutMode??"full"}:{}};return JSON.stringify(r)}function ql(e,t=!1){let n=Eo(e,t),r=0;for(let o=0;o<n.length;o++)r=(r<<5)-r+n.charCodeAt(o)|0;return`flopay_session_${Math.abs(r).toString(36)}`}function $l(e,t){if(!e?.customer||!e.products||t.checkoutMetadata!==void 0)return!1;let n=t.account.email?.trim().toLowerCase()??"",r=e.customer.email?.trim().toLowerCase()??"";if((n?r!==n:e.customer.id!==t.account.userId)||(t.account.country??"").trim().toUpperCase()!==(e.customer.country??"").trim().toUpperCase()||e.successUrl!==t.successUrl||e.cancelUrl!==t.cancelUrl||(e.captureMethod??"automatic")!==(t.captureMethod??"automatic"))return!1;let o=(0,be.resolveSessionCurrency)(t.currency,t.items,t.subscriptions,t.products);if(!o||e.currency.toUpperCase()!==o.toUpperCase())return!1;let i=(t.products??(0,be.foldIntoProducts)(t.items,t.subscriptions)).map(y=>({type:y.type,code:y.code??y.providerItemId??y.providerPlanId??"",quantity:y.quantity??1,totalAmount:y.totalAmount,overrideAmount:y.overrideAmount??null,currency:(y.currency??o).toUpperCase()})).sort((y,h)=>`${y.code}:${y.type??""}`.localeCompare(`${h.code}:${h.type??""}`)),d=e.products.map(y=>({type:y.type,code:y.code??"",quantity:y.quantity??1,totalAmount:y.totalAmount,overrideAmount:y.overrideAmount??null,currency:(y.currency??e.currency).toUpperCase()})).sort((y,h)=>`${y.code}:${y.type??""}`.localeCompare(`${h.code}:${h.type??""}`));if(i.length!==d.length)return!1;for(let y=0;y<i.length;y+=1){let h=i[y],v=d[y];if(h.code!==v.code||h.type!==void 0&&h.type!==v.type||h.quantity!==v.quantity||h.totalAmount!==v.totalAmount||h.overrideAmount!==v.overrideAmount||h.currency!==v.currency)return!1}let c=[...t.couponCodes??[]].sort(),P=[...e.coupons??[]].sort();return c.length===P.length&&c.every((y,h)=>y===P[h])}function da({sessionId:e,nonce:t,createSession:n,billingApiUrl:r,telemetry:o,appearance:i,locale:d,loading:c,error:P,onComplete:y,onError:h,onInstrument:v,onDecline:B,onCountryChange:M,onZipChange:m,showPayPal:S=!0,showStripe:he=!0,enabledPaymentMethods:U,showApplePay:w=!0,showGooglePay:ue=!0,debug:q=!1,layout:ce,theme:H,buttonsTheme:fe,buttonsStyles:$e,cardButtonContent:Se,cardBackButtonContent:Pt,cardTitleContent:ze,showSecurityFooter:Ie,onButtonClick:Re,onBeforeButtonClick:ne,enableAVS:re,cardFieldOrder:L,cardPreFormSlot:Ee,avsLayout:_e,className:J,initialErrorMessage:we=null,children:ve,checkoutMode:T,confirmLabel:O,renderConfirmButton:Ae,onSessionCompleted:ye}){let Q=(0,be.resolveBillingApiUrl)(r),Le=(0,k.useMemo)(()=>(0,be.resolveTheme)(H),[H]),rt=i??Le?.appearance,ct=n?"embedded_checkout":"standard_checkout",Oe=ve?"custom_layout":ce==="buttons"?"buttons_layout":"default_layout",[ee,W]=(0,k.useState)(null),[V,Be]=(0,k.useState)(null),Je=(0,k.useRef)(null),[A,oe]=(0,k.useState)(null),F=(0,k.useRef)(null),[R,at]=(0,k.useState)(null),Ct=(0,k.useMemo)(()=>n?Eo(n):"",[n]),ke=n?`create:${Ct}`:`session:${e??""}`,pt=R?.gateways?.stripe?"stripe":R?.gateways?.paypal?"paypal":void 0,Fe=(0,k.useRef)(new Set),mt=(0,k.useRef)(ke),Et=(0,k.useRef)(ke);ho(()=>{Et.current=ke,mt.current!==ke&&(mt.current=ke,Fe.current.clear())},[ke]);let C=(0,k.useCallback)(N=>{if(Et.current===ke){if(Ma.has(N.name)){if(Fe.current.has(N.name))return;Fe.current.add(N.name)}et(()=>v?.(N))}},[ke,v]),te=Hr(C,ke),Xe=(0,k.useRef)(!1),He=(0,k.useCallback)(N=>{if(Xe.current)return;let $=N.gateway||!pt?N:{...N,gateway:pt};C($)},[C,pt]);(0,k.useEffect)(()=>{te({class:"lifecycle",name:"checkout.mount"})},[te]);let[zt,Lt]=(0,k.useState)(e??""),G=e??zt,dt=n?"":G,[Qt,gt]=(0,k.useState)(!0),[Ut,An]=(0,k.useState)(null),[Bn,Fn]=(0,k.useState)("full"),[Jt,Wn]=(0,k.useState)(!1),[mn,qt]=(0,k.useState)(we),[rr,wt]=(0,k.useState)(null),[Dn,it]=(0,k.useState)(null),[pr,kt]=(0,k.useState)(!1),[Pn,It]=(0,k.useState)(void 0),[Kt,yn]=(0,k.useState)(""),[on,Cn]=(0,k.useState)(!1),[en,Sn]=(0,k.useState)(!1),[Nt,se]=(0,k.useState)(!1),an=(0,k.useRef)(0),Ln=(0,k.useRef)(void 0),[Gn,Cr]=(0,k.useState)("loading"),[Sr,mr]=(0,k.useState)(0),Mt=(0,k.useRef)(!1),Ye=(0,k.useRef)(!1),yr=(0,k.useRef)(!1),E=(0,k.useRef)(null),ot=(0,k.useMemo)(()=>({checkoutMode:T??Bn,layout:ve?"unknown":ce==="buttons"?"buttons":"embedded"}),[T,ve,Bn,ce]),$t=(0,k.useRef)(y);$t.current=y;let fn=(0,k.useRef)(h);fn.current=h;let Pe=(0,k.useRef)(B);Pe.current=B,(0,k.useEffect)(()=>{Vt(V)?.setCheckoutContext(ot),A&&A!==V&&Vt(A)?.setCheckoutContext(ot)},[V,A,ot]);let tn=(0,k.useRef)(ye);tn.current=ye;let wr=(0,k.useCallback)(N=>{Cr(N),!(N!=="exhausted"||yr.current)&&(yr.current=!0,fn.current?.(new be.FloPayError("PayPal is temporarily unavailable. Please try again.","api_error",{code:"paypal_init_timeout"})))},[]),Br=(0,k.useCallback)(()=>{Cr("retrying"),mr(N=>N+1)},[]);(0,k.useEffect)(()=>{Cr("loading"),mr(0),yr.current=!1},[G]),(0,k.useEffect)(()=>{console.info("[FloPay] Checkout initialized",{sdk_version:be.SDK_VERSION,checkout_type:ct,checkout_layout:Oe,billing_api_url:Q})},[Oe,ct,Q]);let sn=(0,k.useMemo)(()=>n?Eo(n,!0):"",[n]),fr=(0,k.useMemo)(()=>Kt===sn?Pn:void 0,[Pn,Kt,sn]),Jn=(0,k.useMemo)(()=>n?_a(n,fr):void 0,[n,fr]),Nn=T??Jn?.checkoutMode??"full",At=(0,k.useMemo)(()=>Jn?{...Jn,checkoutMode:Nn}:void 0,[Jn,Nn]);(0,k.useEffect)(()=>{It(void 0),yn(sn),Ln.current=void 0,se(!1)},[sn]),(0,k.useEffect)(()=>{qt(we)},[we]);let On=(0,k.useCallback)((N,$,ae)=>{et(()=>{Pe.current?.(jt(N,$,ae))})},[]),Xn=(0,k.useCallback)(async(N,$)=>{qt(null),it(null),kt(!1),wt("processing");let ae=$?.sessionId??N.id,ie=N.gateways?.stripe?"stripe":N.gateways?.paypal?"paypal":void 0,Te=Je.current??F.current,z=Vt(Te),X=Te?null:la(Q,o,ot),f={log:g=>{z?z.log(g):X?.log(g)},error:g=>{z?z.error(g):X?.error(g)},terminal:g=>{z?z.terminal(g):X?.terminal(g)},performance:g=>{z?z.performance(g):X?.performance(g)},now:()=>z?.now()??X?.now()??0,elapsed:g=>z?.elapsed(g)??Math.max(0,(X?.now()??g)-g)},K=f.now(),Z=!!($?.initialAutoProcessingError||$?.initialAutoProcessingPending),ut=!1,yt,de=()=>{ut||(ut=!0,Z=!0,yt=f.now(),f.log({name:"checkout.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}),f.log({name:"operation.recovery.started",stage:"recovery",paymentMethodCategory:"saved"}))},Me=!1,Ht=()=>{Me||(Me=!0,f.log({name:"payment.processing.completed",stage:"processing",paymentMethodCategory:"saved"}),f.performance({stage:"processing",durationMs:f.elapsed(K),durationMode:"machine",paymentMethodCategory:"saved"}),yt!==void 0&&f.performance({stage:"recovery",durationMs:f.elapsed(yt),durationMode:"machine",paymentMethodCategory:"saved"}))};f.log({name:"payment.method.selected",stage:"processing",paymentMethodCategory:"saved"}),Xe.current=!0;try{f.log({name:"payment.processing.started",stage:"processing",paymentMethodCategory:"saved"})}finally{Xe.current=!1}te({class:"lifecycle",name:"payment.processing.started",provider:ie}),Z&&de();let tt;try{let g=Xi($?.initialAutoProcessingError),p;if(g)de(),g.type==="paypal_redirect_required"&&E.current?.publishableKey&&bs({sessionId:ae,publishableKey:E.current.publishableKey,paypalPublishableKey:E.current.paypalPublishableKey}),p=await Qo(g,{flopay:Je.current,paypalFlopay:F.current,attempt3DS:$?.attempt3DS,billingApiUrl:Q,sessionId:ae,session:N,telemetry:!1}),g.type==="paypal_redirect_required"&&Ka();else if($?.initialAutoProcessingPending){let pe=(await new Mr.PaymentAPI(Q,{telemetry:!1}).waitForCheckoutSessionCompletion($.initialAutoProcessingPending.sessionId,{initialDelayMs:$.initialAutoProcessingPending.retryAfterMs})).data.session;if(!$r(pe))throw Vo(pe);p=Er(pe,ae)}else{if($?.initialAutoProcessingError)throw Pr($.initialAutoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:$.initialAutoProcessingError.checkoutMethod});if($?.fromCreateSession)return $?.fallbackToFull&&(Fn("full"),vs("full")),!1;{let b=await Jr({billingApiUrl:Q,sessionId:ae,session:N,telemetry:!1});b.type==="success"?p=b.result:(de(),b.type==="paypal_redirect_required"&&E.current?.publishableKey&&bs({sessionId:ae,publishableKey:E.current.publishableKey,paypalPublishableKey:E.current.paypalPublishableKey}),p=await Qo(b,{flopay:Je.current,paypalFlopay:F.current,attempt3DS:$?.attempt3DS,billingApiUrl:Q,sessionId:ae,session:N,telemetry:!1}),b.type==="paypal_redirect_required"&&Ka())}}ae&&Wr(ae),Ht(),Z&&(f.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),f.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),f.terminal({outcome:p.status==="authorized"?"payment_authorized":"payment_succeeded",paymentMethodCategory:"saved"}),kt(p.status==="authorized"),wt("success"),await Io(1200),tt=()=>$t.current?.(p)}catch(g){let p=wo(g),b=p.checkoutMethod??So;qt(p.message),it(p.message),kt(!1),$?.fallbackToFull&&(f.log({name:"operation.fallback",stage:"recovery",paymentMethodCategory:"saved"}),Fn("full"),vs("full")),Ht();let Ce=p.statusCode!==void 0?(0,be.telemetryStatusClass)(p.statusCode,"unknown"):void 0,pe=Ce==="4xx"?{requestCategory:"process_payment",statusClass:Ce}:{},We=Ce===void 0||Ce==="4xx";if(We&&(p.telemetryOutcome==="payment_declined"||!!(p.declineCode||p.code?.toLowerCase().includes("declin"))))f.terminal({outcome:"payment_declined",paymentMethodCategory:"saved",...pe});else if(We&&(p.telemetryOutcome==="validation_rejected"||p.type==="validation_error"))f.terminal({outcome:"validation_rejected",paymentMethodCategory:"saved",...pe});else{let D=(0,be.classifyTelemetryFailure)(g,Z?"RECOVERY_FAILED":"PAYMENT_PROCESSING_FAILED","unknown"),me=p.telemetryRequestCategory??"process_payment";Xe.current=!0;try{f.error({...D,...p.telemetryFailureCategory?{failureCategory:p.telemetryFailureCategory}:{},stage:Z?"recovery":"processing",paymentMethodCategory:"saved",requestCategory:me})}finally{Xe.current=!1}te({class:"technical_error",errorCode:"PAYMENT_PROCESSING_FAILED",requestCategory:me,provider:ie})}return et(()=>fn.current?.(p)),On(b,p,{code:p.code,declineCode:p.declineCode}),wt("error"),await Promise.allSettled([Io(1500),$?.ensureProvidersReady?$.ensureProvidersReady():Promise.resolve()]),Z&&(f.log({name:"checkout.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"}),f.log({name:"operation.recovery.completed",stage:"recovery",paymentMethodCategory:"saved"})),!1}finally{Ht(),X&&Ro(X),wt(null),it(null)}return et(tt),!0},[On,te,Q,o,ot]);(0,k.useEffect)(()=>{if(typeof window>"u"||Ye.current)return;let N=new URLSearchParams(window.location.search),$=N.get("payment_intent_client_secret");if(!$)return;let ae=Nl();ae&&(Ye.current=!0,(async()=>{let ie,Te=0;qt(null),it(null),wt("processing"),Wn(!0);try{if(N.get("redirect_status")==="failed")throw Object.assign(new be.FloPayError("PayPal payment was declined. Please try again.","api_error",{declineCode:"paypal_redirect_failed"}),{checkoutMethod:"paypal"});let{flopay:z,paypalFlopay:X}=await ta({publishableKey:ae.publishableKey,paypalPublishableKey:ae.paypalPublishableKey,billingApiUrl:Q,locale:d,telemetry:o});ie=Vt(X??z),Te=ie?.now()??0,ie?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),ie?.log({name:"operation.recovery.started",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"});let f=(X??z)?.getRawProvider();if(!f)throw Object.assign(new be.FloPayError("PayPal is not available.","api_error"),{checkoutMethod:"paypal"});let{paymentIntent:K,error:Z}=await f.retrievePaymentIntent($);if(Z)throw Object.assign(new be.FloPayError(Z.message??"Failed to retrieve PayPal payment status.","api_error",{code:Z.code}),{checkoutMethod:"paypal"});let ut=Ni(K?.status);if(!K||ut==="failed")throw Object.assign(new be.FloPayError("PayPal payment was not completed. Please try again.","api_error"),{checkoutMethod:"paypal"});let yt=typeof K.payment_method=="string"?K.payment_method:K.payment_method?.id,de=ut;if(ae.sessionId){let tt=(await new Mr.PaymentAPI(Q,{telemetry:!1}).getUnifiedCheckoutSession(ae.sessionId)).data.session;if(tt&&tt.status!=="complete"){let g=await Jr({billingApiUrl:Q,sessionId:ae.sessionId,session:tt,telemetry:!1,tokenizedData:{id:yt??K.id,type:"card",threeDSecureActionResultTokenId:K.id,isPaypal:!0}});if(g.type!=="success")throw Object.assign(new be.FloPayError("Failed to finalize PayPal payment.","api_error"),{checkoutMethod:"paypal"});de=g.result.status}}ae.sessionId&&Wr(ae.sessionId),ie?.log({name:"operation.recovery.completed",stage:"recovery",provider:"paypal",paymentMethodCategory:"paypal"}),ie?.performance({stage:"redirect_resume",durationMs:ie.elapsed(Te),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),ie?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}),wt("success"),await Io(1200),et(()=>$t.current?.({status:de,paymentIntentId:K.id,paymentMethodId:yt,checkoutMethod:"paypal"}))}catch(z){let X=wo(z),f=X.checkoutMethod??"paypal",K=!!(X.declineCode||X.code?.toLowerCase().includes("declin"));if(ie)ie.performance({stage:"redirect_resume",durationMs:ie.elapsed(Te),durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),K?ie.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):ie.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"});else if(K){let Z=la(Q,o,ot);Z.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}),Ro(Z)}else ja(Q,o,ot,"REDIRECT_RESUME_FAILED","redirect_resume");qt(X.message),it(X.message),et(()=>fn.current?.(X)),On(f,X,{code:X.code,declineCode:X.declineCode}),wt("error"),await Io(1500)}finally{Ka(),Ol(),wt(null),it(null),Wn(!1)}})())},[On,d,Q,o,ot]);let ln=(0,k.useRef)(null),Xt=(0,k.useMemo)(()=>At?Eo(At):"",[At]),zn=(0,k.useRef)(At);zn.current=At,(0,k.useEffect)(()=>{Lt(e??"")},[e]),(0,k.useEffect)(()=>{Mt.current=!1,qt(we),it(null),kt(!1),wt(null)},[Xt,we,e]);async function Un(N,$,ae){let ie=la(Q,o,ot),Te=new Mr.PaymentAPI(Q,{telemetry:!1}),z=!1;try{let X=N.idempotencyKey!==void 0?(0,be.resolveIdempotencyKey)(N.idempotencyKey):void 0,f=Ps($,ae),K=Cs($,ae);f?.canonicalIdentity===ae&&K&&K.canonicalIdentity===void 0&&(Ya($,ae,K.idempotencyKey),K={...K,canonicalIdentity:ae});let Z=X??(K?.canonicalIdentity===ae?K.idempotencyKey:void 0),ut,yt=!1;ie.log({name:f?"operation.cache.hit":"operation.cache.miss",stage:"session_create",requestCategory:"session_create"});let de=f?.sid??null,Me=null,Ht,tt,g=!1;if(de)try{Me=await Te.getUnifiedCheckoutSession(de,f?.nonce),f&&f.canonicalIdentity===void 0&&($l(Me.data.session,N)?(Ha($,ae,de,f.nonce??Me.data.session?.clientSecret),K&&K.canonicalIdentity===void 0&&(Ya($,ae,K.idempotencyKey),Z??(Z=K.idempotencyKey))):(Wa($,ae),K=null,Z=X,de=null,Me=null));let b=Me?.data.session?.status,Ce=Me?.data.session,pe=Ce?.clientSecret||f?.nonce;if(de&&Ce?.buyerIdentified===!1&&pe&&(tt=qr(Te,de,pe,N.account)),de&&Me&&b==="complete"){if(Ba(de))return{sid:de,result:Me};Wa($,ae),de=null,Me=null,yt=!0}}catch{ie.log({name:"operation.fallback",stage:"session_read",requestCategory:"session_read"}),f?.canonicalIdentity===void 0?(Wa($,ae),Z=X):Xa($,ae),de=null}if(!de){!X&&(yt||!Z)&&(Z=(0,be.resolveIdempotencyKey)(),ut=Z),Z&&Ya($,ae,Z);let b=ie.now(),Ce=0;ie.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let pe={...N,idempotencyKey:Z,avsCheck:!!re,avsConfig:typeof re=="object"?re:void 0,checkoutType:"embedded_checkout",checkoutLayout:ve?"custom_layout":ce==="buttons"?"buttons_layout":"default_layout"};Object.defineProperty(pe,Mr.SESSION_CREATE_TELEMETRY,{configurable:!1,enumerable:!1,value:{onAttempt:le=>{Ce=Math.max(Ce,le)}}});let We=()=>{ie.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:"2xx"}),ie.performance({stage:"session_create",durationMs:ie.now()-b,durationMode:"machine",requestCategory:"session_create",attempt:Ce,statusClass:"2xx"})},Ze=le=>{let D=(0,be.classifyTelemetryFailure)(le,"CHECKOUT_SESSION_CREATE_FAILED","unknown");ie.performance({stage:"session_create",durationMs:ie.now()-b,durationMode:"machine",requestCategory:"session_create",attempt:Ce,statusClass:D.statusClass}),le instanceof be.FloPayError&&le.type==="validation_error"?ie.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown"}):D.statusClass==="4xx"?ie.terminal({outcome:"validation_rejected",stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create",statusClass:"4xx"}):(ie.error({...D,stage:"session_create",paymentMethodCategory:"unknown",requestCategory:"session_create"}),te({class:"technical_error",errorCode:"CHECKOUT_SESSION_CREATE_FAILED",requestCategory:"session_create"}))};try{if((0,be.isDetachedSessionEligible)(pe)){let le=await Te.createDetachedSession(pe);le.claimed.catch(()=>{}),Me=le.shell,de=le.sessionId,tt=le.claim,Ht=le.claimed.then(D=>{let me=D.data.session?.id??le.sessionId;return me&&Ha($,ae,me,D.data.session?.clientSecret??le.nonce),We(),D},D=>{throw Xa($,ae),Ze(D),D}).finally(()=>Ro(ie)),Ht.catch(()=>{}),z=!0,ie.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",paymentMethodCategory:"card",statusClass:"2xx"}),ie.performance({stage:"session_shell",durationMs:ie.now()-b,durationMode:"machine",requestCategory:"session_create",attempt:Ce,statusClass:"2xx",paymentMethodCategory:"card"})}else Me=await Te.createAndFetchSession(pe),We()}catch(le){throw Ze(le),le}de=Me.data.session?.id??de??"",de&&!Ht&&Ha($,ae,de,Me.data.session?.clientSecret)}let p=Me?.data.session;return!tt&&de&&p?.buyerIdentified===!1&&p.clientSecret&&(tt=qr(Te,de,p.clientSecret,N.account)),{sid:de??"",result:Me,sdkGeneratedIdempotencyKey:ut,...Ht?{claimed:Ht}:{},...tt?{claim:tt}:{},...g?{claimRequiresIdentity:!0}:{}}}finally{z||Ro(ie)}}let st=(0,k.useRef)(Un);ho(()=>{st.current=Un},[Un]);let cn=(0,k.useCallback)(async(N,$)=>{let ae=zn.current;if(!ae)throw new be.FloPayError("createSession is required to bootstrap checkout.","validation_error");let ie=_a(ae,N),Te=Eo(ie),z=ql(ie),X=ca.get(Te);if(!X){let Z={canonicalIdentity:Te,promise:st.current(ie,z,Te),consumers:0,settled:!1};X=Z,ca.set(Te,Z);let ut=()=>{Z.settled=!0,hs(Te,Z)};Z.promise.then(ut,ut)}X.consumers+=1;let f=!1,K=()=>{f||(f=!0,X.consumers-=1,hs(Te,X))};$?.(K);try{let Z=await X.promise;ln.current=Te,N&&(yn(sn),It(Ce=>Fi(Ce,N)));let{sid:ut,result:yt,claimed:de,claim:Me,claimRequiresIdentity:Ht}=Z;if(Ln.current=Me,se(Ht===!0),W(yt),yt.data.session&&at(yt.data.session),ut&&Lt(ut),de){an.current+=1;let Ce=an.current;Sn(!0),de.then(pe=>{an.current===Ce&&(W(pe),pe.data.session&&at(pe.data.session),Sn(!1),se(!1))},pe=>{an.current===Ce&&(Sn(!1),se(!1),An(pe instanceof be.FloPayError?pe:new be.FloPayError(pe instanceof Error?pe.message:"Failed to create session","api_error")))})}else an.current+=1,Sn(!1),se(!1);let{publishableKey:tt,paypalPublishableKey:g}=ea(yt),{flopay:p,paypalFlopay:b}=await ta({publishableKey:tt,paypalPublishableKey:g,billingApiUrl:Q,locale:d,telemetry:o});return Je.current=p,Be(p),F.current=b,oe(b),gt(!1),Z}catch(Z){throw ln.current===Te&&(ln.current=null),Z}finally{$||K()}},[sn,d,Q,o]),dn=(0,k.useRef)(Xn);dn.current=Xn;let qn=(0,k.useRef)(cn);qn.current=cn;let wn=(0,k.useCallback)(async N=>{if(!zl(N)||on)return{sessionId:zt,session:R};Cn(!0);try{let $=await cn(N);return{sessionId:$.sid,session:$.result.data.session??null}}finally{Cn(!1)}},[cn,on,zt,R]),xe=(0,k.useCallback)(async N=>{let $=Ln.current;if(!$)return;let ae=an.current,ie=await $(N);an.current===ae&&(W(ie),ie.data.session&&at(ie.data.session))},[]);(0,k.useEffect)(()=>{let N=!1,$;if(An(null),Xt){let Te=zn.current;return Fn(Nn),gt(!1),ln.current===Xt?()=>{N=!0}:(at(Di(Te,T)),(async()=>{let z=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),X=Nn==="auto"&&!Mt.current&&!z;X&&(qt(null),it(null),wt("processing"));try{let f=await qn.current(void 0,yt=>{$=yt}),K=f.result.data.session??null;E.current=ea(f.result);let Z=Va(f.result),ut=Ba(f.sid||K?.id);if(!N&&X&&K&&!Z&&!ut){Mt.current=!0,await Dl(Xt,f.sdkGeneratedIdempotencyKey,()=>dn.current(K,{attempt3DS:!0,fallbackToFull:!0,fromCreateSession:!0,initialAutoProcessingError:f.result.autoProcessingError,initialAutoProcessingPending:f.result.autoProcessingPending,autoProcessingAttempted:f.result.autoProcessingAttempted,sessionId:f.sid||K.id}));return}!N&&X&&((Z||ut)&&(Mt.current=!0),wt(null),it(null))}catch(f){if(N)return;let K=f instanceof be.FloPayError||typeof f=="object"&&f!==null&&"code"in f?f.code:void 0;if(X&&K==="session_auto_completed"){Mt.current=!0,wt("success"),await Io(1200),N||(et(()=>{$t.current?.({status:"succeeded"})}),wt(null),it(null));return}X&&(wt(null),it(null));let Z=f instanceof be.FloPayError?f:new be.FloPayError(f instanceof Error?f.message:"Failed to create session","api_error");An(Z)}finally{$?.(),$=void 0}})(),()=>{N=!0,$?.()})}gt(!0);async function ae(){let Te=!1;try{let z=new Mr.PaymentAPI(Q,{telemetry:!1}),X=await z.getUnifiedCheckoutSession(G,t);if(N)return;W(X);let f=X.data.session??null;if(at(f),!f)throw new be.FloPayError("No session data returned","api_error");let K=f.checkoutMode;if(K==="setup")throw new be.FloPayError("This is a card setup session. Use FloPayCardSetup instead of FloPayCheckout.","validation_error",{code:"InvalidCardSetupSurface",param:"sessionId"});if(f.status==="authorized"){gt(!1),et(()=>{$t.current?.(Er(f,G)),tn.current?.(f.successUrl??"")});return}if(f.status==="complete"){gt(!1),et(()=>{tn.current?.(f.successUrl??"")});return}if(f.status==="expired")throw jo(f);Te=!0;let Z=T??K??"full";Fn(Z),an.current+=1;let ut=f.clientSecret||t;Ln.current=f.buyerIdentified===!1&&ut?qr(z,G,ut,{...f.customer?.id?{userId:f.customer.id}:{}}):void 0,Sn(!1),se(!1);let yt=typeof window<"u"&&new URLSearchParams(window.location.search).has("payment_intent"),de=Va(X);if(Z==="auto"&&!Mt.current&&!yt&&!de){Mt.current=!0;let Me=ie(X);try{if(await dn.current(f,{attempt3DS:!0,fallbackToFull:!0,ensureProvidersReady:()=>Me,sessionId:G||f.id}),N)return;await Me,N||gt(!1);return}catch{if(N)return;await Me,N||gt(!1);return}}await ie(X),N||gt(!1)}catch(z){if(N)return;Te&&te({class:"technical_error",errorCode:"SDK_INITIALIZATION_FAILED"}),z instanceof be.FloPayError?!Te&&!Ll(z)&&ja(Q,o,ot,"NETWORK_REQUEST_FAILED","session_read"):ja(Q,o,ot,"INTERNAL_SDK_ERROR","checkout_mount");let X=z instanceof be.FloPayError?z:new be.FloPayError(z instanceof Error?z.message:"Failed to initialize checkout","api_error");An(X),gt(!1)}}async function ie(Te){let{publishableKey:z,paypalPublishableKey:X}=ea(Te);E.current={publishableKey:z,paypalPublishableKey:X};let{flopay:f,paypalFlopay:K}=await ta({publishableKey:z,paypalPublishableKey:X,billingApiUrl:Q,locale:d,telemetry:o});Je.current=f,Be(f),F.current=K,oe(K)}return ae(),()=>{N=!0}},[T,Xt,Nn,dt,t]);let Zt=(0,k.useCallback)(async()=>{if(!(Jt||!R)){Wn(!0),qt(null);try{await Xn(R,{attempt3DS:!0,fallbackToFull:!0,sessionId:G||R.id})}finally{Wn(!1)}}},[G,Jt,Xn,R]),Bt=Ja(ee),gr=Va(ee),$n=(0,k.useMemo)(()=>{if(!(!ee||!R||!ee.data.stripe?.publishableKey))return{billingApiUrl:Q}},[ee,R,Q]),hr=!!(n&&!ve&&ce==="buttons"&&ne&&Nn==="full"),gn=(0,k.useMemo)(()=>({session:R,loading:Qt,error:Ut,checkoutMode:Bn,inlineSessionDraft:At,applyInlineSessionPatch:hr?wn:void 0,inlineSessionPatchProcessing:on,claimPending:en,claimRequiresIdentity:Nt,claimBuyerIdentity:xe}),[R,Qt,Ut,Bn,At,hr,wn,on,en,Nt,xe]),kn=!!n&&ce==="buttons"&&!gr&&(!V||!$n),Ft=rr?(0,I.jsx)(Tn,{status:rr,errorMessage:Dn,authorized:pr}):null;if(Qt){if(c)return(0,I.jsxs)(I.Fragment,{children:[c,Ft]});if(ce==="buttons"){let N=Le?.buttonsLayout?.cardButton?.borderRadius??Le?.appearance.variables?.borderRadius??8,$=ae=>(0,I.jsx)("div",{style:{height:ae,borderRadius:N,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"}});return(0,I.jsxs)(I.Fragment,{children:[(0,I.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[S&&$(Ar),he&&(w||ue)&&$(Ar),he&&$(Ar),(0,I.jsx)("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]}),Ft]})}return(0,I.jsxs)(I.Fragment,{children:[(0,I.jsxs)("div",{style:{display:"flex",justifyContent:"center",padding:32},children:[(0,I.jsx)("div",{style:{width:24,height:24,border:"2px solid #e5e7eb",borderTopColor:"#6b7280",borderRadius:"50%",animation:"spin 0.6s linear infinite"}}),(0,I.jsx)("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]}),Ft]})}return Ut?P?(0,I.jsx)(Kn.Provider,{value:gn,children:P(Ut)}):(0,I.jsx)(Kn.Provider,{value:gn,children:(0,I.jsx)("div",{role:"alert","data-testid":"flopay-load-error",style:{padding:24,textAlign:"center",color:"#dc2626",fontSize:14},children:Ut.message})}):kn?(0,I.jsxs)(I.Fragment,{children:[(0,I.jsx)(Kn.Provider,{value:gn,children:(0,I.jsx)(Vl,{onButtonClick:Re,showPayPal:S,showStripe:he,showApplePay:w,showGooglePay:ue,theme:H,buttonsTheme:fe,buttonsStyles:$e,cardButtonContent:Se,cardBackButtonContent:Pt,cardTitleContent:ze})}),Ft]}):gr&&R&&Bt?(0,I.jsxs)(I.Fragment,{children:[(0,I.jsx)(Kn.Provider,{value:gn,children:(0,I.jsxs)("div",{className:J,style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[mn&&(0,I.jsx)(Yr,{icon:!1,children:mn}),Gn==="retrying"&&(0,I.jsx)("div",{role:"status","aria-live":"polite",children:"PayPal is temporarily unavailable. Retrying\u2026"}),Gn==="exhausted"&&(0,I.jsxs)("div",{role:"alert",children:[(0,I.jsx)("div",{children:"PayPal is temporarily unavailable. Please try again."}),(0,I.jsx)("button",{type:"button",onClick:Br,children:"Retry PayPal"})]}),en?c??(0,I.jsx)("div",{role:"status","data-testid":"flopay-paypal-catalog-loading","aria-label":"Preparing PayPal",style:{height:Ar,borderRadius:8,background:"#e5e7eb",animation:"flopay-loading-pulse 1.5s ease-in-out infinite"},children:(0,I.jsx)("style",{children:"@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})}):Gn!=="exhausted"?(0,I.jsx)("div",{"aria-hidden":Gn==="retrying"?!0:void 0,style:Gn==="retrying"?{position:"relative",height:0,opacity:0,pointerEvents:"none"}:void 0,children:(0,I.jsx)(Wi,{sessionId:G,nonce:R.clientSecret||void 0,billingApiUrl:Q,email:R.customer?.email||At?.account?.email,billingName:[R.customer?.firstName,R.customer?.lastName].filter(Boolean).join(" ")||[At?.account?.firstName,At?.account?.lastName].filter(Boolean).join(" ")||void 0,onBuyerIdentityReady:xe,clientId:Bt.clientId,environment:Bt.environment,currency:(R.currency??"usd").toUpperCase(),isSubscription:R.mode==="subscription",providerObjectType:Bt.providerObjectType,onComplete:y,onErrorChange:qt,onDecline:B,onButtonClick:Re,onInitializationStateChange:wr,allowAutomaticRetry:Sr===0,session:R,telemetry:o,telemetryContext:ot,onInstrument:He,debug:q},`${ke}:paypal-init-${Sr}`)}):null]})}),Ft]}):!V||!$n?(0,I.jsx)(I.Fragment,{children:Ft}):Bn==="confirm"?(0,I.jsxs)(I.Fragment,{children:[(0,I.jsx)(Kn.Provider,{value:gn,children:(0,I.jsx)(Po,{flopay:V,paypalFlopay:A,options:$n,onInstrument:He,children:(0,I.jsxs)("div",{className:J,children:[mn&&(0,I.jsx)("div",{style:{color:"#dc2626",fontSize:"0.875rem",marginBottom:"0.75rem",textAlign:"center"},children:mn}),Ae?Ae({onConfirm:Zt,isProcessing:Jt}):(0,I.jsx)("button",{type:"button",onClick:Zt,disabled:Jt,style:{width:"100%",padding:"0.875rem",backgroundColor:"#4A49FF",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:600,cursor:Jt?"not-allowed":"pointer",opacity:Jt?.6:1},children:Jt?"Processing...":O??"Confirm Purchase"})]})},ke)}),Ft]}):(0,I.jsxs)(I.Fragment,{children:[(0,I.jsx)(Kn.Provider,{value:gn,children:(0,I.jsx)(Po,{flopay:V,paypalFlopay:A,options:$n,onInstrument:He,children:ve?(0,I.jsxs)(I.Fragment,{children:[mn&&(0,I.jsx)("div",{style:{padding:"0.75rem 1rem",marginBottom:"0.75rem",backgroundColor:"#FEF3C7",border:"1px solid #F59E0B",borderRadius:"8px",color:"#92400E",fontSize:"0.875rem"},children:mn}),(0,I.jsx)(jl,{sessionId:G,nonce:R?.clientSecret||void 0,billingApiUrl:Q,session:R,children:ve})]}):(0,I.jsx)(ia,{sessionId:G,nonce:R?.clientSecret||void 0,email:R?.customer?.email||At?.account?.email,userId:R?.customer?.id||At?.account?.userId,firstName:R?.customer?.firstName||At?.account?.firstName,lastName:R?.customer?.lastName||At?.account?.lastName,totalAmount:R?Math.round((0,be.buildCheckoutDisplayData)(R).total*100):0,currency:R?.currency?.toLowerCase()??"usd",onComplete:y,onError:h,onDecline:B,error:mn,onErrorChange:qt,showPayPal:S,showStripe:he,enabledPaymentMethods:U??ee?.data.stripe?.enabledPaymentMethods,enabledPaymentMethodCountries:ee?.data.stripe?.enabledPaymentMethodCountries,showApplePay:w,showGooglePay:ue,layout:ce,theme:H,buttonsTheme:fe,buttonsStyles:$e,appearance:rt,cardButtonContent:Se,cardBackButtonContent:Pt,cardTitleContent:ze,onButtonClick:Re,onBeforeButtonClick:ne,onBuyerIdentityReady:xe,enableAVS:re,...L?{cardFieldOrder:L}:{},...Ee?{cardPreFormSlot:Ee}:{},avsLayout:_e,country:R?.customer?.country,city:R?.customer?.city,state:R?.customer?.state,onCountryChange:M,onZipChange:m,avsCheck:!!re,checkoutType:n?"embedded_checkout":"standard_checkout",checkoutLayout:ve?"custom_layout":ce==="buttons"?"buttons_layout":"default_layout",className:J,directPaypal:Ja(ee),isSubscription:R?.mode==="subscription",session:R,dataAttachmentPending:en,dataAttachmentRequiresIdentity:Nt,debug:q})},ke)}),Ft]})}function jl({sessionId:e,nonce:t,billingApiUrl:n,session:r,children:o}){return(0,I.jsx)(I.Fragment,{children:k.default.Children.map(o,i=>{if(!k.default.isValidElement(i))return i;let d=i.props,c={};return d.sessionId||(c.sessionId=e),!d.nonce&&t&&(c.nonce=t),d.billingApiUrl||(c.billingApiUrl=n),r?.customer&&(d.email||(c.email=r.customer.email),d.userId||(c.userId=r.customer.id),d.firstName||(c.firstName=r.customer.firstName),d.lastName||(c.lastName=r.customer.lastName)),Object.keys(c).length===0?i:k.default.cloneElement(i,c)})})}function Vl({onButtonClick:e,showPayPal:t,showStripe:n=!0,showApplePay:r,showGooglePay:o,theme:i,buttonsTheme:d,buttonsStyles:c,cardButtonContent:P,cardBackButtonContent:y,cardTitleContent:h}){let[v,B]=(0,k.useState)(!1),M=(0,k.useMemo)(()=>(0,be.resolveTheme)(i),[i]),m=(0,k.useMemo)(()=>{let w=M?.buttonsLayout??(0,be.resolveButtonsLayoutTheme)(d);return c?{...w,...c,cardButton:{...w.cardButton,...c.cardButton},cardFormContainer:{...w.cardFormContainer,...c.cardFormContainer},backButton:{...w.backButton,...c.backButton},backButtonIcon:{...w.backButtonIcon,...c.backButtonIcon},submitButton:{...w.submitButton,...c.submitButton},title:{...w.title,...c.title}}:w},[M,d,c]),S=M?.buttonsLayout?.cardButton?.borderRadius??M?.appearance.variables?.borderRadius??8,he=w=>(0,I.jsx)("div",{style:{height:w,borderRadius:S,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}}),U=P===void 0?{boxSizing:"border-box",height:Ar,padding:"0 1rem"}:{padding:"0.9rem 1rem"};if(v){let w=m.cardInputBorder??"#e5e7eb",ue=m.cardInputBackground??"white",q=Or(y),ce=Or(h);return(0,I.jsxs)("div",{style:{backgroundColor:m.cardFormContainer?.backgroundColor??"white",borderRadius:"8px",animation:"flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both",overflow:"hidden",...m.cardFormContainer},children:[(0,I.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"0.75rem 0 0.625rem"},children:[(0,I.jsxs)("button",{type:"button",onClick:()=>B(!1),"aria-label":"Back to payment methods",style:{display:"inline-flex",alignItems:"center",gap:q?0:"0.5rem",background:"none",border:"none",color:"#4b5563",fontSize:"0.85rem",fontWeight:500,padding:0,flexShrink:0,opacity:1,cursor:"pointer",...m.backButton},children:[(0,I.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,borderRadius:"50%",backgroundColor:"#f3f4f6",...m.backButtonIcon},children:(0,I.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,I.jsx)("path",{d:"M15 18l-6-6 6-6"})})}),(0,I.jsx)(Ur,{content:y})]}),ce?(0,I.jsx)("div",{style:{flex:1}}):(0,I.jsx)("div",{style:{flex:1,textAlign:"center",fontWeight:600,fontSize:"1.05rem",color:"#262833",paddingRight:80,...m.title},children:(0,I.jsx)(mo,{content:h})})]}),(0,I.jsx)("div",{style:{backgroundColor:ue,border:`1px solid ${w}`,borderTopLeftRadius:8,borderTopRightRadius:8,padding:12,height:45},children:(0,I.jsx)("div",{style:{width:"60%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,I.jsxs)("div",{style:{display:"flex"},children:[(0,I.jsx)("div",{style:{flex:1,backgroundColor:ue,borderTop:"none",borderRight:"none",borderBottom:`1px solid ${w}`,borderLeft:`1px solid ${w}`,borderBottomLeftRadius:8,padding:12,height:45},children:(0,I.jsx)("div",{style:{width:"50%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,I.jsx)("div",{style:{flex:1,backgroundColor:ue,borderTop:"none",borderRight:`1px solid ${w}`,borderBottom:`1px solid ${w}`,borderLeft:`1px solid ${w}`,borderBottomRightRadius:8,padding:12,height:45},children:(0,I.jsx)("div",{style:{width:"40%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})})]}),(0,I.jsx)("div",{style:{backgroundColor:ue,border:`1px solid ${w}`,borderRadius:8,marginTop:8,padding:12,height:45},children:(0,I.jsx)("div",{style:{width:"45%",height:14,borderRadius:4,background:"#e5e7eb",animation:"flopay-interim-pulse 1.5s ease-in-out infinite"}})}),(0,I.jsx)("div",{style:{height:50,borderRadius:8,marginTop:16,background:"#c8c8ff",animation:"flopay-interim-pulse 1.5s ease-in-out infinite",...m.submitButton,opacity:.5}}),(0,I.jsx)("style",{children:`
|
|
41
41
|
@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }
|
|
42
42
|
@keyframes flopay-interim-expand {
|
|
43
43
|
0% { opacity: 0; max-height: 0; transform: translateY(-12px); }
|
|
44
44
|
40% { opacity: 1; }
|
|
45
45
|
100% { opacity: 1; max-height: 600px; transform: translateY(0); }
|
|
46
46
|
}
|
|
47
|
-
`})]})}return(0,I.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&fe(Ar),n&&(r||o)&&fe(Ar),n&&(0,I.jsx)("button",{type:"button",onClick:()=>{e?.("card"),B(!0)},style:{width:"100%",...U,backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:"8px",fontSize:m.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,...m.cardButton},onMouseDown:w=>{w.currentTarget.style.transform="scale(0.985)"},onMouseUp:w=>{w.currentTarget.style.transform="scale(1)"},children:(0,I.jsx)(zr,{content:P})}),(0,I.jsx)("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}var Yn=require("react/jsx-runtime"),Kl=44;function Ss(e){return new Promise(t=>setTimeout(t,e))}function Hl(e,t){return e instanceof bn.FloPayError?e:new bn.FloPayError(e instanceof Error?e.message:t,"api_error")}function Yl(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function Wl(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 ws({sessionId:e,nonce:t,createSession:n,paymentMethodId:r,checkoutMethod:o,clientId:i,products:d,items:c,subscriptions:P,account:y,successUrl:h,cancelUrl:v,couponCodes:B,tagsData:M,utmMetadata:m,billingApiUrl:S,locale:fe,theme:U,appearance:w,buttonsTheme:ue,buttonsStyles:q,onSuccess:ce,onError:H,onDecline:ge,children:$e,disabled:Se=!1,type:Pt="button",style:ze,...Ie}){let Re=(0,qe.useMemo)(()=>(0,bn.resolveBillingApiUrl)(S),[S]),ne=(0,qe.useMemo)(()=>Wl({createSession:n,clientId:i,products:d,items:c,subscriptions:P,account:y,successUrl:h,cancelUrl:v,couponCodes:B,tagsData:M,utmMetadata:m}),[y,v,i,B,n,d,c,P,h,M,m]),[re,L]=(0,qe.useState)(!1),[Ee,_e]=(0,qe.useState)(null),[J,we]=(0,qe.useState)(null),[ve,T]=(0,qe.useState)(!1),[O,Ae]=(0,qe.useState)(null),ye=(0,qe.useRef)(!0),Q=(0,qe.useRef)(null),Le=(0,qe.useRef)(O),rt=(0,qe.useRef)(ce),ct=(0,qe.useRef)(H),Oe=(0,qe.useRef)(ge);(0,qe.useEffect)(()=>{Le.current=O},[O]),(0,qe.useEffect)(()=>{rt.current=ce},[ce]),(0,qe.useEffect)(()=>{ct.current=H},[H]),(0,qe.useEffect)(()=>{Oe.current=ge},[ge]),(0,qe.useEffect)(()=>(ye.current=!0,()=>{ye.current=!1,Q.current?.abort()}),[]),(0,qe.useEffect)(()=>{if(typeof window>"u")return;let C=te=>{te.key==="Escape"&&Ae(null)};return window.addEventListener("keydown",C),()=>{window.removeEventListener("keydown",C)}},[]);let ee=(0,qe.useCallback)((C,te=So)=>{Oe.current?.(jt(te,C,{code:C.code,declineCode:C.declineCode}))},[]),W=(0,qe.useCallback)(async C=>{ye.current&&(we(null),T(C.result.status==="authorized"),_e("success"),await Ss(1200),ye.current&&et(()=>rt.current?.(C)))},[]),V=(0,qe.useCallback)(async(C,te)=>{ye.current&&(ct.current?.(C),te?.emitDecline&&ee(C,te.method),we(C.message),T(!1),_e("error"),await Ss(1500))},[ee]),Be=(0,qe.useCallback)(async(C,te,Xe)=>{let He=C.data.session??null;if(!He)throw new bn.FloPayError("No session data returned","api_error");let zt=He.clientSecret||t;if($r(He)){await W({result:Er(He,te),session:He,sessionId:He.id||te,autoCompleted:!1});return}if(He.status==="expired")throw jo(He);try{if(C.autoProcessingPending){let Qt=(await new ua.PaymentAPI(Re).waitForCheckoutSessionCompletion(C.autoProcessingPending.sessionId,{initialDelayMs:C.autoProcessingPending.retryAfterMs})).data.session;if(!$r(Qt))throw Vo(Qt);await W({result:Er(Qt,te),session:Qt,sessionId:Qt.id||te,autoCompleted:!1});return}if(C.autoProcessingError){if(C.autoProcessingError.type==="3ds_required"&&C.autoProcessingError.nextActionRedirectUrl&&te&&zt){let G=new AbortController;Q.current=G;let dt;try{dt=await Zi({billingApiUrl:Re,sessionId:te,nonce:zt,nextActionRedirectUrl:C.autoProcessingError.nextActionRedirectUrl,signal:G.signal})}finally{Q.current===G&&(Q.current=null)}if(dt.status==="declined")throw Pr({type:dt.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:dt.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:C.autoProcessingError.checkoutMethod});let Ut=(await new ua.PaymentAPI(Re).waitForCheckoutSessionCompletion(te,{initialDelayMs:0,nonce:zt})).data.session;if(!$r(Ut))throw Pr({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:C.autoProcessingError.checkoutMethod});await W({result:Er(Ut,te),session:Ut,sessionId:Ut.id||te,autoCompleted:!1});return}throw Pr(C.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:C.autoProcessingError.checkoutMethod})}if(Xe?.fromCreateSession&&C.autoProcessingAttempted===!0)throw Pr({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let Lt=await Jr({billingApiUrl:Re,sessionId:te??He.id,session:He,nonce:zt});if(Lt.type!=="success")throw Pr({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await W({result:Lt.result,session:He,sessionId:He.id||te,autoCompleted:!1})}catch(Lt){let G=wo(Lt),dt=He.id||te;await V(G,{emitDecline:!0,method:G.checkoutMethod??So}),Yl(G,dt)&&dt&&ye.current&&Ae({sessionId:dt,errorMessage:G.message,nonce:zt||void 0})}},[t,Re,V,W]),Je=(0,qe.useCallback)(async C=>{if(Ie.onClick?.(C),!(C.defaultPrevented||Se||re)){if(Ae(null),e&&ne){let te=new bn.FloPayError("Provide either sessionId or create-session props, not both.","validation_error");await V(te),ye.current&&(_e(null),we(null));return}if(!e&&!ne){let te=new bn.FloPayError("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await V(te),ye.current&&(_e(null),we(null));return}L(!0),we(null),T(!1),_e("processing");try{let te=new ua.PaymentAPI(Re);if(e){let Xe=await te.getUnifiedCheckoutSession(e,t);await Be(Xe,e);return}try{let Xe=await te.createAndFetchSession({...ne});await Be(Xe,Xe.data.session?.id??null,{fromCreateSession:!0})}catch(Xe){if((Xe instanceof bn.FloPayError||typeof Xe=="object"&&Xe!==null&&"code"in Xe?Xe.code:void 0)==="session_auto_completed"){await W({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw Xe}}catch(te){await V(Hl(te,"Automatic payment failed. Please try again."))}finally{ye.current&&(_e(null),we(null),L(!1))}}},[Ie.onClick,ne,Se,re,t,Be,Re,e,V,W]),A=(0,qe.useCallback)(C=>{let te=Le.current;Ae(null),rt.current?.({result:C,session:null,sessionId:te?.sessionId??null,autoCompleted:!1})},[]),oe=(0,qe.useCallback)(C=>{ct.current?.(C)},[]),F=(0,qe.useCallback)(C=>{Oe.current?.(C)},[]),R=(0,qe.useMemo)(()=>(0,bn.resolveTheme)(U),[U]),at=(0,qe.useMemo)(()=>{let C=R?.buttonsLayout??(0,bn.resolveButtonsLayoutTheme)(ue);return q?{...C,...q,cardButton:{...C.cardButton,...q.cardButton}}:C},[R,ue,q]),Ct=(0,qe.useMemo)(()=>{let C=R?.appearance;return w?C?{...C,...w,variables:{...C.variables,...w.variables}}:w:C},[w,R]),ke=Ct?.variables,pt=ke?.colorPrimary??"#4A49FF",Fe=ke?.colorPrimaryHover??Zr(pt,.12),mt=ke?.borderRadius??"8px";return(0,Yn.jsxs)(Yn.Fragment,{children:[(0,Yn.jsx)("button",{...Ie,type:Pt,onClick:Je,disabled:Se||re,"aria-busy":re,style:{width:"100%",...$e===void 0?{boxSizing:"border-box",height:Kl,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...at.cardButton,...$a({themeBundle:R,resolvedPrimaryColor:pt,resolvedBorderRadius:mt,submitButtonStyle:at.submitButton,explicitPrimaryColor:ke?.colorPrimary}),fontSize:at.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:Se||re?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",transition:"background-color 0.15s, border-color 0.2s, box-shadow 0.2s, transform 0.1s",position:"relative",opacity:Se||re?.6:1,...ze},onMouseEnter:C=>{Ie.onMouseEnter?.(C),!C.defaultPrevented&&!Se&&!re&&(R||ke?.colorPrimary)&&(C.currentTarget.style.backgroundColor=Fe)},onMouseLeave:C=>{Ie.onMouseLeave?.(C),!C.defaultPrevented&&(R||ke?.colorPrimary)&&(C.currentTarget.style.backgroundColor=pt)},onMouseDown:C=>{Ie.onMouseDown?.(C),C.defaultPrevented||(C.currentTarget.style.transform="scale(0.985)")},onMouseUp:C=>{Ie.onMouseUp?.(C),C.defaultPrevented||(C.currentTarget.style.transform="scale(1)")},children:(0,Yn.jsx)(zr,{content:$e})}),Ee&&(0,Yn.jsx)(Tn,{status:Ee,errorMessage:J,authorized:ve}),O&&(0,Yn.jsx)("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:C=>{C.target===C.currentTarget&&Ae(null)},style:{position:"fixed",inset:0,background:"rgba(0, 0, 0, 0.45)",display:"flex",alignItems:"center",justifyContent:"center",padding:"1.5rem",zIndex:1100},children:(0,Yn.jsx)("div",{style:{width:"100%",maxWidth:520,maxHeight:"90vh",overflowY:"auto",background:"white",borderRadius:20,padding:"1.5rem",boxShadow:"0 24px 80px rgba(15, 23, 42, 0.28)",display:"flex",flexDirection:"column",gap:"1rem"},children:(0,Yn.jsx)(da,{sessionId:O.sessionId,nonce:O.nonce,checkoutMode:"full",billingApiUrl:Re,locale:fe,theme:U,...Ct?{appearance:Ct}:{},buttonsTheme:ue,buttonsStyles:q,initialErrorMessage:O.errorMessage,cardTitleContent:null,onComplete:A,onError:oe,onDecline:F})})})]})}var pa=require("@flopay/js/card-setup"),vn=require("@flopay/shared"),vt=require("react");var nr=require("react/jsx-runtime"),_o=class extends vn.FloPayError{constructor(t,n,r){super(t,n,r),this.name="FloPayCardSetupError",this.retryable=r.retryable}};function ks(e,t={}){let n=e instanceof vn.FloPayError?e:void 0,r=n?.statusCode,o=t.retryable??(n?.type==="network_error"||n?.type==="rate_limit_error"||typeof r=="number"&&r>=500||n?.code==="vault_capture_timeout"||!n);return new _o(n?.message??(e instanceof Error?e.message:"Failed to load the secure card form."),n?.type??"api_error",{code:t.code??n?.code??"card_setup_load_failed",retryable:o,...n?.param?{param:n.param}:{},...r!==void 0?{statusCode:r}:{}})}function Is({sessionId:e,nonce:t,billingApiUrl:n,telemetry:r,theme:o="modern-light",containerStyle:i,loading:d=null,onReady:c,onComplete:P,onDecline:y,onCancel:h,onValidation:v,onError:B}){let[M,m]=(0,vt.useState)(null),[S,fe]=(0,vt.useState)(null),[U,w]=(0,vt.useState)(null),[ue,q]=(0,vt.useState)(null),[ce,H]=(0,vt.useState)(null),ge=(0,vt.useRef)(!1),$e=(0,vt.useRef)(!1),Se=(0,vt.useMemo)(()=>{if(typeof o=="object")return o;let J=(0,vn.resolveTheme)(o);if(J)return na({appearance:J.appearance,buttonsStyles:J.buttonsLayout,layout:"default"})},[o]),Pt=(0,vt.useRef)(c),ze=(0,vt.useRef)(B),Ie=(0,vt.useRef)(P),Re=(0,vt.useRef)(y),ne=(0,vt.useRef)(h),re=(0,vt.useRef)(v),L=(0,vt.useRef)(!1),Ee=(0,vt.useRef)(!1),_e=(0,vt.useRef)(0);return Pt.current=c,ze.current=B,Ie.current=P,Re.current=y,ne.current=h,re.current=v,(0,vt.useEffect)(()=>{let J=_e.current+1;return _e.current=J,()=>{queueMicrotask(()=>{_e.current===J&&(L.current||Ee.current||(Ee.current=!0,et(()=>{ne.current?.({status:"cancelled",sessionId:e})})))})}},[e]),(0,vt.useEffect)(()=>{let J=!0,we=new pa.PaymentAPI((0,vn.resolveBillingApiUrl)(n),{telemetry:r});return m(null),fe(null),w(null),L.current=!1,Ee.current=!1,(async()=>{try{if(!e.trim())throw new vn.FloPayError("FloPayCardSetup requires a sessionId.","validation_error",{code:"MissingCheckoutSessionId",param:"sessionId"});if(!t.trim())throw new vn.FloPayError("FloPayCardSetup requires a session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let ve=await we.getUnifiedCheckoutSession(e,t);if(!J)return;let T=ve.data.session;if(!T||!(0,vn.isCardSetupCheckoutSession)(T))throw new vn.FloPayError("FloPayCardSetup only accepts a zero-amount, productless setup session.","validation_error",{code:"InvalidCardSetupSession",param:"sessionId"});let O=T.vault;if(O?.html?.trim()||(O=await we.getVaultCapture(e,t)),!O.html?.trim())throw new vn.FloPayError("FloPay: this setup session has no vault card capability. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});if(!J)return;fe(O),m(new pa.PciVaultCardCapture({sessionId:e,operation:"card_setup",telemetry:r}))}catch(ve){if(!J)return;let T=ks(ve);L.current=!0,w(T),et(()=>ze.current?.(T))}})(),()=>{J=!1,we.destroy()}},[n,t,e,r]),(0,vt.useEffect)(()=>{if(!M)return;let J=!1;$e.current=!1,ge.current=!1;let we=M.on("submitting",()=>{ge.current=!0,H(null),q("processing")}),ve=M.on("complete",O=>{L.current=!0,ge.current=!1,q("success"),(async()=>(await new Promise(Ae=>setTimeout(Ae,1200)),!$e.current&&($e.current=!0,et(()=>{Ie.current?.({status:"succeeded",sessionId:e,...O.paymentMethod?{paymentMethod:O.paymentMethod}:{}})}),J||q(null))))()}),T=M.on("decline",O=>{L.current=!0,ge.current=!1,H(O.message??null),q("error"),et(()=>{Re.current?.({status:"declined",sessionId:e,...O.declineReason?{reason:O.declineReason}:{},...O.message?{message:O.message}:{}})}),(async()=>(await new Promise(Ae=>setTimeout(Ae,1500)),J||q(null)))()});return()=>{J=!0,we(),ve(),T()}},[M,e]),U?(0,nr.jsx)("div",{role:"alert",children:U.message}):!M||!S?.html?(0,nr.jsx)(nr.Fragment,{children:d}):(0,nr.jsxs)(nr.Fragment,{children:[ue&&(0,nr.jsx)(Tn,{status:ue,errorMessage:ce,processingLabel:"SAVING CARD...",successLabel:"CARD SAVED",errorLabel:"CARD NOT SAVED",successNote:null}),(0,nr.jsx)(Xr,{capture:M,html:S.html,messageToken:S.messageToken,expectedOrigin:S.expectedOrigin,theme:Se,containerStyle:i,onReady:()=>{et(()=>Pt.current?.())},onValidation:J=>{et(()=>re.current?.(J))},onError:J=>{if(!J)return;ge.current&&(ge.current=!1,H(J),q("error"),setTimeout(()=>q(null),1500));let we=ks(new Error(J),{code:"card_setup_widget_failed",retryable:!0});et(()=>ze.current?.(we))}})]})}0&&(module.exports={DirectPayPalButton,FloPayAutomaticPaymentButton,FloPayCardSetup,FloPayCardSetupError,FloPayCheckout,FloPayProvider,SplitCardForm,VaultCardFields,dropThirdPartyOnlyError,useCheckout,useFloPay,usePayPalFloPay});
|
|
47
|
+
`})]})}return(0,I.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[t&&he(Ar),n&&(r||o)&&he(Ar),n&&(0,I.jsx)("button",{type:"button",onClick:()=>{e?.("card"),B(!0)},style:{width:"100%",...U,backgroundColor:"white",color:"#262833",border:"1px solid #d1d5db",borderRadius:"8px",fontSize:m.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,...m.cardButton},onMouseDown:w=>{w.currentTarget.style.transform="scale(0.985)"},onMouseUp:w=>{w.currentTarget.style.transform="scale(1)"},children:(0,I.jsx)(zr,{content:P})}),(0,I.jsx)("style",{children:"@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }"})]})}var Yn=require("react/jsx-runtime"),Kl=44;function Ss(e){return new Promise(t=>setTimeout(t,e))}function Hl(e,t){return e instanceof bn.FloPayError?e:new bn.FloPayError(e instanceof Error?e.message:t,"api_error")}function Yl(e,t){return!(!t||e.type==="validation_error"||e.checkoutMethod&&e.checkoutMethod!=="card"&&e.checkoutMethod!=="paypal")}function Wl(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 ws({sessionId:e,nonce:t,createSession:n,paymentMethodId:r,checkoutMethod:o,clientId:i,products:d,items:c,subscriptions:P,account:y,successUrl:h,cancelUrl:v,couponCodes:B,tagsData:M,utmMetadata:m,billingApiUrl:S,locale:he,theme:U,appearance:w,buttonsTheme:ue,buttonsStyles:q,onSuccess:ce,onError:H,onDecline:fe,children:$e,disabled:Se=!1,type:Pt="button",style:ze,...Ie}){let Re=(0,qe.useMemo)(()=>(0,bn.resolveBillingApiUrl)(S),[S]),ne=(0,qe.useMemo)(()=>Wl({createSession:n,clientId:i,products:d,items:c,subscriptions:P,account:y,successUrl:h,cancelUrl:v,couponCodes:B,tagsData:M,utmMetadata:m}),[y,v,i,B,n,d,c,P,h,M,m]),[re,L]=(0,qe.useState)(!1),[Ee,_e]=(0,qe.useState)(null),[J,we]=(0,qe.useState)(null),[ve,T]=(0,qe.useState)(!1),[O,Ae]=(0,qe.useState)(null),ye=(0,qe.useRef)(!0),Q=(0,qe.useRef)(null),Le=(0,qe.useRef)(O),rt=(0,qe.useRef)(ce),ct=(0,qe.useRef)(H),Oe=(0,qe.useRef)(fe);(0,qe.useEffect)(()=>{Le.current=O},[O]),(0,qe.useEffect)(()=>{rt.current=ce},[ce]),(0,qe.useEffect)(()=>{ct.current=H},[H]),(0,qe.useEffect)(()=>{Oe.current=fe},[fe]),(0,qe.useEffect)(()=>(ye.current=!0,()=>{ye.current=!1,Q.current?.abort()}),[]),(0,qe.useEffect)(()=>{if(typeof window>"u")return;let C=te=>{te.key==="Escape"&&Ae(null)};return window.addEventListener("keydown",C),()=>{window.removeEventListener("keydown",C)}},[]);let ee=(0,qe.useCallback)((C,te=So)=>{Oe.current?.(jt(te,C,{code:C.code,declineCode:C.declineCode}))},[]),W=(0,qe.useCallback)(async C=>{ye.current&&(we(null),T(C.result.status==="authorized"),_e("success"),await Ss(1200),ye.current&&et(()=>rt.current?.(C)))},[]),V=(0,qe.useCallback)(async(C,te)=>{ye.current&&(ct.current?.(C),te?.emitDecline&&ee(C,te.method),we(C.message),T(!1),_e("error"),await Ss(1500))},[ee]),Be=(0,qe.useCallback)(async(C,te,Xe)=>{let He=C.data.session??null;if(!He)throw new bn.FloPayError("No session data returned","api_error");let zt=He.clientSecret||t;if($r(He)){await W({result:Er(He,te),session:He,sessionId:He.id||te,autoCompleted:!1});return}if(He.status==="expired")throw jo(He);try{if(C.autoProcessingPending){let Qt=(await new ua.PaymentAPI(Re).waitForCheckoutSessionCompletion(C.autoProcessingPending.sessionId,{initialDelayMs:C.autoProcessingPending.retryAfterMs})).data.session;if(!$r(Qt))throw Vo(Qt);await W({result:Er(Qt,te),session:Qt,sessionId:Qt.id||te,autoCompleted:!1});return}if(C.autoProcessingError){if(C.autoProcessingError.type==="3ds_required"&&C.autoProcessingError.nextActionRedirectUrl&&te&&zt){let G=new AbortController;Q.current=G;let dt;try{dt=await Zi({billingApiUrl:Re,sessionId:te,nonce:zt,nextActionRedirectUrl:C.autoProcessingError.nextActionRedirectUrl,signal:G.signal})}finally{Q.current===G&&(Q.current=null)}if(dt.status==="declined")throw Pr({type:dt.declineReason??"decline",message:"Card was declined.",gatewayErrorCode:dt.gatewayDeclineReason??void 0},"Card was declined.",{checkoutMethod:C.autoProcessingError.checkoutMethod});let Ut=(await new ua.PaymentAPI(Re).waitForCheckoutSessionCompletion(te,{initialDelayMs:0,nonce:zt})).data.session;if(!$r(Ut))throw Pr({type:"unknown",message:"Card authentication was not completed."},"Card authentication was not completed.",{checkoutMethod:C.autoProcessingError.checkoutMethod});await W({result:Er(Ut,te),session:Ut,sessionId:Ut.id||te,autoCompleted:!1});return}throw Pr(C.autoProcessingError,"Automatic payment failed. Please try again.",{checkoutMethod:C.autoProcessingError.checkoutMethod})}if(Xe?.fromCreateSession&&C.autoProcessingAttempted===!0)throw Pr({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");let Lt=await Jr({billingApiUrl:Re,sessionId:te??He.id,session:He,nonce:zt});if(Lt.type!=="success")throw Pr({type:"unknown",message:"Automatic payment failed. Please try again."},"Automatic payment failed. Please try again.");await W({result:Lt.result,session:He,sessionId:He.id||te,autoCompleted:!1})}catch(Lt){let G=wo(Lt),dt=He.id||te;await V(G,{emitDecline:!0,method:G.checkoutMethod??So}),Yl(G,dt)&&dt&&ye.current&&Ae({sessionId:dt,errorMessage:G.message,nonce:zt||void 0})}},[t,Re,V,W]),Je=(0,qe.useCallback)(async C=>{if(Ie.onClick?.(C),!(C.defaultPrevented||Se||re)){if(Ae(null),e&&ne){let te=new bn.FloPayError("Provide either sessionId or create-session props, not both.","validation_error");await V(te),ye.current&&(_e(null),we(null));return}if(!e&&!ne){let te=new bn.FloPayError("Provide a sessionId or the props required to create an automatic payment session.","validation_error");await V(te),ye.current&&(_e(null),we(null));return}L(!0),we(null),T(!1),_e("processing");try{let te=new ua.PaymentAPI(Re);if(e){let Xe=await te.getUnifiedCheckoutSession(e,t);await Be(Xe,e);return}try{let Xe=await te.createAndFetchSession({...ne});await Be(Xe,Xe.data.session?.id??null,{fromCreateSession:!0})}catch(Xe){if((Xe instanceof bn.FloPayError||typeof Xe=="object"&&Xe!==null&&"code"in Xe?Xe.code:void 0)==="session_auto_completed"){await W({result:{status:"succeeded"},session:null,sessionId:null,autoCompleted:!0});return}throw Xe}}catch(te){await V(Hl(te,"Automatic payment failed. Please try again."))}finally{ye.current&&(_e(null),we(null),L(!1))}}},[Ie.onClick,ne,Se,re,t,Be,Re,e,V,W]),A=(0,qe.useCallback)(C=>{let te=Le.current;Ae(null),rt.current?.({result:C,session:null,sessionId:te?.sessionId??null,autoCompleted:!1})},[]),oe=(0,qe.useCallback)(C=>{ct.current?.(C)},[]),F=(0,qe.useCallback)(C=>{Oe.current?.(C)},[]),R=(0,qe.useMemo)(()=>(0,bn.resolveTheme)(U),[U]),at=(0,qe.useMemo)(()=>{let C=R?.buttonsLayout??(0,bn.resolveButtonsLayoutTheme)(ue);return q?{...C,...q,cardButton:{...C.cardButton,...q.cardButton}}:C},[R,ue,q]),Ct=(0,qe.useMemo)(()=>{let C=R?.appearance;return w?C?{...C,...w,variables:{...C.variables,...w.variables}}:w:C},[w,R]),ke=Ct?.variables,pt=ke?.colorPrimary??"#4A49FF",Fe=ke?.colorPrimaryHover??Zr(pt,.12),mt=ke?.borderRadius??"8px";return(0,Yn.jsxs)(Yn.Fragment,{children:[(0,Yn.jsx)("button",{...Ie,type:Pt,onClick:Je,disabled:Se||re,"aria-busy":re,style:{width:"100%",...$e===void 0?{boxSizing:"border-box",height:Kl,padding:"0 1rem"}:{padding:"0.9rem 1rem"},...at.cardButton,...$a({themeBundle:R,resolvedPrimaryColor:pt,resolvedBorderRadius:mt,submitButtonStyle:at.submitButton,explicitPrimaryColor:ke?.colorPrimary}),fontSize:at.cardButtonFontSize??"0.95rem",fontWeight:600,cursor:Se||re?"not-allowed":"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.625rem",transition:"background-color 0.15s, border-color 0.2s, box-shadow 0.2s, transform 0.1s",position:"relative",opacity:Se||re?.6:1,...ze},onMouseEnter:C=>{Ie.onMouseEnter?.(C),!C.defaultPrevented&&!Se&&!re&&(R||ke?.colorPrimary)&&(C.currentTarget.style.backgroundColor=Fe)},onMouseLeave:C=>{Ie.onMouseLeave?.(C),!C.defaultPrevented&&(R||ke?.colorPrimary)&&(C.currentTarget.style.backgroundColor=pt)},onMouseDown:C=>{Ie.onMouseDown?.(C),C.defaultPrevented||(C.currentTarget.style.transform="scale(0.985)")},onMouseUp:C=>{Ie.onMouseUp?.(C),C.defaultPrevented||(C.currentTarget.style.transform="scale(1)")},children:(0,Yn.jsx)(zr,{content:$e})}),Ee&&(0,Yn.jsx)(Tn,{status:Ee,errorMessage:J,authorized:ve}),O&&(0,Yn.jsx)("div",{"data-testid":"flopay-automatic-payment-fallback",role:"dialog","aria-modal":"true",onClick:C=>{C.target===C.currentTarget&&Ae(null)},style:{position:"fixed",inset:0,background:"rgba(0, 0, 0, 0.45)",display:"flex",alignItems:"center",justifyContent:"center",padding:"1.5rem",zIndex:1100},children:(0,Yn.jsx)("div",{style:{width:"100%",maxWidth:520,maxHeight:"90vh",overflowY:"auto",background:"white",borderRadius:20,padding:"1.5rem",boxShadow:"0 24px 80px rgba(15, 23, 42, 0.28)",display:"flex",flexDirection:"column",gap:"1rem"},children:(0,Yn.jsx)(da,{sessionId:O.sessionId,nonce:O.nonce,checkoutMode:"full",billingApiUrl:Re,locale:he,theme:U,...Ct?{appearance:Ct}:{},buttonsTheme:ue,buttonsStyles:q,initialErrorMessage:O.errorMessage,cardTitleContent:null,onComplete:A,onError:oe,onDecline:F})})})]})}var pa=require("@flopay/js/card-setup"),vn=require("@flopay/shared"),vt=require("react");var nr=require("react/jsx-runtime"),_o=class extends vn.FloPayError{constructor(t,n,r){super(t,n,r),this.name="FloPayCardSetupError",this.retryable=r.retryable}};function ks(e,t={}){let n=e instanceof vn.FloPayError?e:void 0,r=n?.statusCode,o=t.retryable??(n?.type==="network_error"||n?.type==="rate_limit_error"||typeof r=="number"&&r>=500||n?.code==="vault_capture_timeout"||!n);return new _o(n?.message??(e instanceof Error?e.message:"Failed to load the secure card form."),n?.type??"api_error",{code:t.code??n?.code??"card_setup_load_failed",retryable:o,...n?.param?{param:n.param}:{},...r!==void 0?{statusCode:r}:{}})}function Is({sessionId:e,nonce:t,billingApiUrl:n,telemetry:r,theme:o="modern-light",containerStyle:i,loading:d=null,onReady:c,onComplete:P,onDecline:y,onCancel:h,onValidation:v,onError:B}){let[M,m]=(0,vt.useState)(null),[S,he]=(0,vt.useState)(null),[U,w]=(0,vt.useState)(null),[ue,q]=(0,vt.useState)(null),[ce,H]=(0,vt.useState)(null),fe=(0,vt.useRef)(!1),$e=(0,vt.useRef)(!1),Se=(0,vt.useMemo)(()=>{if(typeof o=="object")return o;let J=(0,vn.resolveTheme)(o);if(J)return na({appearance:J.appearance,buttonsStyles:J.buttonsLayout,layout:"default"})},[o]),Pt=(0,vt.useRef)(c),ze=(0,vt.useRef)(B),Ie=(0,vt.useRef)(P),Re=(0,vt.useRef)(y),ne=(0,vt.useRef)(h),re=(0,vt.useRef)(v),L=(0,vt.useRef)(!1),Ee=(0,vt.useRef)(!1),_e=(0,vt.useRef)(0);return Pt.current=c,ze.current=B,Ie.current=P,Re.current=y,ne.current=h,re.current=v,(0,vt.useEffect)(()=>{let J=_e.current+1;return _e.current=J,()=>{queueMicrotask(()=>{_e.current===J&&(L.current||Ee.current||(Ee.current=!0,et(()=>{ne.current?.({status:"cancelled",sessionId:e})})))})}},[e]),(0,vt.useEffect)(()=>{let J=!0,we=new pa.PaymentAPI((0,vn.resolveBillingApiUrl)(n),{telemetry:r});return m(null),he(null),w(null),L.current=!1,Ee.current=!1,(async()=>{try{if(!e.trim())throw new vn.FloPayError("FloPayCardSetup requires a sessionId.","validation_error",{code:"MissingCheckoutSessionId",param:"sessionId"});if(!t.trim())throw new vn.FloPayError("FloPayCardSetup requires a session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let ve=await we.getUnifiedCheckoutSession(e,t);if(!J)return;let T=ve.data.session;if(!T||!(0,vn.isCardSetupCheckoutSession)(T))throw new vn.FloPayError("FloPayCardSetup only accepts a zero-amount, productless setup session.","validation_error",{code:"InvalidCardSetupSession",param:"sessionId"});let O=T.vault;if(O?.html?.trim()||(O=await we.getVaultCapture(e,t)),!O.html?.trim())throw new vn.FloPayError("FloPay: this setup session has no vault card capability. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});if(!J)return;he(O),m(new pa.PciVaultCardCapture({sessionId:e,operation:"card_setup",telemetry:r}))}catch(ve){if(!J)return;let T=ks(ve);L.current=!0,w(T),et(()=>ze.current?.(T))}})(),()=>{J=!1,we.destroy()}},[n,t,e,r]),(0,vt.useEffect)(()=>{if(!M)return;let J=!1;$e.current=!1,fe.current=!1;let we=M.on("submitting",()=>{fe.current=!0,H(null),q("processing")}),ve=M.on("complete",O=>{L.current=!0,fe.current=!1,q("success"),(async()=>(await new Promise(Ae=>setTimeout(Ae,1200)),!$e.current&&($e.current=!0,et(()=>{Ie.current?.({status:"succeeded",sessionId:e,...O.paymentMethod?{paymentMethod:O.paymentMethod}:{}})}),J||q(null))))()}),T=M.on("decline",O=>{L.current=!0,fe.current=!1,H(O.message??null),q("error"),et(()=>{Re.current?.({status:"declined",sessionId:e,...O.declineReason?{reason:O.declineReason}:{},...O.message?{message:O.message}:{}})}),(async()=>(await new Promise(Ae=>setTimeout(Ae,1500)),J||q(null)))()});return()=>{J=!0,we(),ve(),T()}},[M,e]),U?(0,nr.jsx)("div",{role:"alert",children:U.message}):!M||!S?.html?(0,nr.jsx)(nr.Fragment,{children:d}):(0,nr.jsxs)(nr.Fragment,{children:[ue&&(0,nr.jsx)(Tn,{status:ue,errorMessage:ce,processingLabel:"SAVING CARD...",successLabel:"CARD SAVED",errorLabel:"CARD NOT SAVED",successNote:null}),(0,nr.jsx)(Xr,{capture:M,html:S.html,messageToken:S.messageToken,expectedOrigin:S.expectedOrigin,theme:Se,containerStyle:i,onReady:()=>{et(()=>Pt.current?.())},onValidation:J=>{et(()=>re.current?.(J))},onError:J=>{if(!J)return;fe.current&&(fe.current=!1,H(J),q("error"),setTimeout(()=>q(null),1500));let we=ks(new Error(J),{code:"card_setup_widget_failed",retryable:!0});et(()=>ze.current?.(we))}})]})}0&&(module.exports={DirectPayPalButton,FloPayAutomaticPaymentButton,FloPayCardSetup,FloPayCardSetupError,FloPayCheckout,FloPayProvider,SplitCardForm,VaultCardFields,dropThirdPartyOnlyError,useCheckout,useFloPay,usePayPalFloPay});
|