@flopay/react 0.5.17 → 0.5.19
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 +446 -537
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1 -62
- package/dist/index.d.ts +1 -62
- package/dist/index.mjs +391 -480
- package/dist/index.mjs.map +1 -1
- package/package.json +3 -3
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/provider.tsx","../src/context.ts","../src/flopay-checkout.tsx","../src/card-button-content.tsx","../src/elements.tsx","../src/split-card-form.tsx","../src/hooks.ts","../src/processing-overlay.tsx","../src/checkout-utils.ts","../src/recent-completion.ts","../src/in-app-browser-notice.tsx","../src/in-app-browser.ts","../src/saved-payment-flow.ts","../src/checkout-form.tsx","../src/paypal-button.tsx","../src/automatic-payment-button.tsx"],"sourcesContent":["import React, { useEffect, useState, useMemo } from 'react';\nimport type { FloPay, FloPayElements } from '@flopay/js';\nimport type { FloPayAppearance } from '@flopay/shared';\nimport { resolveBillingApiUrl } from '@flopay/shared';\nimport { FloPayContext } from './context.js';\n\n/** Props for the `FloPayProvider` component. */\nexport interface FloPayProviderProps {\n /** A `FloPay` instance or a promise that resolves to one (from `loadFloPay()`). */\n flopay: Promise<FloPay> | FloPay;\n /**\n * Optional dedicated `FloPay` instance for PayPal, loaded with\n * `gatewayData.paypalPublishableKey`. When omitted or `null`, PayPal is\n * disabled (the button is not rendered).\n */\n paypalFlopay?: Promise<FloPay> | FloPay | null;\n /** Optional configuration applied when creating the elements group. */\n options?: {\n locale?: string;\n appearance?: FloPayAppearance;\n clientSecret?: string;\n /** Total amount in smallest currency unit (cents). Used when no clientSecret. */\n amount?: number;\n /** ISO 4217 currency code (lowercase). Used when no clientSecret. */\n currency?: string;\n /** How payment methods are created. 'manual' (default for cards) or 'auto' (needed for PayPal). */\n paymentMethodCreation?: 'manual' | 'auto';\n /** Requests reusable payment credentials for future payments. */\n setupFutureUsage?: 'off_session' | 'on_session';\n /** Billing API base URL. Set once here so child components don't need to repeat it. */\n billingApiUrl?: string;\n };\n children: React.ReactNode;\n}\n\n/**\n * Provides FloPay SDK context to the component tree.\n *\n * Wrap your checkout page (or your entire app) with this provider:\n *\n * ```tsx\n * <FloPayProvider flopay={loadFloPay('pk_test_...')}>\n * <CheckoutForm />\n * </FloPayProvider>\n * ```\n */\nexport function FloPayProvider({\n flopay: floPayProp,\n paypalFlopay: paypalFloPayProp,\n options,\n children,\n}: FloPayProviderProps): React.ReactElement {\n const [flopay, setFloPay] = useState<FloPay | null>(\n floPayProp instanceof Promise ? null : floPayProp,\n );\n const [paypalFlopay, setPaypalFloPay] = useState<FloPay | null>(\n paypalFloPayProp instanceof Promise || !paypalFloPayProp ? null : paypalFloPayProp,\n );\n const [elements, setElements] = useState<FloPayElements | null>(null);\n\n // Resolve the promise if needed\n useEffect(() => {\n let cancelled = false;\n\n if (floPayProp instanceof Promise) {\n floPayProp.then((instance) => {\n if (!cancelled) {\n setFloPay(instance);\n }\n });\n } else {\n setFloPay(floPayProp);\n }\n\n return () => {\n cancelled = true;\n };\n }, [floPayProp]);\n\n // Resolve the PayPal promise / prop\n useEffect(() => {\n let cancelled = false;\n\n if (!paypalFloPayProp) {\n setPaypalFloPay(null);\n return;\n }\n\n if (paypalFloPayProp instanceof Promise) {\n paypalFloPayProp.then((instance) => {\n if (!cancelled) {\n setPaypalFloPay(instance);\n }\n });\n } else {\n setPaypalFloPay(paypalFloPayProp);\n }\n\n return () => {\n cancelled = true;\n };\n }, [paypalFloPayProp]);\n\n // Create elements group once FloPay is ready\n useEffect(() => {\n if (!flopay) {\n setElements(null);\n return;\n }\n\n const els = flopay.elements({\n appearance: options?.appearance,\n clientSecret: options?.clientSecret,\n amount: options?.amount,\n currency: options?.currency,\n paymentMethodCreation: options?.paymentMethodCreation,\n setupFutureUsage: options?.setupFutureUsage,\n });\n setElements(els);\n\n return () => {\n els.destroy();\n };\n }, [\n flopay,\n options?.appearance,\n options?.clientSecret,\n options?.amount,\n options?.currency,\n options?.paymentMethodCreation,\n options?.setupFutureUsage,\n ]);\n\n const resolvedBillingApiUrl = resolveBillingApiUrl(options?.billingApiUrl);\n\n const value = useMemo(\n () => ({ flopay, paypalFlopay, elements, billingApiUrl: resolvedBillingApiUrl }),\n [flopay, paypalFlopay, elements, resolvedBillingApiUrl],\n );\n\n return (\n <FloPayContext.Provider value={value}>\n {children}\n </FloPayContext.Provider>\n );\n}\n","import { createContext } from 'react';\nimport type { FloPay, FloPayElements } from '@flopay/js';\nimport type {\n CheckoutMode,\n CheckoutSession,\n FloPayError,\n InlineSessionDraft,\n InlineSessionPatch,\n} from '@flopay/shared';\n\n/** Internal context value for the FloPay provider. */\nexport interface FloPayContextValue {\n flopay: FloPay | null;\n /**\n * Dedicated FloPay instance for PayPal, loaded with `gatewayData.paypalPublishableKey`.\n * `null` or absent means PayPal is disabled for the current session.\n */\n paypalFlopay?: FloPay | null;\n elements: FloPayElements | null;\n billingApiUrl: string;\n}\n\n/** Internal context value for checkout state. */\nexport interface CheckoutContextValue {\n session: CheckoutSession | null;\n loading: boolean;\n error: FloPayError | null;\n checkoutMode?: CheckoutMode;\n inlineSessionDraft?: InlineSessionDraft;\n applyInlineSessionPatch?: (\n patch: InlineSessionPatch,\n ) => Promise<{ sessionId: string; session: CheckoutSession | null }>;\n inlineSessionPatchProcessing?: boolean;\n}\n\nexport const FloPayContext = createContext<FloPayContextValue>({\n flopay: null,\n paypalFlopay: null,\n elements: null,\n billingApiUrl: '',\n});\n\nexport const CheckoutContext = createContext<CheckoutContextValue>({\n session: null,\n loading: false,\n error: null,\n});\n","import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport { PaymentAPI } from '@flopay/js';\nimport type { FloPay } from '@flopay/js';\nimport type {\n BeforeButtonClickEvent,\n CheckoutButtonMethod,\n FloPayAppearance,\n DeclineEvent,\n InlineSessionDraft,\n InlineSessionParams,\n InlineSessionPatch,\n PaymentResult,\n CheckoutSession,\n CheckoutMode,\n NormalizedCheckoutSession,\n} from '@flopay/shared';\nimport { SDK_VERSION, FloPayError, resolveBillingApiUrl, buildCheckoutDisplayData, resolveButtonsLayoutTheme } from '@flopay/shared';\nimport type { ButtonsLayoutStyles, ButtonsLayoutTheme } from '@flopay/shared';\nimport {\n BackButtonContentSlot,\n CardButtonContentSlot,\n TitleContentSlot,\n isEmptySlotContent,\n} from './card-button-content.js';\nimport { FloPayProvider } from './provider.js';\nimport { SplitCardForm } from './split-card-form.js';\nimport { CheckoutContext } from './context.js';\nimport {\n buildDeclineEvent,\n buildSyntheticSession,\n mapPayPalIntentStatusToPaymentResult,\n mergeInlineSessionPatch,\n mergeInlineSessionPatches,\n} from './checkout-utils.js';\nimport {\n PROCESSING_OVERLAY_ERROR_DELAY_MS,\n PROCESSING_OVERLAY_SUCCESS_DELAY_MS,\n ProcessingOverlay,\n type OverlayStatus,\n} from './processing-overlay.js';\nimport {\n checkoutProcessErrorToFloPayError,\n DEFAULT_SAVED_PAYMENT_DECLINE_METHOD,\n getRedirectResultFromCheckoutProcessError,\n handleSavedPaymentRedirectResult,\n loadSavedPaymentProviders,\n normalizeSavedPaymentError,\n processSavedPaymentForMode,\n resolveSavedPaymentPublishableKeys,\n} from './saved-payment-flow.js';\nimport { markSessionRecentlyCompleted, wasSessionRecentlyCompleted } from './recent-completion.js';\n\nconst DEFAULT_BUTTONS_LAYOUT_BUTTON_HEIGHT = 44;\nconst PAYPAL_RESUME_STORAGE_KEY = 'flopay_checkout_saved_payment_resume';\n\n// Module-scoped dedup map: cache key → in-flight `POST /v1/checkouts/sessions`\n// promise. Lives for the page-load only. Shared across every FloPayCheckout\n// instance so two mounts that race (StrictMode dev double-mount, Suspense\n// remount, navigation flicker, etc.) await the same POST instead of starting\n// their own and producing two backend sessions for the same cart.\n// `sessionStorage[cacheKey]` is the durable cross-page-load layer; this Map\n// is the within-page-load layer that closes the window between \"POST is in\n// flight\" and \"POST result has been written to sessionStorage\".\nconst sessionInflightMap: Map<string, Promise<{ sid: string; result: NormalizedCheckoutSession }>> = new Map();\n\n// Cross-module signal for \"this session was just /process'd successfully and\n// is mid-completion.\" Lives in sessionStorage (see `recent-completion.ts`) so\n// it survives both real component remounts and the cross-module boundary\n// between SplitCardForm (where /process succeeds) and this file (where\n// `resolveInlineSession` decides whether to clear a complete-status cache\n// hit). Marker is written *before* the 1.2s overlay delay in SplitCardForm,\n// so a bootstrap that re-runs during that delay still detects the session\n// as \"this journey's completion\" and reuses it.\ntype CheckoutLogType = 'standard_checkout' | 'embedded_checkout';\ntype CheckoutLogLayout = 'default_layout' | 'buttons_layout' | 'custom_layout';\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\ninterface PayPalResumeState {\n sessionId: string | null;\n publishableKey: string;\n paypalPublishableKey?: string;\n}\n\nfunction canUseStorage() {\n return typeof window !== 'undefined' && typeof window.sessionStorage !== 'undefined';\n}\n\nfunction readPayPalResumeState(): PayPalResumeState | null {\n if (!canUseStorage()) return null;\n\n try {\n const raw = window.sessionStorage.getItem(PAYPAL_RESUME_STORAGE_KEY);\n if (!raw) return null;\n return JSON.parse(raw) as PayPalResumeState;\n } catch {\n return null;\n }\n}\n\nfunction persistPayPalResumeState(state: PayPalResumeState) {\n if (!canUseStorage()) return;\n\n try {\n window.sessionStorage.setItem(PAYPAL_RESUME_STORAGE_KEY, JSON.stringify(state));\n } catch (error) {\n console.warn('[FloPayCheckout] Failed to persist PayPal resume state.', error);\n }\n}\n\nfunction clearPayPalResumeState() {\n if (!canUseStorage()) return;\n\n try {\n window.sessionStorage.removeItem(PAYPAL_RESUME_STORAGE_KEY);\n } catch (error) {\n console.warn('[FloPayCheckout] Failed to clear PayPal resume state.', error);\n }\n}\n\nfunction clearPayPalRedirectParams() {\n if (typeof window === 'undefined') return;\n\n const url = new URL(window.location.href);\n const keys = ['payment_intent', 'payment_intent_client_secret', 'redirect_status'];\n let changed = false;\n\n for (const key of keys) {\n if (url.searchParams.has(key)) {\n url.searchParams.delete(key);\n changed = true;\n }\n }\n\n if (changed) {\n window.history.replaceState(window.history.state, '', url.toString());\n }\n}\n\nfunction replaceCheckoutModeQueryParam(mode: CheckoutMode) {\n if (typeof window === 'undefined') return;\n\n const url = new URL(window.location.href);\n url.searchParams.set('mode', mode);\n window.history.replaceState(window.history.state, '', url.toString());\n}\n\n/** Props for the all-in-one `FloPayCheckout` wrapper. */\nexport interface FloPayCheckoutProps {\n /** The checkout session ID (UUID from billing API). Required unless `createSession` is provided. */\n sessionId?: string;\n /**\n * Create a checkout session inline — no separate API route needed.\n * The component POSTs to the billing API, gets the full session back, and renders the form.\n * Alternative to `sessionId` (provide one or the other).\n */\n createSession?: InlineSessionDraft;\n /** Billing API base URL. Defaults to the shared `BILLING_API_URL` constant. */\n billingApiUrl?: string;\n /** Visual appearance for payment elements. */\n appearance?: FloPayAppearance;\n /** Locale for payment elements (default: 'auto'). */\n locale?: string;\n /** Custom loading UI. Defaults to a simple centered spinner. */\n loading?: React.ReactNode;\n /** Custom error UI. Receives the error. Defaults to showing the error message. */\n error?: (error: FloPayError) => React.ReactNode;\n /** Called when the full payment flow completes successfully. */\n onComplete?: (result: PaymentResult) => void;\n /** Called when a payment error occurs. */\n onError?: (error: FloPayError) => void;\n /** Called when a payment is declined or the authentication step fails. */\n onDecline?: (decline: DeclineEvent) => void;\n /** Called when the full cardholder name input changes. */\n onFullNameChange?: (value: string) => void;\n /** Called when the AVS country dropdown changes. */\n onCountryChange?: (country: string) => void;\n /** Called when the AVS ZIP/postcode input changes. */\n onZipChange?: (zip: string) => void;\n /** Whether to show the PayPal button (default: true). */\n showPayPal?: boolean;\n /** Whether to show Apple Pay button (default: true). Only renders on supported devices. */\n showApplePay?: boolean;\n /** Whether to show Google Pay button (default: true). Only renders on supported devices. */\n showGooglePay?: boolean;\n /** Layout mode: 'default' (all visible) or 'buttons' (PayPal/wallets + expandable card form). */\n layout?: 'default' | 'buttons';\n /** Theme preset for the buttons layout: 'default', 'minimal', 'rounded', or 'dark'. */\n buttonsTheme?: import('@flopay/shared').ButtonsLayoutTheme;\n /** Custom style overrides for the buttons layout. Merged on top of the theme preset. */\n buttonsStyles?: import('@flopay/shared').ButtonsLayoutStyles;\n /** Custom React content rendered inside the card button when `layout=\"buttons\"`. */\n cardButtonContent?: React.ReactNode;\n /** Custom React content rendered for the buttons-layout card back button label. */\n cardBackButtonContent?: React.ReactNode;\n /** Custom React content rendered for the card-form title. */\n cardTitleContent?: React.ReactNode;\n /** Whether to show the default security footer in `layout=\"default\"`. Defaults to `true`. */\n showSecurityFooter?: boolean;\n /**\n * Called when a payment method button is clicked.\n * `method`: `'card'` | `'paypal'` | `'apple_pay'` | `'google_pay'`\n */\n onButtonClick?: (method: CheckoutButtonMethod) => void;\n /**\n * Called before a payment button continues in `layout=\"buttons\"`.\n * Runs for card, PayPal, Apple Pay, and Google Pay.\n * In `layout=\"buttons\"` with `createSession`, the returned patch is merged\n * into the inline session params before the selected flow continues.\n */\n onBeforeButtonClick?: (\n event: BeforeButtonClickEvent,\n ) => void | false | Promise<void | false | InlineSessionPatch> | InlineSessionPatch;\n /**\n * Enable AVS (Address Verification).\n * - `true` — show country + postal code (backward compatible default)\n * - `AVSFieldConfig` — granular per-field control, optionally scoped to country codes\n * - `false` / omitted — AVS disabled\n */\n enableAVS?: boolean | import('@flopay/shared').AVSFieldConfig;\n /** Layout for AVS fields: 'row' (side-by-side, default) or 'column' (stacked). */\n avsLayout?: 'row' | 'column';\n /** Label for the submit button. */\n submitLabel?: string;\n /** Additional CSS class for the wrapper. */\n className?: string;\n /** Seed an initial checkout error message for the rendered payment form. */\n initialErrorMessage?: string | null;\n /**\n * Override the default `SplitCardForm`. When provided, children are rendered\n * inside the initialized `FloPayProvider` with session props auto-injected.\n */\n children?: React.ReactNode;\n\n // ── Checkout mode props ──\n\n /**\n * Override the session's checkoutMode.\n * - `'full'` — show payment form (default)\n * - `'confirm'` — show confirm button, uses saved payment method\n * - `'auto'` — auto-submit with saved PM, falls back to `'full'` on failure\n */\n checkoutMode?: CheckoutMode;\n /** Label for the confirm button in `confirm` mode. Default: `'Confirm Purchase'`. */\n confirmLabel?: string;\n /** Custom confirm button renderer for `confirm` mode. */\n renderConfirmButton?: (props: {\n onConfirm: () => void;\n isProcessing: boolean;\n }) => React.ReactNode;\n /** Called when the session has already been completed. Receives the successUrl. */\n onSessionCompleted?: (successUrl: string) => void;\n\n /**\n * @deprecated No longer used. The Stripe publishable key is sourced exclusively\n * from the checkout session's `gatewayData.publishableKey`. Accepted only for\n * backward compatibility with older consumer code — the value is ignored.\n */\n fallbackPublishableKey?: string;\n}\n\nfunction hasInlineSessionPatchData(\n patch: InlineSessionPatch | undefined,\n): boolean {\n if (!patch) return false;\n\n return Boolean(\n (patch.account && Object.keys(patch.account).length > 0)\n || patch.couponCodes !== undefined\n || patch.tagsData !== undefined\n || patch.utmMetadata !== undefined,\n );\n}\n\n/**\n * All-in-one checkout component. Fetches the session, initializes the\n * payment provider, and renders the appropriate UI based on checkout mode.\n *\n * **Modes:**\n * - `full` (default) — renders `SplitCardForm` with card fields + wallet buttons\n * - `confirm` — renders a \"Confirm Purchase\" button, uses saved payment method\n * - `auto` — auto-submits with saved PM, falls back to `full` on failure\n *\n * ```tsx\n * <FloPayCheckout\n * sessionId=\"sess_abc123\"\n * onComplete={(result) => router.push('/success')}\n * onError={(err) => console.error(err)}\n * />\n * ```\n */\nexport function FloPayCheckout({\n sessionId: sessionIdProp,\n createSession: createSessionParams,\n billingApiUrl,\n appearance,\n locale,\n loading: loadingNode,\n error: errorNode,\n onComplete,\n onError,\n onDecline,\n onFullNameChange,\n onCountryChange,\n onZipChange,\n showPayPal = true,\n showApplePay = true,\n showGooglePay = true,\n layout,\n buttonsTheme,\n buttonsStyles,\n cardButtonContent,\n cardBackButtonContent,\n cardTitleContent,\n showSecurityFooter = true,\n onButtonClick,\n onBeforeButtonClick,\n enableAVS,\n avsLayout,\n submitLabel,\n className,\n initialErrorMessage = null,\n children,\n checkoutMode: checkoutModeProp,\n confirmLabel,\n renderConfirmButton,\n onSessionCompleted,\n}: FloPayCheckoutProps): React.ReactElement {\n const resolvedBillingUrl = resolveBillingApiUrl(billingApiUrl);\n const checkoutType: CheckoutLogType = createSessionParams ? 'embedded_checkout' : 'standard_checkout';\n const checkoutLayout: CheckoutLogLayout = children\n ? 'custom_layout'\n : layout === 'buttons'\n ? 'buttons_layout'\n : 'default_layout';\n\n const [unified, setUnified] = useState<NormalizedCheckoutSession | null>(null);\n const [flopay, setFloPay] = useState<FloPay | null>(null);\n const flopayRef = useRef<FloPay | null>(null);\n const [paypalFlopay, setPaypalFloPay] = useState<FloPay | null>(null);\n const paypalFlopayRef = useRef<FloPay | null>(null);\n const [session, setSession] = useState<CheckoutSession | null>(null);\n const [resolvedSessionId, setResolvedSessionId] = useState<string>(sessionIdProp ?? '');\n const activeSessionId = sessionIdProp ?? resolvedSessionId;\n const initSessionDependency = createSessionParams ? '' : activeSessionId;\n const [isLoading, setIsLoading] = useState(true);\n const [loadError, setLoadError] = useState<FloPayError | null>(null);\n const [currentMode, setCurrentMode] = useState<CheckoutMode>('full');\n const [confirmProcessing, setConfirmProcessing] = useState(false);\n const [modeError, setModeError] = useState<string | null>(initialErrorMessage);\n const [modeOverlayStatus, setModeOverlayStatus] = useState<OverlayStatus | null>(null);\n const [modeOverlayError, setModeOverlayError] = useState<string | null>(null);\n const [createSessionPatch, setCreateSessionPatch] = useState<InlineSessionPatch | undefined>(undefined);\n const [createSessionPatchBaseHash, setCreateSessionPatchBaseHash] = useState('');\n const [cardBootstrapPending, setCardBootstrapPending] = useState(false);\n const autoCheckoutAttempted = useRef(false);\n const paypalResumeAttempted = useRef(false);\n const savedPaymentKeysRef = useRef<{\n publishableKey: string;\n paypalPublishableKey?: string;\n } | null>(null);\n\n // Store callbacks in refs to avoid re-triggering the init useEffect\n const onCompleteRef = useRef(onComplete);\n onCompleteRef.current = onComplete;\n const onErrorRef = useRef(onError);\n onErrorRef.current = onError;\n const onDeclineRef = useRef(onDecline);\n onDeclineRef.current = onDecline;\n const onSessionCompletedRef = useRef(onSessionCompleted);\n onSessionCompletedRef.current = onSessionCompleted;\n\n useEffect(() => {\n console.info('[FloPay] Checkout initialized', {\n sdk_version: SDK_VERSION,\n checkout_type: checkoutType,\n checkout_layout: checkoutLayout,\n billing_api_url: resolvedBillingUrl,\n });\n }, [checkoutLayout, checkoutType, resolvedBillingUrl]);\n\n const baseCreateSessionHash = useMemo(\n () => createSessionParams ? hashCreateParams(createSessionParams) : '',\n [createSessionParams],\n );\n const activeCreateSessionPatch = useMemo(\n () => createSessionPatchBaseHash === baseCreateSessionHash\n ? createSessionPatch\n : undefined,\n [createSessionPatch, createSessionPatchBaseHash, baseCreateSessionHash],\n );\n const effectiveCreateSessionBase = useMemo(\n () => createSessionParams\n ? mergeInlineSessionPatch(createSessionParams, activeCreateSessionPatch)\n : undefined,\n [createSessionParams, activeCreateSessionPatch],\n );\n const effectiveCreateSessionMode = checkoutModeProp ?? effectiveCreateSessionBase?.checkoutMode ?? 'full';\n const effectiveCreateSession = useMemo(\n () => effectiveCreateSessionBase\n ? {\n ...effectiveCreateSessionBase,\n checkoutMode: effectiveCreateSessionMode,\n }\n : undefined,\n [effectiveCreateSessionBase, effectiveCreateSessionMode],\n );\n\n useEffect(() => {\n setCreateSessionPatch(undefined);\n setCreateSessionPatchBaseHash(baseCreateSessionHash);\n }, [baseCreateSessionHash]);\n\n useEffect(() => {\n setModeError(initialErrorMessage);\n }, [initialErrorMessage]);\n\n const emitDecline = useCallback(\n (\n method: CheckoutButtonMethod,\n input: string | FloPayError,\n overrides?: { code?: string; declineCode?: string },\n ) => {\n onDeclineRef.current?.(buildDeclineEvent(method, input, overrides));\n },\n [],\n );\n\n const runSavedPaymentFlow = useCallback(\n async (\n sess: CheckoutSession,\n options?: {\n attempt3DS?: boolean;\n fallbackToFull?: boolean;\n ensureProvidersReady?: () => Promise<unknown>;\n fromCreateSession?: boolean;\n initialAutoProcessingError?: NormalizedCheckoutSession['autoProcessingError'];\n autoProcessingAttempted?: boolean;\n sessionId?: string;\n },\n ): Promise<boolean> => {\n setModeError(null);\n setModeOverlayError(null);\n setModeOverlayStatus('processing');\n\n const activeSessionId = options?.sessionId ?? sess.id;\n\n try {\n const redirectResult = getRedirectResultFromCheckoutProcessError(options?.initialAutoProcessingError);\n let paymentResult: PaymentResult;\n\n if (redirectResult) {\n if (\n redirectResult.type === 'paypal_redirect_required'\n && savedPaymentKeysRef.current\n ) {\n persistPayPalResumeState({\n sessionId: activeSessionId,\n publishableKey: savedPaymentKeysRef.current.publishableKey,\n paypalPublishableKey: savedPaymentKeysRef.current.paypalPublishableKey,\n });\n }\n\n paymentResult = await handleSavedPaymentRedirectResult(redirectResult, {\n flopay: flopayRef.current,\n paypalFlopay: paypalFlopayRef.current,\n attempt3DS: options?.attempt3DS,\n billingApiUrl: resolvedBillingUrl,\n sessionId: activeSessionId,\n session: sess,\n });\n\n if (redirectResult.type === 'paypal_redirect_required') {\n clearPayPalResumeState();\n }\n } else if (options?.initialAutoProcessingError) {\n throw checkoutProcessErrorToFloPayError(\n options.initialAutoProcessingError,\n 'Automatic payment failed. Please try again.',\n {\n checkoutMethod: options.initialAutoProcessingError.checkoutMethod,\n },\n );\n } else if (options?.fromCreateSession) {\n if (options?.fallbackToFull) {\n setCurrentMode('full');\n replaceCheckoutModeQueryParam('full');\n }\n return false;\n } else {\n const result = await processSavedPaymentForMode({\n billingApiUrl: resolvedBillingUrl,\n sessionId: activeSessionId,\n session: sess,\n });\n if (result.type === 'success') {\n paymentResult = result.result;\n } else {\n if (\n result.type === 'paypal_redirect_required'\n && savedPaymentKeysRef.current\n ) {\n persistPayPalResumeState({\n sessionId: activeSessionId,\n publishableKey: savedPaymentKeysRef.current.publishableKey,\n paypalPublishableKey: savedPaymentKeysRef.current.paypalPublishableKey,\n });\n }\n\n paymentResult = await handleSavedPaymentRedirectResult(result, {\n flopay: flopayRef.current,\n paypalFlopay: paypalFlopayRef.current,\n attempt3DS: options?.attempt3DS,\n billingApiUrl: resolvedBillingUrl,\n sessionId: activeSessionId,\n session: sess,\n });\n\n if (result.type === 'paypal_redirect_required') {\n clearPayPalResumeState();\n }\n }\n }\n\n // Mark before the overlay delay so a bootstrap that re-runs during\n // the delay window detects the completion and reuses the session.\n if (activeSessionId) markSessionRecentlyCompleted(activeSessionId);\n setModeOverlayStatus('success');\n await sleep(PROCESSING_OVERLAY_SUCCESS_DELAY_MS);\n onCompleteRef.current?.(paymentResult);\n return true;\n } catch (err) {\n const floPayErr = normalizeSavedPaymentError(err);\n const method = floPayErr.checkoutMethod ?? DEFAULT_SAVED_PAYMENT_DECLINE_METHOD;\n\n setModeError(floPayErr.message);\n setModeOverlayError(floPayErr.message);\n if (options?.fallbackToFull) {\n setCurrentMode('full');\n replaceCheckoutModeQueryParam('full');\n }\n onErrorRef.current?.(floPayErr);\n emitDecline(method, floPayErr, {\n code: floPayErr.code,\n declineCode: floPayErr.declineCode,\n });\n setModeOverlayStatus('error');\n\n await Promise.allSettled([\n sleep(PROCESSING_OVERLAY_ERROR_DELAY_MS),\n options?.ensureProvidersReady ? options.ensureProvidersReady() : Promise.resolve(),\n ]);\n return false;\n } finally {\n setModeOverlayStatus(null);\n setModeOverlayError(null);\n }\n },\n [\n emitDecline,\n normalizeSavedPaymentError,\n resolvedBillingUrl,\n ],\n );\n\n useEffect(() => {\n if (typeof window === 'undefined' || paypalResumeAttempted.current) {\n return;\n }\n\n const params = new URLSearchParams(window.location.search);\n const clientSecret = params.get('payment_intent_client_secret');\n if (!clientSecret) {\n return;\n }\n\n const resumeState = readPayPalResumeState();\n if (!resumeState) {\n return;\n }\n\n paypalResumeAttempted.current = true;\n\n void (async () => {\n setModeError(null);\n setModeOverlayError(null);\n setModeOverlayStatus('processing');\n setConfirmProcessing(true);\n\n try {\n if (params.get('redirect_status') === 'failed') {\n throw Object.assign(\n new FloPayError('PayPal payment was declined. Please try again.', 'api_error'),\n { checkoutMethod: 'paypal' as const },\n );\n }\n\n const {\n flopay: resumeFlopay,\n paypalFlopay: resumePaypalFlopay,\n } = await loadSavedPaymentProviders({\n publishableKey: resumeState.publishableKey,\n paypalPublishableKey: resumeState.paypalPublishableKey,\n billingApiUrl: resolvedBillingUrl,\n locale,\n });\n\n const paypalStripe = (resumePaypalFlopay ?? resumeFlopay).getRawProvider() as import('@stripe/stripe-js').Stripe | null;\n if (!paypalStripe) {\n throw Object.assign(\n new FloPayError('PayPal is not available.', 'api_error'),\n { checkoutMethod: 'paypal' as const },\n );\n }\n\n const { paymentIntent, error } = await paypalStripe.retrievePaymentIntent(clientSecret);\n if (error) {\n throw Object.assign(\n new FloPayError(\n error.message ?? 'Failed to retrieve PayPal payment status.',\n 'api_error',\n { code: error.code },\n ),\n { checkoutMethod: 'paypal' as const },\n );\n }\n\n const resultStatus = mapPayPalIntentStatusToPaymentResult(paymentIntent?.status);\n\n if (!paymentIntent || resultStatus === 'failed') {\n throw Object.assign(\n new FloPayError('PayPal payment was not completed. Please try again.', 'api_error'),\n { checkoutMethod: 'paypal' as const },\n );\n }\n\n const paymentMethodId = typeof paymentIntent.payment_method === 'string'\n ? paymentIntent.payment_method\n : paymentIntent.payment_method?.id;\n\n // Manual-capture PayPal PIs land at `requires_capture` after PayPal\n // authorization. Backend must capture via /process, otherwise the PI\n // sits at requires_capture forever (\"Uncaptured\" in Stripe).\n let finalResultStatus: PaymentResult['status'] = resultStatus;\n if (resumeState.sessionId) {\n const resumeApi = new PaymentAPI(resolvedBillingUrl);\n const resumeSessionResult = await resumeApi.getUnifiedCheckoutSession(resumeState.sessionId);\n const resumeSession = resumeSessionResult.data.session;\n if (resumeSession && resumeSession.status !== 'complete') {\n const processResult = await processSavedPaymentForMode({\n billingApiUrl: resolvedBillingUrl,\n sessionId: resumeState.sessionId,\n session: resumeSession,\n tokenizedData: {\n id: paymentMethodId ?? paymentIntent.id,\n type: 'card',\n threeDSecureActionResultTokenId: paymentIntent.id,\n isPaypal: true,\n },\n });\n if (processResult.type !== 'success') {\n throw Object.assign(\n new FloPayError('Failed to finalize PayPal payment.', 'api_error'),\n { checkoutMethod: 'paypal' as const },\n );\n }\n // /process's result.status reflects post-capture state; the\n // pre-capture PI status mapping would otherwise leak through.\n finalResultStatus = processResult.result.status;\n }\n }\n\n if (resumeState.sessionId) markSessionRecentlyCompleted(resumeState.sessionId);\n setModeOverlayStatus('success');\n await sleep(PROCESSING_OVERLAY_SUCCESS_DELAY_MS);\n onCompleteRef.current?.({\n status: finalResultStatus,\n paymentIntentId: paymentIntent.id,\n paymentMethodId,\n checkoutMethod: 'paypal',\n });\n } catch (err) {\n const floPayErr = normalizeSavedPaymentError(err);\n const method = floPayErr.checkoutMethod ?? 'paypal';\n\n setModeError(floPayErr.message);\n setModeOverlayError(floPayErr.message);\n onErrorRef.current?.(floPayErr);\n emitDecline(method, floPayErr, {\n code: floPayErr.code,\n declineCode: floPayErr.declineCode,\n });\n setModeOverlayStatus('error');\n await sleep(PROCESSING_OVERLAY_ERROR_DELAY_MS);\n } finally {\n clearPayPalResumeState();\n clearPayPalRedirectParams();\n setModeOverlayStatus(null);\n setModeOverlayError(null);\n setConfirmProcessing(false);\n }\n })();\n }, [emitDecline, locale, normalizeSavedPaymentError, resolvedBillingUrl]);\n\n // ── Session creation dedup ──\n // Uses the module-level `sessionInflightMap` (declared near the top of this\n // file) so two FloPayCheckout instances mounted in the same page-load —\n // including React StrictMode's dev double-mount, a Suspense remount, or a\n // navigation that briefly remounts the parent — share the same in-flight\n // POST instead of each starting their own and producing duplicate sessions.\n // A per-component useRef would be reset on each remount and cannot dedupe\n // across instances.\n // Tracks whether init has already completed — prevents redundant re-runs\n // when createSessionParams is a new object ref but semantically identical.\n const initializedHashRef = useRef<string | null>(null);\n\n // ── Deterministic hash for session caching ──\n\n function hashCreateParams(params: InlineSessionDraft | undefined): string {\n // Include only a compact buyer fingerprint in the cache key. The resulting\n // sessionStorage key is hashed, but the checkout session itself is account-\n // bound on the backend; reusing it across emails/users can route payment\n // processing through the wrong persisted gateway.\n //\n // Note: `account.userId` is intentionally excluded. It is a consumer-\n // generated identifier and many consumers (e.g. funnels-next) regenerate\n // it per component mount via `crypto.randomUUID()` — including it here\n // would produce a new hash on every mount, miss the sessionStorage cache,\n // and POST a duplicate session every time. Email + country are sufficient\n // buyer-identity for cross-buyer cache safety.\n const key = JSON.stringify({\n c: params?.clientId,\n a: {\n e: params?.account?.email?.trim().toLowerCase() ?? '',\n country: params?.account?.country ?? '',\n },\n successUrl: params?.successUrl,\n cancelUrl: params?.cancelUrl,\n i: params?.items?.map(x => `${x.providerItemId}:${x.totalAmount}:${x.overrideAmount ?? ''}:${x.quantity ?? 1}`).sort(),\n s: params?.subscriptions?.map(x => `${x.providerPlanId}:${x.totalAmount}:${x.overrideAmount ?? ''}:${x.quantity ?? 1}`).sort(),\n couponCodes: params?.couponCodes,\n tagsData: params?.tagsData,\n utmMetadata: params?.utmMetadata,\n tokenizedData: params?.tokenizedData,\n m: params?.checkoutMode ?? 'full',\n });\n let h = 0;\n for (let i = 0; i < key.length; i++) {\n h = ((h << 5) - h + key.charCodeAt(i)) | 0;\n }\n return `flopay_session_${Math.abs(h).toString(36)}`;\n }\n\n // Stable hash of createSession params — used as effect dependency instead\n // of the raw object, so a new object reference with the same values\n // doesn't re-trigger the effect.\n const createSessionHash = useMemo(\n () => effectiveCreateSession ? hashCreateParams(effectiveCreateSession) : '',\n [effectiveCreateSession],\n );\n // Keep a ref to the latest params so the effect closure always sees them.\n const createSessionParamsRef = useRef(effectiveCreateSession);\n createSessionParamsRef.current = effectiveCreateSession;\n\n useEffect(() => {\n setResolvedSessionId(sessionIdProp ?? '');\n }, [sessionIdProp]);\n\n useEffect(() => {\n autoCheckoutAttempted.current = false;\n setModeError(initialErrorMessage);\n setModeOverlayError(null);\n setModeOverlayStatus(null);\n }, [createSessionHash, initialErrorMessage, sessionIdProp]);\n\n async function resolveInlineSession(\n params: InlineSessionDraft,\n cacheKey: string,\n ): Promise<{ sid: string; result: NormalizedCheckoutSession }> {\n const api = new PaymentAPI(resolvedBillingUrl);\n let sid: string | null = typeof window !== 'undefined'\n ? window.sessionStorage.getItem(cacheKey)\n : null;\n let realResult: NormalizedCheckoutSession | null = null;\n\n if (sid) {\n try {\n realResult = await api.getUnifiedCheckoutSession(sid);\n const status = realResult.data.session?.status;\n if (status === 'complete') {\n // If this session was completed inside the current page-load — the\n // marker is written synchronously in SplitCardForm the moment\n // /process succeeds, *before* the 1.2s overlay delay — return the\n // completed session as-is. Otherwise the parent's mid-flight\n // onComplete + navigation could race a re-mounted bootstrap into\n // clearing the cache and POSTing a duplicate session that would\n // then be /process'd with the same PI (the source of the\n // duplicate-subscription bug).\n if (wasSessionRecentlyCompleted(sid)) {\n return { sid, result: realResult };\n }\n // Otherwise the cached session is genuinely stale (e.g. user\n // revisits /checkout in a new page-load after a previous successful\n // checkout). Clear and create a new one as before.\n if (typeof window !== 'undefined') window.sessionStorage.removeItem(cacheKey);\n sid = null;\n realResult = null;\n }\n } catch {\n if (typeof window !== 'undefined') window.sessionStorage.removeItem(cacheKey);\n sid = null;\n }\n }\n\n if (!sid) {\n // Inject checkout analytics metadata into the session creation payload\n const paramsWithAnalytics: InlineSessionParams = {\n ...(params as InlineSessionParams),\n avsCheck: !!enableAVS,\n avsConfig: typeof enableAVS === 'object' ? enableAVS : undefined,\n checkoutType: 'embedded_checkout',\n checkoutLayout: children ? 'custom_layout' : layout === 'buttons' ? 'buttons_layout' : 'default_layout',\n };\n realResult = await api.createAndFetchSession(paramsWithAnalytics);\n sid = realResult.data.session?.id ?? '';\n if (sid && typeof window !== 'undefined') {\n window.sessionStorage.setItem(cacheKey, sid);\n }\n }\n\n return { sid: sid ?? '', result: realResult! };\n }\n\n const bootstrapInlineSession = useCallback(\n async (patch?: InlineSessionPatch) => {\n const baseParams = createSessionParamsRef.current;\n if (!baseParams) {\n throw new FloPayError('createSession is required to bootstrap checkout.', 'validation_error');\n }\n\n const mergedParams = mergeInlineSessionPatch(baseParams, patch);\n // The cache key includes a compact buyer fingerprint because backend\n // sessions are account-bound. Account, coupon, tag, UTM, or cart changes\n // should bootstrap a fresh session instead of reusing a stale gateway.\n const cacheKey = hashCreateParams(mergedParams);\n\n let promise = sessionInflightMap.get(cacheKey);\n if (!promise) {\n promise = resolveInlineSession(mergedParams, cacheKey);\n sessionInflightMap.set(cacheKey, promise);\n }\n\n let resolved: { sid: string; result: NormalizedCheckoutSession };\n try {\n resolved = await promise;\n } finally {\n // Only the inserter clears the map entry — but `delete` on a missing\n // key is a no-op so this is safe to call from every awaiter.\n sessionInflightMap.delete(cacheKey);\n }\n\n initializedHashRef.current = cacheKey;\n\n try {\n if (patch) {\n setCreateSessionPatchBaseHash(baseCreateSessionHash);\n setCreateSessionPatch((prev) => mergeInlineSessionPatches(prev, patch));\n }\n\n const { sid, result: realResult } = resolved;\n\n setUnified(realResult);\n if (realResult.data.session) {\n setSession(realResult.data.session);\n }\n if (sid) {\n setResolvedSessionId(sid);\n }\n\n const {\n publishableKey,\n paypalPublishableKey,\n } = resolveSavedPaymentPublishableKeys(realResult);\n const {\n flopay: instance,\n paypalFlopay: paypalInstance,\n } = await loadSavedPaymentProviders({\n publishableKey,\n paypalPublishableKey,\n billingApiUrl: resolvedBillingUrl,\n locale,\n });\n\n flopayRef.current = instance;\n setFloPay(instance);\n paypalFlopayRef.current = paypalInstance;\n setPaypalFloPay(paypalInstance);\n\n setIsLoading(false);\n } catch (err) {\n if (initializedHashRef.current === cacheKey) {\n initializedHashRef.current = null;\n }\n throw err;\n }\n\n return resolved;\n },\n [locale, resolvedBillingUrl],\n );\n\n const handleInlineSessionPatch = useCallback(async (patch: InlineSessionPatch) => {\n if (!hasInlineSessionPatchData(patch) || cardBootstrapPending) {\n return {\n sessionId: resolvedSessionId,\n session,\n };\n }\n\n setCardBootstrapPending(true);\n try {\n const resolved = await bootstrapInlineSession(patch);\n return {\n sessionId: resolved.sid,\n session: resolved.result.data.session ?? null,\n };\n } finally {\n setCardBootstrapPending(false);\n }\n }, [\n bootstrapInlineSession,\n cardBootstrapPending,\n resolvedSessionId,\n session,\n ]);\n\n // ── Fetch session + initialize ──\n\n useEffect(() => {\n let cancelled = false;\n setLoadError(null);\n\n // ── createSession path: render immediately, resolve in background ──\n if (createSessionHash) {\n const params = createSessionParamsRef.current!;\n setSession(buildSyntheticSession(params, checkoutModeProp));\n setCurrentMode(effectiveCreateSessionMode);\n setIsLoading(false);\n\n // Already initialized with the same params — skip the network bootstrap\n // but keep the synthetic session in sync with any mode override.\n if (initializedHashRef.current === createSessionHash) {\n return () => { cancelled = true; };\n }\n\n (async () => {\n // Skip auto-checkout when resuming from a PayPal redirect — the\n // PayPal-resume effect (above) is the canonical completer for that\n // path. Without this guard, runSavedPaymentFlow races the resume\n // effect and triggers a duplicate POST /v1/checkouts/sessions/process.\n const hasPayPalRedirectParams =\n typeof window !== 'undefined' &&\n new URLSearchParams(window.location.search).has('payment_intent');\n\n const shouldAutoProcessInlineSession =\n effectiveCreateSessionMode === 'auto' &&\n !autoCheckoutAttempted.current &&\n !hasPayPalRedirectParams;\n\n if (shouldAutoProcessInlineSession) {\n setModeError(null);\n setModeOverlayError(null);\n setModeOverlayStatus('processing');\n }\n\n try {\n const resolved = await bootstrapInlineSession();\n const resolvedSession = resolved.result.data.session ?? null;\n savedPaymentKeysRef.current = resolveSavedPaymentPublishableKeys(resolved.result);\n\n if (\n !cancelled &&\n shouldAutoProcessInlineSession &&\n resolvedSession\n ) {\n autoCheckoutAttempted.current = true;\n await runSavedPaymentFlow(resolvedSession, {\n attempt3DS: true,\n fallbackToFull: true,\n fromCreateSession: true,\n initialAutoProcessingError: resolved.result.autoProcessingError,\n autoProcessingAttempted: resolved.result.autoProcessingAttempted,\n sessionId: resolved.sid || resolvedSession.id,\n });\n return;\n }\n\n if (!cancelled && shouldAutoProcessInlineSession) {\n setModeOverlayStatus(null);\n setModeOverlayError(null);\n }\n } catch (err) {\n if (cancelled) return;\n\n const errorCode = err instanceof FloPayError\n ? err.code\n : typeof err === 'object' && err !== null && 'code' in err\n ? (err as { code?: string }).code\n : undefined;\n\n if (\n shouldAutoProcessInlineSession &&\n errorCode === 'session_auto_completed'\n ) {\n autoCheckoutAttempted.current = true;\n setModeOverlayStatus('success');\n await sleep(PROCESSING_OVERLAY_SUCCESS_DELAY_MS);\n\n if (!cancelled) {\n onCompleteRef.current?.({ status: 'succeeded' });\n setModeOverlayStatus(null);\n setModeOverlayError(null);\n }\n return;\n }\n\n if (shouldAutoProcessInlineSession) {\n setModeOverlayStatus(null);\n setModeOverlayError(null);\n }\n\n const floPayErr = err instanceof FloPayError ? err\n : new FloPayError(err instanceof Error ? err.message : 'Failed to create session', 'api_error');\n setLoadError(floPayErr);\n }\n })();\n\n return () => { cancelled = true; };\n }\n\n // ── Existing sessionId flow ──\n setIsLoading(true);\n\n async function init() {\n try {\n const api = new PaymentAPI(resolvedBillingUrl);\n const result = await api.getUnifiedCheckoutSession(activeSessionId);\n\n if (cancelled) return;\n setUnified(result);\n\n const sess = result.data.session ?? null;\n setSession(sess);\n\n if (!sess) {\n throw new FloPayError('No session data returned', 'api_error');\n }\n\n if (sess.status === 'complete') {\n setIsLoading(false);\n onSessionCompletedRef.current?.(sess.successUrl ?? '');\n return;\n }\n\n if (sess.status === 'expired') {\n throw new FloPayError('Checkout session has expired.', 'api_error', {\n code: 'checkout_session_expired',\n });\n }\n\n const effectiveMode = checkoutModeProp ?? sess.checkoutMode ?? 'full';\n setCurrentMode(effectiveMode);\n\n const hasPayPalRedirectParams =\n typeof window !== 'undefined' &&\n new URLSearchParams(window.location.search).has('payment_intent');\n\n if (\n effectiveMode === 'auto' &&\n !autoCheckoutAttempted.current &&\n !hasPayPalRedirectParams\n ) {\n autoCheckoutAttempted.current = true;\n const stripeInitPromise = initStripe(result);\n\n try {\n await runSavedPaymentFlow(sess, {\n attempt3DS: true,\n fallbackToFull: true,\n ensureProvidersReady: () => stripeInitPromise,\n sessionId: activeSessionId || sess.id,\n });\n if (cancelled) return;\n await stripeInitPromise;\n if (!cancelled) {\n setIsLoading(false);\n }\n return;\n } catch {\n if (cancelled) return;\n await stripeInitPromise;\n if (!cancelled) setIsLoading(false);\n return;\n }\n }\n\n await initStripe(result);\n if (!cancelled) setIsLoading(false);\n } catch (err) {\n if (cancelled) return;\n const floPayErr = err instanceof FloPayError ? err\n : new FloPayError(err instanceof Error ? err.message : 'Failed to initialize checkout', 'api_error');\n setLoadError(floPayErr);\n setIsLoading(false);\n }\n }\n\n async function initStripe(result: NormalizedCheckoutSession) {\n const {\n publishableKey,\n paypalPublishableKey,\n } = resolveSavedPaymentPublishableKeys(result);\n savedPaymentKeysRef.current = {\n publishableKey,\n paypalPublishableKey,\n };\n const {\n flopay: instance,\n paypalFlopay: paypalInstance,\n } = await loadSavedPaymentProviders({\n publishableKey,\n paypalPublishableKey,\n billingApiUrl: resolvedBillingUrl,\n locale,\n });\n\n flopayRef.current = instance;\n setFloPay(instance);\n paypalFlopayRef.current = paypalInstance;\n setPaypalFloPay(paypalInstance);\n }\n\n init();\n return () => {\n cancelled = true;\n };\n // Only re-run when the session/config identity changes — NOT when callbacks change.\n // Callbacks are accessed via refs (onCompleteRef, onSessionCompletedRef).\n // `createSessionHash` is a stable string derived from createSessionParams,\n // so a new object reference with the same values won't re-trigger.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [\n bootstrapInlineSession,\n checkoutModeProp,\n createSessionHash,\n effectiveCreateSessionMode,\n initSessionDependency,\n runSavedPaymentFlow,\n ]);\n\n // ── Confirm mode handler ──\n\n const handleConfirmCheckout = useCallback(async () => {\n if (confirmProcessing || !session) return;\n setConfirmProcessing(true);\n setModeError(null);\n\n try {\n await runSavedPaymentFlow(session, {\n fallbackToFull: true,\n sessionId: activeSessionId || session.id,\n });\n } finally {\n setConfirmProcessing(false);\n }\n }, [activeSessionId, confirmProcessing, runSavedPaymentFlow, session]);\n\n // Provider options from session data\n const providerOptions = useMemo(() => {\n if (!unified || !session) return undefined;\n\n const opts: {\n appearance?: FloPayAppearance;\n paymentMethodCreation: 'manual';\n billingApiUrl: string;\n clientSecret?: string;\n amount?: number;\n currency?: string;\n } = {\n appearance,\n paymentMethodCreation: 'manual',\n billingApiUrl: resolvedBillingUrl,\n };\n\n if (\n unified.provider === 'stripe' &&\n unified.data.stripe?.clientSecret\n ) {\n opts.clientSecret = unified.data.stripe.clientSecret;\n } else {\n // Use display total (respects hideItems logic) instead of raw session.amount\n const displayTotal = buildCheckoutDisplayData(session).total;\n opts.amount = Math.round(displayTotal * 100) || session.amount;\n opts.currency = session.currency?.toLowerCase();\n }\n\n return opts;\n }, [unified, session, appearance, resolvedBillingUrl]);\n\n const shouldHandleInlineSessionPatch = Boolean(\n createSessionParams &&\n !children &&\n layout === 'buttons' &&\n onBeforeButtonClick &&\n effectiveCreateSessionMode === 'full',\n );\n\n // Checkout context\n const checkoutValue = useMemo(\n () => ({\n session,\n loading: isLoading,\n error: loadError,\n checkoutMode: currentMode,\n inlineSessionDraft: effectiveCreateSession,\n applyInlineSessionPatch: shouldHandleInlineSessionPatch\n ? handleInlineSessionPatch\n : undefined,\n inlineSessionPatchProcessing: cardBootstrapPending,\n }),\n [\n session,\n isLoading,\n loadError,\n currentMode,\n effectiveCreateSession,\n shouldHandleInlineSessionPatch,\n handleInlineSessionPatch,\n cardBootstrapPending,\n ],\n );\n const shouldShowInterimButtons =\n Boolean(createSessionParams) &&\n layout === 'buttons' &&\n (!flopay || !providerOptions);\n const modeOverlay = modeOverlayStatus\n ? (\n <ProcessingOverlay\n status={modeOverlayStatus}\n errorMessage={modeOverlayError}\n />\n )\n : null;\n\n // ── Loading state ──\n if (isLoading) {\n if (loadingNode) {\n return (\n <>\n {loadingNode}\n {modeOverlay}\n </>\n );\n }\n\n // Buttons layout: show button-shaped skeletons\n if (layout === 'buttons') {\n const skeletonBar = (h: number) => (\n <div style={{\n height: h, borderRadius: 8, background: '#e5e7eb',\n animation: 'flopay-loading-pulse 1.5s ease-in-out infinite',\n }} />\n );\n return (\n <>\n <div style={{ display: 'flex', flexDirection: 'column', gap: '0.5rem' }}>\n {showPayPal && skeletonBar(DEFAULT_BUTTONS_LAYOUT_BUTTON_HEIGHT)}\n {(showApplePay || showGooglePay) && skeletonBar(DEFAULT_BUTTONS_LAYOUT_BUTTON_HEIGHT)}\n {skeletonBar(DEFAULT_BUTTONS_LAYOUT_BUTTON_HEIGHT)}\n <style>{`@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }`}</style>\n </div>\n {modeOverlay}\n </>\n );\n }\n\n // Default layout: centered spinner\n return (\n <>\n <div style={{ display: 'flex', justifyContent: 'center', padding: 32 }}>\n <div style={{\n width: 24, height: 24,\n border: '2px solid #e5e7eb', borderTopColor: '#6b7280',\n borderRadius: '50%', animation: 'spin 0.6s linear infinite',\n }} />\n <style>{`@keyframes spin { to { transform: rotate(360deg); } }`}</style>\n </div>\n {modeOverlay}\n </>\n );\n }\n\n // ── Error state ──\n if (loadError) {\n if (errorNode) {\n return (\n <CheckoutContext.Provider value={checkoutValue}>\n {errorNode(loadError)}\n </CheckoutContext.Provider>\n );\n }\n return (\n <CheckoutContext.Provider value={checkoutValue}>\n <div\n style={{\n padding: 24,\n textAlign: 'center',\n color: '#dc2626',\n fontSize: 14,\n }}\n >\n {loadError.message}\n </div>\n </CheckoutContext.Provider>\n );\n }\n\n // When using createSession + buttons layout, render an interim buttons view\n // while Stripe initializes in the background. The Credit/Debit Card button\n // is fully interactive (expands card form); PayPal/wallets show as skeletons.\n // Once flopay loads, the real SplitCardForm replaces this seamlessly.\n if (shouldShowInterimButtons) {\n return (\n <>\n <CheckoutContext.Provider value={checkoutValue}>\n <InterimButtonsView\n onButtonClick={onButtonClick}\n showPayPal={showPayPal}\n showApplePay={showApplePay}\n showGooglePay={showGooglePay}\n buttonsTheme={buttonsTheme}\n buttonsStyles={buttonsStyles}\n cardButtonContent={cardButtonContent}\n cardBackButtonContent={cardBackButtonContent}\n cardTitleContent={cardTitleContent}\n />\n </CheckoutContext.Provider>\n {modeOverlay}\n </>\n );\n }\n\n if (!flopay || !providerOptions) {\n return <>{modeOverlay}</>;\n }\n\n // ── Confirm mode ──\n if (currentMode === 'confirm') {\n return (\n <>\n <CheckoutContext.Provider value={checkoutValue}>\n <FloPayProvider flopay={flopay} paypalFlopay={paypalFlopay} options={providerOptions}>\n <div className={className}>\n {modeError && (\n <div\n style={{\n color: '#dc2626',\n fontSize: '0.875rem',\n marginBottom: '0.75rem',\n textAlign: 'center',\n }}\n >\n {modeError}\n </div>\n )}\n {renderConfirmButton ? (\n renderConfirmButton({\n onConfirm: handleConfirmCheckout,\n isProcessing: confirmProcessing,\n })\n ) : (\n <button\n type=\"button\"\n onClick={handleConfirmCheckout}\n disabled={confirmProcessing}\n style={{\n width: '100%',\n padding: '0.875rem',\n backgroundColor: '#4A49FF',\n color: 'white',\n border: 'none',\n borderRadius: '8px',\n fontSize: '1rem',\n fontWeight: 600,\n cursor: confirmProcessing ? 'not-allowed' : 'pointer',\n opacity: confirmProcessing ? 0.6 : 1,\n }}\n >\n {confirmProcessing\n ? 'Processing...'\n : confirmLabel ?? 'Confirm Purchase'}\n </button>\n )}\n </div>\n </FloPayProvider>\n </CheckoutContext.Provider>\n {modeOverlay}\n </>\n );\n }\n\n // ── Full mode (default / fallback) ──\n return (\n <>\n <CheckoutContext.Provider value={checkoutValue}>\n <FloPayProvider flopay={flopay} paypalFlopay={paypalFlopay} options={providerOptions}>\n {children ? (\n <>\n {modeError && (\n <div\n style={{\n padding: '0.75rem 1rem',\n marginBottom: '0.75rem',\n backgroundColor: '#FEF3C7',\n border: '1px solid #F59E0B',\n borderRadius: '8px',\n color: '#92400E',\n fontSize: '0.875rem',\n }}\n >\n {modeError}\n </div>\n )}\n <SessionInjector\n sessionId={activeSessionId}\n billingApiUrl={resolvedBillingUrl}\n session={session}\n >\n {children}\n </SessionInjector>\n </>\n ) : (\n <SplitCardForm\n sessionId={activeSessionId}\n email={session?.customer?.email}\n userId={session?.customer?.id}\n firstName={session?.customer?.firstName}\n lastName={session?.customer?.lastName}\n totalAmount={session ? Math.round(buildCheckoutDisplayData(session).total * 100) : 0}\n currency={session?.currency?.toLowerCase() ?? 'usd'}\n onComplete={onComplete}\n onError={onError}\n onDecline={onDecline}\n error={modeError}\n onErrorChange={setModeError}\n onFullNameChange={onFullNameChange}\n showPayPal={showPayPal}\n showApplePay={showApplePay}\n showGooglePay={showGooglePay}\n layout={layout}\n buttonsTheme={buttonsTheme}\n buttonsStyles={buttonsStyles}\n cardButtonContent={cardButtonContent}\n cardBackButtonContent={cardBackButtonContent}\n cardTitleContent={cardTitleContent}\n showSecurityFooter={showSecurityFooter}\n onButtonClick={onButtonClick}\n onBeforeButtonClick={onBeforeButtonClick}\n enableAVS={enableAVS}\n avsLayout={avsLayout}\n country={session?.customer?.country}\n city={session?.customer?.city}\n state={session?.customer?.state}\n onCountryChange={onCountryChange}\n onZipChange={onZipChange}\n avsCheck={!!enableAVS}\n checkoutType={createSessionParams ? 'embedded_checkout' : 'standard_checkout'}\n checkoutLayout={children ? 'custom_layout' : layout === 'buttons' ? 'buttons_layout' : 'default_layout'}\n submitLabel={submitLabel}\n className={className}\n />\n )}\n </FloPayProvider>\n </CheckoutContext.Provider>\n {modeOverlay}\n </>\n );\n}\n\n/**\n * Auto-injects session props into child form components.\n * Explicit props on children take precedence over injected values.\n */\nfunction SessionInjector({\n sessionId,\n billingApiUrl,\n session,\n children,\n}: {\n sessionId: string;\n billingApiUrl: string;\n session: CheckoutSession | null;\n children: React.ReactNode;\n}) {\n return (\n <>\n {React.Children.map(children, (child) => {\n if (!React.isValidElement(child)) return child;\n\n const existing = child.props as Record<string, unknown>;\n const injected: Record<string, unknown> = {};\n\n if (!existing.sessionId) injected.sessionId = sessionId;\n if (!existing.billingApiUrl) injected.billingApiUrl = billingApiUrl;\n\n if (session?.customer) {\n if (!existing.email) injected.email = session.customer.email;\n if (!existing.userId) injected.userId = session.customer.id;\n if (!existing.firstName)\n injected.firstName = session.customer.firstName;\n if (!existing.lastName)\n injected.lastName = session.customer.lastName;\n }\n\n if (Object.keys(injected).length === 0) return child;\n return React.cloneElement(child, injected);\n })}\n </>\n );\n}\n\n/**\n * Interim buttons view rendered while Stripe initializes in the background.\n * Shows skeleton bars for PayPal/wallets and a fully interactive Credit/Debit Card button.\n */\nfunction InterimButtonsView({\n onButtonClick,\n onCardButtonClick,\n cardLoading = false,\n cardOpen,\n errorMessage,\n showPayPal,\n showApplePay,\n showGooglePay,\n buttonsTheme,\n buttonsStyles: stylesOverride,\n cardButtonContent,\n cardBackButtonContent,\n cardTitleContent,\n}: {\n onButtonClick?: (method: CheckoutButtonMethod) => void;\n onCardButtonClick?: () => void | Promise<void>;\n cardLoading?: boolean;\n cardOpen?: boolean;\n errorMessage?: string | null;\n showPayPal: boolean;\n showApplePay: boolean;\n showGooglePay: boolean;\n buttonsTheme?: ButtonsLayoutTheme;\n buttonsStyles?: ButtonsLayoutStyles;\n cardButtonContent?: React.ReactNode;\n cardBackButtonContent?: React.ReactNode;\n cardTitleContent?: React.ReactNode;\n}) {\n const [showCardForm, setShowCardForm] = useState(false);\n const isCardOpenControlled = typeof cardOpen === 'boolean';\n\n useEffect(() => {\n if (isCardOpenControlled) {\n setShowCardForm(cardOpen);\n }\n }, [cardOpen, isCardOpenControlled]);\n\n const bStyles = useMemo<ButtonsLayoutStyles>(() => {\n const base = resolveButtonsLayoutTheme(buttonsTheme);\n if (!stylesOverride) return base;\n return {\n ...base,\n ...stylesOverride,\n cardButton: { ...base.cardButton, ...stylesOverride.cardButton },\n cardFormContainer: { ...base.cardFormContainer, ...stylesOverride.cardFormContainer },\n backButton: { ...base.backButton, ...stylesOverride.backButton },\n backButtonIcon: { ...base.backButtonIcon, ...stylesOverride.backButtonIcon },\n submitButton: { ...base.submitButton, ...stylesOverride.submitButton },\n title: { ...base.title, ...stylesOverride.title },\n };\n }, [buttonsTheme, stylesOverride]);\n\n const skeleton = (h: number) => (\n <div style={{\n height: h, borderRadius: 8, background: '#e5e7eb',\n animation: 'flopay-interim-pulse 1.5s ease-in-out infinite',\n }} />\n );\n const cardButtonSizing = cardButtonContent === undefined\n ? { boxSizing: 'border-box' as const, height: DEFAULT_BUTTONS_LAYOUT_BUTTON_HEIGHT, padding: '0 1rem' }\n : { padding: '0.9rem 1rem' };\n\n if (showCardForm) {\n // Show a card form placeholder with back button — real form takes over when Stripe loads\n const inputBorder = bStyles.cardInputBorder ?? '#e5e7eb';\n const inputBg = bStyles.cardInputBackground ?? 'white';\n const hideBackButtonLabel = isEmptySlotContent(cardBackButtonContent);\n const hideTitle = isEmptySlotContent(cardTitleContent);\n return (\n <div style={{\n backgroundColor: (bStyles.cardFormContainer?.backgroundColor as string) ?? 'white',\n borderRadius: '8px',\n animation: 'flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both',\n overflow: 'hidden',\n ...bStyles.cardFormContainer as React.CSSProperties,\n }}>\n <div style={{ display: 'flex', alignItems: 'center', padding: '0.75rem 0 0.625rem' }}>\n <button\n type=\"button\"\n onClick={() => {\n if (!isCardOpenControlled) {\n setShowCardForm(false);\n }\n }}\n aria-label=\"Back to payment methods\"\n disabled={isCardOpenControlled || cardLoading}\n style={{\n display: 'inline-flex', alignItems: 'center', gap: hideBackButtonLabel ? 0 : '0.5rem',\n background: 'none', border: 'none',\n color: '#4b5563', fontSize: '0.85rem', fontWeight: 500,\n padding: 0, flexShrink: 0, opacity: isCardOpenControlled || cardLoading ? 0.6 : 1,\n cursor: isCardOpenControlled || cardLoading ? 'not-allowed' : 'pointer',\n ...bStyles.backButton as React.CSSProperties,\n }}\n >\n <span style={{\n display: 'inline-flex', alignItems: 'center', justifyContent: 'center',\n width: 28, height: 28, borderRadius: '50%',\n backgroundColor: '#f3f4f6',\n ...bStyles.backButtonIcon as React.CSSProperties,\n }}>\n <svg width=\"14\" height=\"14\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2.5\" strokeLinecap=\"round\" strokeLinejoin=\"round\">\n <path d=\"M15 18l-6-6 6-6\" />\n </svg>\n </span>\n <BackButtonContentSlot content={cardBackButtonContent} />\n </button>\n {hideTitle ? (\n <div style={{ flex: 1 }} />\n ) : (\n <div style={{\n flex: 1, textAlign: 'center', fontWeight: 600, fontSize: '1.05rem',\n color: '#262833', paddingRight: 80,\n ...bStyles.title as React.CSSProperties,\n }}>\n <TitleContentSlot content={cardTitleContent} />\n </div>\n )}\n </div>\n {/* Skeleton card fields */}\n <div style={{ backgroundColor: inputBg, border: `1px solid ${inputBorder}`, borderTopLeftRadius: 8, borderTopRightRadius: 8, padding: 12, height: 45 }}>\n <div style={{ width: '60%', height: 14, borderRadius: 4, background: '#e5e7eb', animation: 'flopay-interim-pulse 1.5s ease-in-out infinite' }} />\n </div>\n <div style={{ display: 'flex' }}>\n <div style={{ flex: 1, backgroundColor: inputBg, border: `1px solid ${inputBorder}`, borderTop: 'none', borderRight: 'none', borderBottomLeftRadius: 8, padding: 12, height: 45 }}>\n <div style={{ width: '50%', height: 14, borderRadius: 4, background: '#e5e7eb', animation: 'flopay-interim-pulse 1.5s ease-in-out infinite' }} />\n </div>\n <div style={{ flex: 1, backgroundColor: inputBg, border: `1px solid ${inputBorder}`, borderTop: 'none', borderBottomRightRadius: 8, padding: 12, height: 45 }}>\n <div style={{ width: '40%', height: 14, borderRadius: 4, background: '#e5e7eb', animation: 'flopay-interim-pulse 1.5s ease-in-out infinite' }} />\n </div>\n </div>\n <div style={{ backgroundColor: inputBg, border: `1px solid ${inputBorder}`, borderRadius: 8, marginTop: 8, padding: 12, height: 45 }}>\n <div style={{ width: '45%', height: 14, borderRadius: 4, background: '#e5e7eb', animation: 'flopay-interim-pulse 1.5s ease-in-out infinite' }} />\n </div>\n <div style={{\n height: 50, borderRadius: 8, marginTop: 16, background: '#c8c8ff',\n animation: 'flopay-interim-pulse 1.5s ease-in-out infinite',\n ...bStyles.submitButton as React.CSSProperties,\n opacity: 0.5,\n }} />\n <style>{`\n @keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }\n @keyframes flopay-interim-expand {\n 0% { opacity: 0; max-height: 0; transform: translateY(-12px); }\n 40% { opacity: 1; }\n 100% { opacity: 1; max-height: 600px; transform: translateY(0); }\n }\n `}</style>\n </div>\n );\n }\n\n return (\n <div style={{ display: 'flex', flexDirection: 'column', gap: '0.5rem' }}>\n {showPayPal && skeleton(DEFAULT_BUTTONS_LAYOUT_BUTTON_HEIGHT)}\n {(showApplePay || showGooglePay) && skeleton(DEFAULT_BUTTONS_LAYOUT_BUTTON_HEIGHT)}\n <button\n type=\"button\"\n onClick={async () => {\n if (cardLoading) return;\n if (onCardButtonClick) {\n await onCardButtonClick();\n return;\n }\n onButtonClick?.('card');\n setShowCardForm(true);\n }}\n disabled={cardLoading}\n style={{\n width: '100%',\n ...cardButtonSizing,\n backgroundColor: 'white', color: '#262833',\n border: '1px solid #d1d5db', borderRadius: '8px',\n fontSize: bStyles.cardButtonFontSize ?? '0.95rem', fontWeight: 600,\n cursor: cardLoading ? 'not-allowed' : 'pointer', display: 'flex',\n alignItems: 'center', justifyContent: 'center', gap: '0.625rem',\n boxShadow: '0 1px 2px rgba(0,0,0,0.04)',\n transition: 'transform 0.1s',\n position: 'relative',\n opacity: cardLoading ? 0.6 : 1,\n ...bStyles.cardButton as React.CSSProperties,\n }}\n onMouseDown={(e) => { e.currentTarget.style.transform = 'scale(0.985)'; }}\n onMouseUp={(e) => { e.currentTarget.style.transform = 'scale(1)'; }}\n >\n <CardButtonContentSlot content={cardButtonContent} />\n </button>\n {errorMessage && (\n <div style={{\n margin: '0.25rem 0', padding: '0.625rem 0.875rem',\n background: '#FEF2F2', border: '1px solid #FECACA', borderRadius: '8px',\n color: '#991B1B', fontSize: '0.85rem', fontWeight: 600,\n display: 'flex', alignItems: 'center', gap: '0.5rem',\n ...(bStyles.errorBanner as React.CSSProperties | undefined),\n }}>\n <svg width=\"16\" height=\"16\" viewBox=\"0 0 24 24\" fill=\"none\" style={{ flexShrink: 0 }}>\n <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\" />\n </svg>\n {errorMessage}\n </div>\n )}\n <style>{`@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }`}</style>\n </div>\n );\n}\n","import React from 'react';\n\nexport function DefaultCardButtonContent(): React.ReactElement {\n return (\n <>\n <svg\n width=\"20\"\n height=\"20\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"1.5\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n aria-hidden=\"true\"\n >\n <rect width=\"20\" height=\"14\" x=\"2\" y=\"5\" rx=\"2\" />\n <line x1=\"2\" x2=\"22\" y1=\"10\" y2=\"10\" />\n </svg>\n Credit / Debit Card\n <svg\n width=\"16\"\n height=\"16\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"#9ca3af\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n style={{ position: 'absolute', right: '1rem' }}\n aria-hidden=\"true\"\n >\n <path d=\"M9 18l6-6-6-6\" />\n </svg>\n </>\n );\n}\n\nexport function DefaultBackButtonContent(): React.ReactElement {\n return <>Go back</>;\n}\n\nexport function DefaultTitleContent(): React.ReactElement {\n return <>Secure card checkout</>;\n}\n\nexport function isEmptySlotContent(content: React.ReactNode | undefined): boolean {\n return content !== undefined && (content === '' || content === null || content === false);\n}\n\nexport function CardButtonContentSlot({\n content,\n}: {\n content?: React.ReactNode;\n}): React.ReactElement {\n return <>{content === undefined ? <DefaultCardButtonContent /> : content}</>;\n}\n\nexport function BackButtonContentSlot({\n content,\n}: {\n content?: React.ReactNode;\n}): React.ReactElement {\n return <>{content === undefined ? <DefaultBackButtonContent /> : content}</>;\n}\n\nexport function TitleContentSlot({\n content,\n}: {\n content?: React.ReactNode;\n}): React.ReactElement {\n return <>{content === undefined ? <DefaultTitleContent /> : content}</>;\n}\n","import React, { useEffect, useRef, useContext } from 'react';\nimport type { ElementType, ElementChangeEvent, ElementOptions, MountedElement } from '@flopay/shared';\nimport { FloPayContext } from './context.js';\n\n/** Common props shared by all element components. */\nexport interface ElementComponentProps {\n /** Additional CSS class for the wrapper div. */\n className?: string;\n /** Element id attribute for the wrapper div. */\n id?: string;\n /** Inline styles for the wrapper div. */\n style?: React.CSSProperties;\n /** Options forwarded to the underlying element. */\n options?: Partial<ElementOptions>;\n /** Fired when the element's value changes. */\n onChange?: (event: ElementChangeEvent) => void;\n /** Fired when the element is fully rendered and ready. */\n onReady?: () => void;\n /** Fired when the element gains focus. */\n onFocus?: () => void;\n /** Fired when the element loses focus. */\n onBlur?: () => void;\n /** Fired when the Escape key is pressed inside the element. */\n onEscape?: () => void;\n}\n\n/**\n * Generic element component factory.\n *\n * Each element component:\n * 1. Gets the Elements instance from context\n * 2. Creates the appropriate element type\n * 3. Mounts it to a ref'd container div\n * 4. Forwards events as props\n * 5. Cleans up on unmount\n *\n * TODO: In a future phase, each element will render inside an iframe\n * for PCI DSS SAQ-A compliance. For now, they wrap the provider's\n * elements directly.\n */\nfunction createElementComponent(\n elementType: ElementType,\n displayName: string,\n): React.FC<ElementComponentProps> {\n function ElementComponent({\n className,\n id,\n style,\n options,\n onChange,\n onReady,\n onFocus,\n onBlur,\n onEscape,\n }: ElementComponentProps) {\n const containerRef = useRef<HTMLDivElement>(null);\n const elementRef = useRef<MountedElement | null>(null);\n const { elements } = useContext(FloPayContext);\n\n useEffect(() => {\n if (!elements || !containerRef.current) return;\n\n let mounted = true;\n\n (async () => {\n // Reuse existing element if Stripe already created one of this type\n // (handles React Strict Mode double-mount).\n let element = elements.getElement(elementType);\n if (!element) {\n element = await elements.create(elementType, options);\n }\n\n if (!mounted || !containerRef.current) {\n return;\n }\n\n element.mount(containerRef.current);\n elementRef.current = element;\n\n if (onChange) element.on('change', onChange as (...args: unknown[]) => void);\n if (onReady) element.on('ready', onReady as (...args: unknown[]) => void);\n if (onFocus) element.on('focus', onFocus as (...args: unknown[]) => void);\n if (onBlur) element.on('blur', onBlur as (...args: unknown[]) => void);\n if (onEscape) element.on('escape', onEscape as (...args: unknown[]) => void);\n })();\n\n return () => {\n mounted = false;\n // Unmount only — don't destroy. Stripe Elements tracks elements\n // internally; destroying prevents reuse on Strict Mode remount.\n // Guard with try/catch: the element may already be destroyed if\n // the parent provider recreated the Elements group (e.g. on\n // appearance change).\n if (elementRef.current) {\n try {\n elementRef.current.unmount();\n } catch {\n // Element already destroyed — safe to ignore\n }\n elementRef.current = null;\n }\n };\n }, [elements]);\n\n return <div ref={containerRef} className={className} id={id} style={style} />;\n }\n\n ElementComponent.displayName = displayName;\n return ElementComponent;\n}\n\n/**\n * Renders the unified Payment Element — a single component that accepts\n * cards, wallets, and other payment methods.\n *\n * TODO: Will render inside an iframe for PCI compliance in a future phase.\n */\nexport const PaymentElement = createElementComponent('payment', 'PaymentElement');\n\n/**\n * Renders a combined card input (number + expiry + CVC).\n *\n * TODO: Will render inside an iframe for PCI compliance in a future phase.\n */\nexport const CardElement = createElementComponent('card', 'CardElement');\n\n/**\n * Renders a card number input field.\n *\n * TODO: Will render inside an iframe for PCI compliance in a future phase.\n */\nexport const CardNumberElement = createElementComponent('cardNumber', 'CardNumberElement');\n\n/**\n * Renders a card expiry input field.\n *\n * TODO: Will render inside an iframe for PCI compliance in a future phase.\n */\nexport const CardExpiryElement = createElementComponent('cardExpiry', 'CardExpiryElement');\n\n/**\n * Renders a card CVC input field.\n *\n * TODO: Will render inside an iframe for PCI compliance in a future phase.\n */\nexport const CardCvcElement = createElementComponent('cardCvc', 'CardCvcElement');\n\n/**\n * Renders an address input element.\n */\nexport const AddressElement = createElementComponent('address', 'AddressElement');\n","import {\n CardCvcElement,\n CardExpiryElement,\n CardNumberElement,\n} from './elements.js';\nimport {\n ExpressCheckoutElement,\n Elements as StripeElements,\n useElements as useStripeElements,\n useStripe as useStripeRaw,\n} from '@stripe/react-stripe-js';\nimport type {\n BeforeButtonClickEvent,\n CheckoutButtonMethod,\n DeclineEvent,\n InlineSessionPatch,\n PaymentResult,\n TokenizedBody,\n ButtonsLayoutStyles,\n AVSFieldConfig,\n} from '@flopay/shared';\nimport {\n resolveButtonsLayoutTheme,\n getPostalCodeLabel,\n getStateLabel,\n getStateOptions,\n COUNTRY_OPTIONS,\n resolveAVSConfig,\n isAVSFieldVisible,\n getStateFromPostalCode,\n} from '@flopay/shared';\nimport React, { forwardRef, useCallback, useContext, useEffect, useImperativeHandle, useMemo, useRef, useState } from 'react';\nimport type {\n Stripe,\n StripeExpressCheckoutElementConfirmEvent,\n StripeExpressCheckoutElementReadyEvent,\n} from '@stripe/stripe-js';\nimport { useBillingApiUrl, useElements, useFloPay, usePayPalFloPay } from './hooks.js';\nimport { CheckoutContext } from './context.js';\nimport {\n BackButtonContentSlot,\n CardButtonContentSlot,\n TitleContentSlot,\n isEmptySlotContent,\n} from './card-button-content.js';\nimport {\n PROCESSING_OVERLAY_ERROR_DELAY_MS,\n PROCESSING_OVERLAY_SUCCESS_DELAY_MS,\n ProcessingOverlay,\n type OverlayStatus,\n} from './processing-overlay.js';\nimport {\n buildDeclineEvent,\n buildFloPayApiErrorFromResponse,\n mergeAccountPatch,\n resolvePaymentIntentPaymentMethodId,\n resolveTokenizedPaymentMethodId,\n retrievePaymentIntentFromProvider,\n} from './checkout-utils.js';\nimport { markSessionRecentlyCompleted } from './recent-completion.js';\nimport { InAppBrowserNotice } from './in-app-browser-notice.js';\nimport { isInAppBrowser } from './in-app-browser.js';\n\nimport { FloPayError } from '@flopay/shared';\n\n/** localStorage key for persisting wallet payment state across redirects. */\nconst WALLET_RESUME_KEY = 'flopay_wallet_resume';\n\ntype MaybePromise<T> = T | Promise<T>;\n\n// ─── Global keyframes (always present — not gated behind overlay render) ────\n\nconst FLOPAY_KEYFRAMES = `\n@keyframes flopay-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }\n@keyframes flopay-fade-in { 0% { opacity: 0; } 100% { opacity: 1; } }\n@keyframes flopay-buttons-enter {\n 0% { opacity: 0; transform: translateX(-16px) scale(0.97); }\n 100% { opacity: 1; transform: translateX(0) scale(1); }\n}\n@keyframes flopay-buttons-exit {\n 0% { opacity: 1; transform: translateX(0) scale(1); }\n 100% { opacity: 0; transform: translateX(-16px) scale(0.97); }\n}\n@keyframes flopay-card-enter {\n 0% { opacity: 0; transform: translateX(16px) scale(0.97); }\n 100% { opacity: 1; transform: translateX(0) scale(1); }\n}\n@keyframes flopay-card-exit {\n 0% { opacity: 1; transform: translateX(0) scale(1); }\n 100% { opacity: 0; transform: translateX(16px) scale(0.97); }\n}\n`;\n\nconst DEFAULT_BUTTONS_LAYOUT_BUTTON_HEIGHT = 44;\n\ntype TokenizedBodyOverrides = {\n accountPatch?: InlineSessionPatch['account'];\n completionPaymentMethodId?: string;\n sessionId?: string;\n};\n\ntype InternalTokenizedBodyHandler = (\n body: TokenizedBody,\n overrides?: TokenizedBodyOverrides,\n) => void;\n\ntype BeforeButtonClickPatchResult = {\n error: FloPayError | null;\n sessionId?: string;\n};\n\ntype BeforeButtonClickResult = {\n proceed: boolean;\n accountPatch?: InlineSessionPatch['account'];\n sessionId?: string;\n};\n\ntype RunBeforeButtonClick = (method: CheckoutButtonMethod) => Promise<BeforeButtonClickResult>;\n\nfunction getButtonMethodLabel(method: CheckoutButtonMethod): string {\n switch (method) {\n case 'paypal': return 'PayPal';\n case 'apple_pay': return 'Apple Pay';\n case 'google_pay': return 'Google Pay';\n default: return 'Card';\n }\n}\n\nfunction normalizeBeforeButtonClickError(\n method: CheckoutButtonMethod,\n err: unknown,\n): FloPayError {\n return err instanceof FloPayError\n ? err\n : new FloPayError(\n err instanceof Error ? err.message : `${getButtonMethodLabel(method)} before-click hook failed.`,\n 'validation_error',\n );\n}\n\nfunction FloPayKeyframes() {\n return <style>{FLOPAY_KEYFRAMES}</style>;\n}\n\nfunction toCssSize(value: string | number | undefined): string | undefined {\n if (typeof value === 'number') return `${value}px`;\n return value;\n}\n\nfunction toCssWeight(value: string | number | undefined): string | number | undefined {\n if (typeof value === 'number' || typeof value === 'string') return value;\n return undefined;\n}\n\n/**\n * Express-checkout element load states.\n *\n * - `loading`: initial — waiting for ExpressCheckoutElement's `ready` event.\n * - `ready`: at least one of the requested methods is available on this\n * device. Element renders.\n * - `unavailable`: the element initialized fine but `availablePaymentMethods`\n * reported none of the requested methods. The interpretation of this state\n * is method-dependent — see the notice trigger below.\n * - `load_error`: Stripe's `onLoadError` fired — the element couldn't\n * initialize at all (script blocked, network failure).\n */\ntype ExpressCheckoutLoadState = 'loading' | 'ready' | 'unavailable' | 'load_error';\n\nfunction resolveExpressCheckoutLoadState(\n event: StripeExpressCheckoutElementReadyEvent,\n methods: Array<'paypal' | 'applePay' | 'googlePay'>,\n): ExpressCheckoutLoadState {\n const available = event.availablePaymentMethods;\n if (!available) return 'unavailable';\n\n return methods.some((method) => available[method]) ? 'ready' : 'unavailable';\n}\n\nfunction ExpressCheckoutReadySwap({\n state,\n placeholderTestId,\n children,\n}: {\n state: ExpressCheckoutLoadState;\n placeholderTestId?: string;\n children: React.ReactNode;\n}) {\n if (state === 'unavailable' || state === 'load_error') return null;\n\n return (\n <div style={{ position: 'relative', minHeight: 44 }}>\n <div\n data-testid={placeholderTestId}\n aria-hidden={state === 'ready'}\n style={{\n position: 'absolute',\n inset: 0,\n height: 44,\n borderRadius: 8,\n background: '#e5e7eb',\n animation: state === 'ready' ? undefined : 'flopay-pulse 1.5s ease-in-out infinite',\n opacity: state === 'ready' ? 0 : 1,\n transform: state === 'ready' ? 'scale(0.985)' : 'scale(1)',\n transition: 'opacity 140ms ease-out, transform 140ms ease-out',\n pointerEvents: 'none',\n }}\n />\n <div\n style={{\n minHeight: 44,\n opacity: state === 'ready' ? 1 : 0,\n transform: state === 'ready' ? 'translateY(0)' : 'translateY(2px)',\n transition: 'opacity 140ms ease-out, transform 140ms ease-out',\n pointerEvents: state === 'ready' ? 'auto' : 'none',\n }}\n >\n {children}\n </div>\n </div>\n );\n}\n\n/** Methods exposed via ref for external 3DS handling. */\nexport interface SplitCardFormRef {\n handleNextAction: (clientSecret: string) => Promise<void>;\n}\n\n/** Props for the `SplitCardForm` component. */\nexport interface SplitCardFormProps {\n /** The checkout session ID (UUID from billing API). */\n sessionId: string;\n /** Billing API base URL. Optional — defaults to the value from FloPayProvider or the shared constant. */\n billingApiUrl?: string;\n /** User's email (required for creating payment intents). */\n email?: string;\n /** User ID (required for processing payments). */\n userId?: string;\n /** Called when the full payment flow completes successfully. */\n onComplete?: (result: PaymentResult) => void;\n /** Called when a payment error occurs. */\n onError?: (error: FloPayError) => void;\n /** Called when a payment is declined or the authentication step fails. */\n onDecline?: (decline: DeclineEvent) => void;\n /**\n * **Override**: If provided, delegates backend submission to the caller.\n * When omitted, processes internally (calls processPayment + handles 3DS).\n */\n onTokenizedBody?: (tokenizedBody: TokenizedBody) => void;\n /** First name for billing. */\n firstName?: string;\n /** Last name for billing. */\n lastName?: string;\n /** Checkout version for A/B tracking. */\n chv?: string;\n /** Label for the submit button. */\n submitLabel?: string;\n /** Additional CSS class for the form wrapper. */\n className?: string;\n /** Custom children (overrides default submit button). */\n children?: React.ReactNode;\n /** External processing state. */\n isProcessing?: boolean;\n /** External error message. */\n error?: string | null;\n /** Called when internal error state changes. */\n onErrorChange?: (error: string | null) => void;\n /** Callback when the full cardholder name input changes. */\n onFullNameChange?: (value: string) => void;\n /** Callback when first name changes (from the name input). */\n onFirstNameChange?: (value: string) => void;\n /** Callback when last name changes (from the name input). */\n onLastNameChange?: (value: string) => void;\n /**\n * Show PayPal button above card fields. Defaults to `true`.\n * Uses Stripe's ExpressCheckoutElement in a separate Elements instance,\n * matching checkout/StripeCardForm architecture.\n */\n showPayPal?: boolean;\n /** Show Apple Pay button. Defaults to `true`. Only renders on supported devices. */\n showApplePay?: boolean;\n /** Show Google Pay button. Defaults to `true`. Only renders on supported devices. */\n showGooglePay?: boolean;\n /**\n * Layout mode for the payment form.\n * - `'default'` — all payment methods + card form shown together (current behavior)\n * - `'buttons'` — PayPal, wallets, and a \"Credit / Debit Card\" button; clicking the card\n * button expands the card form with a back button to return to the button view\n */\n layout?: 'default' | 'buttons';\n /**\n * Theme preset for the `buttons` layout. Ignored when `layout` is `'default'`.\n * - `'default'` — white card button, neutral borders\n * - `'minimal'` — borderless, subtle backgrounds\n * - `'rounded'` — large border radius, soft shadows\n * - `'dark'` — dark backgrounds, light text\n */\n buttonsTheme?: import('@flopay/shared').ButtonsLayoutTheme;\n /** Custom style overrides for the `buttons` layout. Merged on top of the theme preset. */\n buttonsStyles?: import('@flopay/shared').ButtonsLayoutStyles;\n /** Custom React content rendered inside the card button when `layout=\"buttons\"`. */\n cardButtonContent?: React.ReactNode;\n /** Custom React content rendered for the buttons-layout card back button label. */\n cardBackButtonContent?: React.ReactNode;\n /** Custom React content rendered for the card-form title. */\n cardTitleContent?: React.ReactNode;\n /** Whether to show the default security footer in `layout=\"default\"`. Defaults to `true`. */\n showSecurityFooter?: boolean;\n /**\n * Called when a payment method button is clicked.\n * `method`: `'card'` | `'paypal'` | `'apple_pay'` | `'google_pay'`\n */\n onButtonClick?: (method: CheckoutButtonMethod) => void;\n /**\n * Called before a payment button continues in `layout=\"buttons\"`.\n * Runs for card, PayPal, Apple Pay, and Google Pay.\n */\n onBeforeButtonClick?: (\n event: BeforeButtonClickEvent,\n ) => MaybePromise<void | false | InlineSessionPatch>;\n /**\n * Enable AVS (Address Verification).\n * - `true` — show country + postal code (backward compatible default)\n * - `AVSFieldConfig` — granular per-field control, optionally scoped to country codes\n * - `false` / omitted — AVS disabled\n */\n enableAVS?: boolean | AVSFieldConfig;\n /** Layout for AVS fields: 'row' (side-by-side, default) or 'column' (stacked). */\n avsLayout?: 'row' | 'column';\n /** Pre-filled country code (ISO 3166-1 alpha-2) for AVS. */\n country?: string;\n /** Pre-filled ZIP/postal code for AVS. */\n zip?: string;\n /** Pre-filled street address (line 1) for AVS. Typically from a partner GeoIP / profile lookup. */\n addressLine1?: string;\n /** Pre-filled apt/suite/unit (line 2) for AVS. */\n addressLine2?: string;\n /** Pre-filled city for AVS. Typically from a partner GeoIP / profile lookup. */\n city?: string;\n /** Pre-filled state/province for AVS. Typically from a partner GeoIP / profile lookup. */\n state?: string;\n /** Callback when AVS country changes. */\n onCountryChange?: (country: string) => void;\n /** Callback when AVS ZIP/postal code changes. */\n onZipChange?: (zip: string) => void;\n // ── Checkout analytics metadata ──\n /** Whether AVS was enabled (sent to backend for analytics). */\n avsCheck?: boolean;\n /** Checkout type: 'standard_checkout' or 'embedded_checkout'. */\n checkoutType?: string;\n /** Checkout layout: 'default_layout', 'buttons_layout', or 'custom_layout'. */\n checkoutLayout?: string;\n /** Total amount in cents (smallest currency unit). Used for wallet/PayPal Elements config. */\n totalAmount?: number;\n /** Currency code (used for PayPal Elements config). */\n currency?: string;\n /** Render the card form expanded on first paint when `layout=\"buttons\"`. */\n initialCardOpen?: boolean;\n}\n\n/**\n * Split card checkout form matching `checkout/StripeCardForm`:\n * PayPal button → divider → CardNumber → CardExpiry + CardCVC → Full Name → Submit.\n *\n * PayPal uses its own Stripe Elements instance (no `paymentMethodCreation`)\n * exactly like checkout does with two separate `<Elements>` wrappers.\n */\nexport const SplitCardForm = forwardRef<SplitCardFormRef, SplitCardFormProps>(\n function SplitCardForm(props, ref) {\n return <SplitCardFormInner {...props} innerRef={ref} />;\n },\n);\n\n// ─── PayPal button (own Elements instance) ──────────────────────────────────\n// Mirrors checkout/StripeCardForm's StripePayPalButtonInner exactly.\n\nfunction PayPalButtonInner({\n sessionId,\n email,\n billingApiUrl,\n onTokenizedBody,\n onErrorChange,\n isProcessing = false,\n onButtonClick,\n onDecline,\n runBeforeButtonClick,\n onLoadStateChange,\n}: {\n sessionId: string;\n email?: string;\n billingApiUrl: string;\n onTokenizedBody: InternalTokenizedBodyHandler;\n onErrorChange?: (error: string | null) => void;\n isProcessing?: boolean;\n onButtonClick?: (method: CheckoutButtonMethod) => void;\n onDecline?: (decline: DeclineEvent) => void;\n runBeforeButtonClick?: RunBeforeButtonClick;\n onLoadStateChange?: (state: ExpressCheckoutLoadState) => void;\n}) {\n const stripe = useStripeRaw();\n const elements = useStripeElements();\n const [loadState, setLoadState] = useState<ExpressCheckoutLoadState>('loading');\n const onLoadStateChangeRef = useRef(onLoadStateChange);\n useEffect(() => {\n onLoadStateChangeRef.current = onLoadStateChange;\n }, [onLoadStateChange]);\n useEffect(() => {\n onLoadStateChangeRef.current?.(loadState);\n }, [loadState]);\n const [submitting, setSubmitting] = useState(false);\n const paypalResumeAttempted = useRef(false);\n const beforeClickRef = useRef<{\n accountPatch?: InlineSessionPatch['account'];\n sessionId?: string;\n } | null>(null);\n const baseUrl = billingApiUrl.replace(/\\/+$/, '');\n\n // Resume PayPal redirect return — detect payment_intent in URL\n useEffect(() => {\n if (!stripe || paypalResumeAttempted.current) return;\n\n const params = new URLSearchParams(window.location.search);\n const paymentIntentId = params.get('payment_intent');\n const clientSecret = params.get('payment_intent_client_secret');\n const redirectStatus = params.get('redirect_status');\n\n if (!paymentIntentId || !clientSecret) return;\n paypalResumeAttempted.current = true;\n\n // Strip Stripe's PayPal-redirect params from the URL up front, before any\n // async work. The resume `useRef` guard above is reset on remount — if a\n // remount races our async resume, the only way to stop it from re-firing\n // for the same PI is to make sure the URL no longer signals \"we're inside\n // a resume.\" Doing this synchronously (rather than only after a successful\n // /process) closes that re-entry window for every branch below.\n const cleanedUrl = new URL(window.location.href);\n cleanedUrl.searchParams.delete('payment_intent');\n cleanedUrl.searchParams.delete('payment_intent_client_secret');\n cleanedUrl.searchParams.delete('redirect_status');\n window.history.replaceState({}, '', cleanedUrl.toString());\n\n (async () => {\n try {\n setSubmitting(true);\n\n if (redirectStatus === 'failed') {\n const message = 'PayPal payment was declined. Please try again.';\n onErrorChange?.(message);\n onDecline?.(buildDeclineEvent('paypal', message));\n return;\n }\n\n const { paymentIntent, error } = await stripe.retrievePaymentIntent(clientSecret);\n if (error) {\n onErrorChange?.(error.message ?? 'Failed to retrieve PayPal payment status.');\n return;\n }\n\n if (paymentIntent && (paymentIntent.status === 'requires_capture' || paymentIntent.status === 'succeeded')) {\n const paymentMethodId = typeof paymentIntent.payment_method === 'string'\n ? paymentIntent.payment_method\n : paymentIntent.payment_method?.id;\n\n onTokenizedBody({\n id: paymentMethodId ?? paymentIntent.id,\n type: 'card',\n threeDSecureActionResultTokenId: paymentIntent.id,\n isPaypal: true,\n });\n } else {\n const message = 'PayPal payment was not completed. Please try again.';\n onErrorChange?.(message);\n onDecline?.(buildDeclineEvent('paypal', message));\n }\n } catch (err) {\n onErrorChange?.(err instanceof Error ? err.message : 'Failed to complete PayPal payment.');\n } finally {\n setSubmitting(false);\n }\n })();\n }, [stripe, onTokenizedBody, onErrorChange, onDecline]);\n\n const handlePayPalClick = useCallback(async (\n event: { resolve: () => void; reject: () => void },\n ) => {\n if (isProcessing || submitting) {\n event.reject();\n return;\n }\n\n const beforeClick = runBeforeButtonClick\n ? await runBeforeButtonClick('paypal')\n : { proceed: true } as BeforeButtonClickResult;\n\n if (!beforeClick.proceed) {\n beforeClickRef.current = null;\n event.reject();\n return;\n }\n\n beforeClickRef.current = {\n accountPatch: beforeClick.accountPatch,\n sessionId: beforeClick.sessionId,\n };\n onButtonClick?.('paypal');\n event.resolve();\n }, [isProcessing, onButtonClick, runBeforeButtonClick, submitting]);\n\n // PayPal confirm handler — called by ExpressCheckoutElement onConfirm\n const handlePayPalConfirm = useCallback(async (event: StripeExpressCheckoutElementConfirmEvent) => {\n if (!stripe || !elements) return;\n\n let prepared = beforeClickRef.current;\n beforeClickRef.current = null;\n\n if (!prepared && runBeforeButtonClick) {\n const beforeClick = await runBeforeButtonClick('paypal');\n if (!beforeClick.proceed) {\n event.paymentFailed({ reason: 'fail', message: 'PayPal checkout was cancelled.' });\n return;\n }\n prepared = {\n accountPatch: beforeClick.accountPatch,\n sessionId: beforeClick.sessionId,\n };\n }\n\n const effectiveSessionId = prepared?.sessionId ?? sessionId;\n const effectiveEmail = prepared?.accountPatch?.email ?? email;\n\n try {\n setSubmitting(true);\n onErrorChange?.(null);\n\n if (!effectiveSessionId || !effectiveEmail) {\n throw new Error('Missing sessionId or email for PayPal payment');\n }\n\n const createPM = stripe.createPaymentMethod as unknown as (\n params: { type: string },\n ) => Promise<{ error?: { message?: string }; paymentMethod?: { id: string } }>;\n\n const { error: pmError, paymentMethod } = await createPM({ type: 'paypal' });\n if (pmError) {\n const message = pmError.message ?? 'PayPal payment failed.';\n onErrorChange?.(message);\n event.paymentFailed({ reason: 'fail', message });\n return;\n }\n\n // 1. Create PaymentIntent via backend with the PayPal payment method.\n // isPaypal must be string 'true' — backend checks === 'true'.\n\n const intentResponse = await fetch(`${baseUrl}/v1/checkouts/payments/intents`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n sessionId: effectiveSessionId,\n email: effectiveEmail,\n paymentMethodType: paymentMethod?.id ?? 'paypal',\n isPaypal: 'true',\n setupFutureUsage: 'off_session',\n setup_future_usage: 'off_session',\n }),\n });\n\n if (!intentResponse.ok) {\n const intentError = await buildFloPayApiErrorFromResponse(\n intentResponse,\n 'Failed to create payment intent',\n );\n onErrorChange?.(intentError.message);\n onDecline?.(buildDeclineEvent('paypal', intentError));\n event.paymentFailed({ reason: 'fail', message: intentError.message });\n return;\n }\n const intentJson = await intentResponse.json() as { data?: { id?: string } };\n const intentClientSecret = intentJson.data?.id;\n if (!intentClientSecret) throw new Error('No client_secret in payment intent response');\n\n // 2. Confirm payment — PayPal will redirect or complete inline.\n const confirmParams: Record<string, unknown> = {\n return_url: window.location.href,\n };\n if (paymentMethod?.id) {\n confirmParams['payment_method'] = paymentMethod.id;\n }\n\n const { error: confirmError, paymentIntent } = await stripe.confirmPayment({\n clientSecret: intentClientSecret,\n confirmParams: confirmParams as { return_url: string },\n redirect: 'if_required',\n });\n\n if (confirmError) {\n const message = confirmError.message ?? 'PayPal payment failed.';\n onErrorChange?.(message);\n onDecline?.(buildDeclineEvent('paypal', message, {\n code: confirmError.code,\n }));\n return;\n }\n\n const confirmedPmId = typeof paymentIntent?.payment_method === 'string'\n ? paymentIntent.payment_method\n : paymentIntent?.payment_method?.id;\n\n onTokenizedBody({\n id: confirmedPmId ?? paymentIntent?.id,\n type: 'card',\n threeDSecureActionResultTokenId: paymentIntent?.id,\n isPaypal: true,\n }, {\n accountPatch: prepared?.accountPatch,\n sessionId: effectiveSessionId,\n });\n return;\n } catch (err) {\n onErrorChange?.(err instanceof Error ? err.message : 'PayPal payment failed. Please try again.');\n } finally {\n setSubmitting(false);\n }\n }, [stripe, elements, sessionId, email, baseUrl, onTokenizedBody, onErrorChange, onDecline, runBeforeButtonClick]);\n\n return (\n <>\n <ExpressCheckoutReadySwap state={loadState} placeholderTestId=\"flopay-paypal-placeholder\">\n <ExpressCheckoutElement\n onReady={(event) => setLoadState(resolveExpressCheckoutLoadState(event, ['paypal']))}\n onLoadError={() => setLoadState('load_error')}\n onClick={handlePayPalClick}\n onConfirm={handlePayPalConfirm}\n onCancel={() => {\n beforeClickRef.current = null;\n onDecline?.(buildDeclineEvent('paypal', 'PayPal checkout was cancelled.'));\n }}\n options={{\n buttonType: { paypal: 'paypal' } as Record<string, string>,\n billingAddressRequired: false,\n phoneNumberRequired: false,\n shippingAddressRequired: false,\n paymentMethods: {\n applePay: 'never',\n googlePay: 'never',\n paypal: 'auto',\n link: 'never',\n },\n } as Parameters<typeof ExpressCheckoutElement>[0]['options']}\n />\n </ExpressCheckoutReadySwap>\n {submitting && <ProcessingOverlay status=\"processing\" />}\n </>\n );\n}\n\n// ─── Wallet buttons (Apple Pay / Google Pay — own Elements instance) ────────\n// Uses raw stripe + elements from its own StripeElements context,\n// matching checkout/StripeCardForm's handleExpressCheckoutConfirm exactly.\n\nfunction WalletButtonInner({\n sessionId,\n email,\n billingApiUrl,\n showApplePay = true,\n showGooglePay = true,\n onTokenizedBody,\n onErrorChange,\n onButtonClick,\n onDecline,\n runBeforeButtonClick,\n onLoadStateChange,\n}: {\n sessionId: string;\n email?: string;\n billingApiUrl: string;\n showApplePay?: boolean;\n showGooglePay?: boolean;\n onTokenizedBody: InternalTokenizedBodyHandler;\n onErrorChange?: (error: string | null) => void;\n onButtonClick?: (method: CheckoutButtonMethod) => void;\n onDecline?: (decline: DeclineEvent) => void;\n runBeforeButtonClick?: RunBeforeButtonClick;\n onLoadStateChange?: (state: ExpressCheckoutLoadState) => void;\n}) {\n const stripe = useStripeRaw();\n const elements = useStripeElements();\n const [loadState, setLoadState] = useState<ExpressCheckoutLoadState>('loading');\n const onLoadStateChangeRef = useRef(onLoadStateChange);\n useEffect(() => {\n onLoadStateChangeRef.current = onLoadStateChange;\n }, [onLoadStateChange]);\n useEffect(() => {\n onLoadStateChangeRef.current?.(loadState);\n }, [loadState]);\n const [submitting, setSubmitting] = useState(false);\n const baseUrl = billingApiUrl.replace(/\\/+$/, '');\n const lastWalletMethodRef = useRef<CheckoutButtonMethod>('card');\n const beforeClickRef = useRef<{\n accountPatch?: InlineSessionPatch['account'];\n sessionId?: string;\n } | null>(null);\n\n const handleWalletConfirm = useCallback(\n async (event: StripeExpressCheckoutElementConfirmEvent) => {\n if (!stripe || !elements) return;\n\n // Detect wallet type from the express checkout event\n const walletType = (event as unknown as { expressPaymentType?: string }).expressPaymentType;\n let prepared = beforeClickRef.current;\n beforeClickRef.current = null;\n\n if (!prepared && runBeforeButtonClick) {\n const beforeClick = await runBeforeButtonClick(\n walletType === 'apple_pay' ? 'apple_pay' : 'google_pay',\n );\n if (!beforeClick.proceed) {\n event.paymentFailed({ reason: 'fail', message: 'Wallet checkout was cancelled.' });\n return;\n }\n prepared = {\n accountPatch: beforeClick.accountPatch,\n sessionId: beforeClick.sessionId,\n };\n }\n\n const method = walletType === 'apple_pay' ? 'apple_pay' : 'google_pay';\n const effectiveSessionId = prepared?.sessionId ?? sessionId;\n const effectiveEmail = prepared?.accountPatch?.email ?? email;\n\n try {\n setSubmitting(true);\n onErrorChange?.(null);\n\n // 1. Submit elements (validates wallet payment sheet)\n const { error: submitError } = await elements.submit();\n if (submitError) {\n onErrorChange?.(submitError.message ?? 'Wallet payment failed.');\n return;\n }\n\n // 2. Create PaymentMethod from wallet token via the wallet's own Elements\n const { error: pmError, paymentMethod } = await stripe.createPaymentMethod({ elements });\n if (pmError || !paymentMethod) {\n onErrorChange?.(pmError?.message ?? 'Failed to create payment method.');\n return;\n }\n\n if (!effectiveSessionId || !effectiveEmail) {\n throw new Error('Missing sessionId or email for wallet payment');\n }\n\n // 3. Create PaymentIntent via backend\n const intentResponse = await fetch(`${baseUrl}/v1/checkouts/payments/intents`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n sessionId: effectiveSessionId,\n email: effectiveEmail,\n paymentMethodType: paymentMethod.id,\n isPaypal: false,\n }),\n });\n\n if (!intentResponse.ok) {\n const intentError = await buildFloPayApiErrorFromResponse(\n intentResponse,\n 'Failed to create payment intent',\n );\n onErrorChange?.(intentError.message);\n onDecline?.(buildDeclineEvent(method, intentError));\n event.paymentFailed({ reason: 'fail', message: intentError.message });\n return;\n }\n const intentJson = await intentResponse.json() as { data?: { id?: string } };\n const intentClientSecret = intentJson.data?.id;\n if (!intentClientSecret) throw new Error('No client_secret in payment intent response');\n\n // 4. Confirm card payment (handles 3DS automatically)\n const { error: confirmError, paymentIntent } = await stripe.confirmCardPayment(\n intentClientSecret,\n { payment_method: paymentMethod.id },\n );\n\n if (confirmError) {\n const message = confirmError.message ?? 'Wallet payment failed.';\n onErrorChange?.(message);\n onDecline?.(buildDeclineEvent(method, message, {\n code: confirmError.code,\n }));\n return;\n }\n\n // 5. Send PM + PI to process endpoint\n onTokenizedBody({\n id: paymentMethod.id,\n type: 'card',\n threeDSecureActionResultTokenId: paymentIntent?.id,\n }, {\n accountPatch: prepared?.accountPatch,\n sessionId: effectiveSessionId,\n });\n } catch (err) {\n onErrorChange?.(err instanceof Error ? err.message : 'Wallet payment failed. Please try again.');\n } finally {\n setSubmitting(false);\n }\n },\n [stripe, elements, sessionId, email, baseUrl, onTokenizedBody, onErrorChange, onDecline, runBeforeButtonClick],\n );\n\n return (\n <>\n <ExpressCheckoutReadySwap state={loadState} placeholderTestId=\"flopay-wallet-placeholder\">\n <ExpressCheckoutElement\n onReady={(event) => setLoadState(resolveExpressCheckoutLoadState(event, ['applePay', 'googlePay']))}\n onLoadError={() => setLoadState('load_error')}\n onClick={async (event) => {\n lastWalletMethodRef.current = event.expressPaymentType === 'apple_pay' ? 'apple_pay' : 'google_pay';\n\n const beforeClick = runBeforeButtonClick\n ? await runBeforeButtonClick(lastWalletMethodRef.current)\n : { proceed: true } as BeforeButtonClickResult;\n\n if (!beforeClick.proceed) {\n beforeClickRef.current = null;\n event.reject();\n return;\n }\n\n beforeClickRef.current = {\n accountPatch: beforeClick.accountPatch,\n sessionId: beforeClick.sessionId,\n };\n onButtonClick?.(lastWalletMethodRef.current);\n event.resolve();\n }}\n onConfirm={handleWalletConfirm}\n onCancel={() => {\n beforeClickRef.current = null;\n onDecline?.(buildDeclineEvent(lastWalletMethodRef.current, 'Wallet checkout was cancelled.'));\n }}\n options={{\n buttonType: { applePay: 'plain', googlePay: 'plain' } as Record<string, string>,\n paymentMethods: {\n applePay: showApplePay ? 'always' : 'never',\n googlePay: showGooglePay ? 'always' : 'never',\n paypal: 'never',\n link: 'never',\n amazonPay: 'never',\n klarna: 'never',\n },\n layout: { maxColumns: 1, overflow: 'never' },\n } as Parameters<typeof ExpressCheckoutElement>[0]['options']}\n />\n </ExpressCheckoutReadySwap>\n {submitting && <ProcessingOverlay status=\"processing\" />}\n </>\n );\n}\n\n// ─── Main form ──────────────────────────────────────────────────────────────\n\nfunction SplitCardFormInner({\n sessionId,\n billingApiUrl,\n email,\n userId,\n onComplete,\n onError,\n onDecline,\n onTokenizedBody,\n firstName,\n lastName,\n chv,\n submitLabel = 'CONFIRM PAYMENT',\n className,\n children,\n isProcessing: externalProcessing,\n error: externalError,\n onErrorChange,\n onFullNameChange,\n onFirstNameChange,\n onLastNameChange,\n showPayPal = true,\n showApplePay = true,\n showGooglePay = true,\n layout = 'default',\n buttonsTheme,\n buttonsStyles: buttonsStylesOverride,\n cardButtonContent,\n cardBackButtonContent,\n cardTitleContent,\n showSecurityFooter = true,\n onButtonClick,\n onBeforeButtonClick,\n enableAVS: enableAVSProp,\n avsLayout: avsLayoutProp = 'row',\n country: countryProp,\n zip: zipProp,\n addressLine1: addressLine1Prop,\n addressLine2: addressLine2Prop,\n city: cityProp,\n state: stateProp,\n onCountryChange,\n onZipChange,\n avsCheck: avsCheckProp,\n checkoutType: checkoutTypeProp,\n checkoutLayout: checkoutLayoutProp,\n totalAmount = 0,\n currency = 'usd',\n initialCardOpen = false,\n innerRef,\n}: SplitCardFormProps & { innerRef: React.Ref<SplitCardFormRef> }) {\n const flopay = useFloPay();\n const paypalFlopay = usePayPalFloPay();\n const elements = useElements();\n const checkout = useContext(CheckoutContext);\n const contextBillingUrl = useBillingApiUrl();\n const [processing, setProcessing] = useState(false);\n const [error, setError] = useState<string | null>(null);\n const [is3DSActive, setIs3DSActive] = useState(false);\n const [selectedCountry, setSelectedCountry] = useState(countryProp ?? 'US');\n const [zipCode, setZipCode] = useState(zipProp ?? '');\n const [addressLine1, setAddressLine1] = useState(addressLine1Prop ?? '');\n const [addressLine2, setAddressLine2] = useState(addressLine2Prop ?? '');\n const [city, setCity] = useState(cityProp ?? '');\n const [stateValue, setStateValue] = useState(stateProp ?? '');\n const [accountPatch, setAccountPatch] = useState<InlineSessionPatch['account']>({});\n const zipCodeRef = useRef(zipProp ?? '');\n const selectedCountryRef = useRef(countryProp ?? 'US');\n const addressLine1Ref = useRef(addressLine1Prop ?? '');\n const addressLine2Ref = useRef(addressLine2Prop ?? '');\n const cityRef = useRef(cityProp ?? '');\n const stateRef = useRef(stateProp ?? '');\n\n // Resolve AVS config: boolean → default config, object → as-is, falsy → null\n const avsConfig = useMemo(() => resolveAVSConfig(enableAVSProp), [enableAVSProp]);\n const enableAVS = avsConfig !== null;\n\n // Buttons ↔ Card transition state machine\n type ViewState = 'buttons' | 'expanding' | 'card' | 'collapsing';\n const [viewState, setViewState] = useState<ViewState>(initialCardOpen ? 'card' : 'buttons');\n const showCardForm = viewState === 'expanding' || viewState === 'card';\n const TRANSITION_MS = 280;\n\n const expandToCard = useCallback(() => {\n setViewState('expanding');\n setTimeout(() => setViewState('card'), TRANSITION_MS);\n }, []);\n\n const collapseToButtons = useCallback(() => {\n setViewState('collapsing');\n setTimeout(() => setViewState('buttons'), TRANSITION_MS);\n }, []);\n\n useEffect(() => {\n if (layout === 'buttons' && initialCardOpen) {\n setViewState('card');\n }\n }, [layout, initialCardOpen]);\n const [fullName, setFullName] = useState('');\n const [formReady, setFormReady] = useState(false);\n const [overlayStatus, setOverlayStatus] = useState<OverlayStatus | null>(null);\n const processingRef = useRef(false);\n\n const resolvedBillingApiUrl = billingApiUrl || contextBillingUrl;\n const displayError = externalError ?? error;\n\n // Resolve buttons layout styles: theme preset merged with custom overrides\n const bStyles = useMemo<ButtonsLayoutStyles>(() => {\n const base = resolveButtonsLayoutTheme(buttonsTheme);\n if (!buttonsStylesOverride) return base;\n return {\n ...base,\n ...buttonsStylesOverride,\n cardButton: { ...base.cardButton, ...buttonsStylesOverride.cardButton },\n cardFormContainer: { ...base.cardFormContainer, ...buttonsStylesOverride.cardFormContainer },\n backButton: { ...base.backButton, ...buttonsStylesOverride.backButton },\n backButtonIcon: { ...base.backButtonIcon, ...buttonsStylesOverride.backButtonIcon },\n submitButton: { ...base.submitButton, ...buttonsStylesOverride.submitButton },\n title: { ...base.title, ...buttonsStylesOverride.title },\n };\n }, [buttonsTheme, buttonsStylesOverride]);\n const isInlineSessionPatchProcessing = checkout.inlineSessionPatchProcessing ?? false;\n const isSubmitting = (externalProcessing ?? processing) || isInlineSessionPatchProcessing;\n const isSelfContained = !onTokenizedBody;\n const baseUrl = resolvedBillingApiUrl.replace(/\\/+$/, '');\n const resolvedAccount = useMemo(() => mergeAccountPatch({\n userId,\n email,\n firstName,\n lastName,\n country: countryProp,\n zip: zipProp,\n }, accountPatch), [userId, email, firstName, lastName, countryProp, zipProp, accountPatch]);\n\n // Get raw Stripe instance for wallet Elements provider (primary Stripe account).\n const stripeInstance = useMemo(() => {\n if (!flopay) return null;\n return flopay.getRawProvider() as Stripe | null;\n }, [flopay]);\n\n // Get raw Stripe instance for the PayPal Elements provider. PayPal lives on\n // the dedicated PayPal Stripe account (gatewayData.paypalPublishableKey).\n // When no PayPal FloPay is configured, PayPal is disabled entirely.\n const paypalStripeInstance = useMemo(() => {\n if (!paypalFlopay) return null;\n return paypalFlopay.getRawProvider() as Stripe | null;\n }, [paypalFlopay]);\n\n // totalAmount is in cents (smallest currency unit) when passed from FloPayCheckout.\n // Stripe Elements `amount` expects cents.\n const amountInCents = totalAmount || 100; // minimum 1 cent\n\n // Wallet (Apple/Google Pay) Elements options — uses paymentMethodCreation: 'manual'\n // to match the main card Elements, allowing explicit createPaymentMethod() calls.\n const walletOptions = useMemo(() => ({\n mode: 'payment' as const,\n amount: amountInCents,\n currency: currency.toLowerCase(),\n paymentMethodCreation: 'manual' as const,\n captureMethod: 'manual' as const,\n }), [amountInCents, currency]);\n\n // PayPal Elements options — no paymentMethodCreation (matches checkout)\n const paypalOptions = useMemo(() => ({\n mode: 'payment' as const,\n amount: amountInCents,\n currency: currency.toLowerCase(),\n captureMethod: 'manual' as const,\n setupFutureUsage: 'off_session' as const,\n }), [amountInCents, currency]);\n\n const updateError = useCallback(\n (err: string | null) => {\n setError(err);\n onErrorChange?.(err);\n },\n [onErrorChange],\n );\n\n const emitDecline = useCallback(\n (\n method: CheckoutButtonMethod,\n input: string | FloPayError,\n overrides?: { code?: string; declineCode?: string },\n ) => {\n onDecline?.(buildDeclineEvent(method, input, overrides));\n },\n [onDecline],\n );\n\n const showWallets = showApplePay || showGooglePay;\n\n // Track express-checkout availability so we can render a non-disruptive\n // notice when PayPal and wallets actually fail to load. Common cause: the\n // buyer is in an in-app browser (Instagram, Facebook, TikTok webviews) or\n // behind an ad-blocker that strips Stripe.js / payment-button hosts.\n //\n // Two signals drive the notice:\n //\n // 1. UA detection (`isInAppBrowser`). Proactive — fires before Stripe\n // even tries. Catches the common social-app WebViews where neither\n // `onLoadError` nor `availablePaymentMethods.paypal=false` is\n // guaranteed to surface (Stripe's iframe loads fine, PayPal's SDK\n // can't initialize within it, Stripe reports `unavailable`).\n //\n // 2. Stripe load state. Reactive — catches the long tail (desktop\n // ad-blockers, new WebViews we haven't tagged, gateway misconfig).\n //\n // For PayPal, both `load_error` and `unavailable` are treated as failure:\n // PayPal availability isn't device-dependent, so `unavailable` here means\n // something blocked it. For wallets, only `load_error` counts — Apple/\n // Google Pay `unavailable` is normal on most devices and would otherwise\n // false-positive on every desktop session.\n const [paypalLoadState, setPaypalLoadState] = useState<ExpressCheckoutLoadState>('loading');\n const [walletLoadState, setWalletLoadState] = useState<ExpressCheckoutLoadState>('loading');\n const [inAppBrowserDetected, setInAppBrowserDetected] = useState(false);\n useEffect(() => {\n setInAppBrowserDetected(isInAppBrowser());\n }, []);\n const expectedPayPal = showPayPal && !!paypalStripeInstance;\n const expectedWallets = showWallets && !!stripeInstance;\n const paypalLoadFailed = expectedPayPal\n && (paypalLoadState === 'load_error' || paypalLoadState === 'unavailable');\n const walletsLoadFailed = expectedWallets && walletLoadState === 'load_error';\n const showInAppBrowserNotice = (\n (expectedPayPal || expectedWallets)\n && (inAppBrowserDetected || paypalLoadFailed || walletsLoadFailed)\n );\n\n const handleNameChange = useCallback((value: string) => {\n setFullName(value);\n onFullNameChange?.(value);\n const parts = value.trim().split(/\\s+/);\n onFirstNameChange?.(parts[0] ?? '');\n onLastNameChange?.(parts.length > 1 ? parts.slice(1).join(' ') : '');\n }, [onFullNameChange, onFirstNameChange, onLastNameChange]);\n\n const applyInlineSessionPatch = useCallback(\n (patch: InlineSessionPatch, method: CheckoutButtonMethod): Promise<BeforeButtonClickPatchResult> => {\n if (!checkout.applyInlineSessionPatch) {\n return Promise.resolve({ error: null, sessionId });\n }\n\n return checkout.applyInlineSessionPatch(patch)\n .then((result) => ({\n error: null,\n sessionId: result.sessionId || sessionId,\n }))\n .catch((err) => {\n const floPayErr = normalizeBeforeButtonClickError(method, err);\n updateError(floPayErr.message);\n onError?.(floPayErr);\n return { error: floPayErr, sessionId };\n });\n },\n [checkout.applyInlineSessionPatch, onError, sessionId, updateError],\n );\n\n const runBeforeButtonClick = useCallback(async (\n method: CheckoutButtonMethod,\n ): Promise<BeforeButtonClickResult> => {\n if (!onBeforeButtonClick) return { proceed: true };\n\n try {\n const result = await onBeforeButtonClick({\n method,\n sessionId: sessionId || undefined,\n createSession: checkout.inlineSessionDraft,\n });\n\n if (result === false) {\n return { proceed: false };\n }\n\n if (result && typeof result === 'object') {\n if (result.account) {\n setAccountPatch((prev) => ({ ...(prev ?? {}), ...result.account }));\n }\n\n const patchResult = await applyInlineSessionPatch(result, method);\n if (patchResult.error) {\n return {\n proceed: false,\n accountPatch: result.account,\n };\n }\n\n return {\n proceed: true,\n accountPatch: result.account,\n sessionId: patchResult.sessionId,\n };\n }\n\n return { proceed: true };\n } catch (err) {\n const floPayErr = normalizeBeforeButtonClickError(method, err);\n updateError(floPayErr.message);\n onError?.(floPayErr);\n return { proceed: false };\n }\n }, [applyInlineSessionPatch, checkout.inlineSessionDraft, onBeforeButtonClick, onError, sessionId, updateError]);\n\n // ── Internal processPayment + 3DS retry ──\n\n const processPaymentInternal = useCallback(\n async (tokenizedBody: TokenizedBody, overrides?: TokenizedBodyOverrides) => {\n // Prevent double-processing\n if (processingRef.current) return;\n processingRef.current = true;\n\n setProcessing(true);\n setOverlayStatus('processing');\n updateError(null);\n\n const effectiveSessionId = overrides?.sessionId ?? sessionId;\n const effectiveAccount = mergeAccountPatch(resolvedAccount, overrides?.accountPatch);\n const resolvedCompletionPaymentMethodId =\n overrides?.completionPaymentMethodId ?? resolveTokenizedPaymentMethodId(tokenizedBody);\n const requestTokenizedBody = tokenizedBody.originalPaymentMethodId\n ? { ...tokenizedBody, originalPaymentMethodId: undefined }\n : tokenizedBody;\n\n try {\n const response = await fetch(`${baseUrl}/v1/checkouts/sessions/process`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'x-user-id': effectiveAccount.userId ?? '',\n },\n body: JSON.stringify({\n sessionId: effectiveSessionId,\n tokenizedData: requestTokenizedBody,\n accountData: {\n userId: effectiveAccount.userId ?? '',\n email: effectiveAccount.email ?? '',\n firstName: effectiveAccount.firstName ?? fullName.trim().split(/\\s+/)[0] ?? '',\n lastName: effectiveAccount.lastName ?? fullName.trim().split(/\\s+/).slice(1).join(' ') ?? '',\n ...(avsConfig ? (() => {\n const c = selectedCountryRef.current;\n const stateVisible = isAVSFieldVisible(avsConfig.state, c);\n const line1Visible = isAVSFieldVisible(avsConfig.address_line_1, c);\n const zipVisible = isAVSFieldVisible(avsConfig.postal_code, c);\n // When line1 is collected but state is hidden, derive state\n // from the ZIP for US/CA so Stripe AVS still gets a state signal.\n const derivedState = (line1Visible && !stateVisible && zipVisible)\n ? getStateFromPostalCode(c, zipCodeRef.current ?? '')\n : null;\n const stateValue = stateVisible ? stateRef.current : derivedState;\n return {\n country: c,\n ...(zipVisible && zipCodeRef.current ? { zip: zipCodeRef.current } : {}),\n ...(isAVSFieldVisible(avsConfig.city, c) && cityRef.current ? { city: cityRef.current } : {}),\n ...(stateValue ? { state: stateValue } : {}),\n ...(line1Visible && addressLine1Ref.current ? { addressLine1: addressLine1Ref.current } : {}),\n ...(isAVSFieldVisible(avsConfig.address_line_2, c) && addressLine2Ref.current ? { addressLine2: addressLine2Ref.current } : {}),\n };\n })() : {}),\n },\n chv,\n // Checkout analytics metadata\n avsCheck: avsCheckProp ?? false,\n checkoutType: checkoutTypeProp,\n checkoutLayout: checkoutLayoutProp,\n // Resolved exposure: which fields were actually shown for the active country.\n // Country-scoped rules (e.g. ['US', 'CA']) are flattened to booleans here.\n avsConfig: avsConfig ? {\n country: isAVSFieldVisible(avsConfig.country, selectedCountryRef.current),\n postal_code: isAVSFieldVisible(avsConfig.postal_code, selectedCountryRef.current),\n address_line_1: isAVSFieldVisible(avsConfig.address_line_1, selectedCountryRef.current),\n address_line_2: isAVSFieldVisible(avsConfig.address_line_2, selectedCountryRef.current),\n city: isAVSFieldVisible(avsConfig.city, selectedCountryRef.current),\n state: isAVSFieldVisible(avsConfig.state, selectedCountryRef.current),\n } : undefined,\n }),\n });\n\n if (response.ok) {\n // Mark the session as completed *now*, before the 1.2s success\n // overlay delay below. A bootstrap that re-runs during that delay\n // (real remount, navigation flicker, etc.) would otherwise see the\n // backend status flipped to 'complete', clear the cache, and POST\n // a duplicate session that would then be /process'd with the\n // original PaymentIntent — double-charging the buyer.\n markSessionRecentlyCompleted(effectiveSessionId);\n setOverlayStatus('success');\n await new Promise((r) => setTimeout(r, PROCESSING_OVERLAY_SUCCESS_DELAY_MS));\n onComplete?.({\n status: 'succeeded',\n paymentIntentId: tokenizedBody.threeDSecureActionResultTokenId,\n paymentMethodId: resolvedCompletionPaymentMethodId,\n checkoutMethod: tokenizedBody.isPaypal ? 'paypal' : 'card',\n });\n return;\n }\n\n const json = await response.json().catch(() => null) as Record<string, unknown> | null;\n\n if (json?.type === '3ds_required') {\n const secret = json['threeDSecureToken'] as string;\n if (!flopay || !secret) {\n setOverlayStatus('error');\n updateError('3DS authentication required but no token provided.');\n return;\n }\n\n setIs3DSActive(true);\n try {\n // Only include AVS fields that are currently visible for the selected country.\n const retryBillingAddress: Record<string, string> = {};\n const retryCC = selectedCountryRef.current;\n const retryCountry = enableAVS ? retryCC : effectiveAccount.country;\n if (retryCountry) retryBillingAddress['country'] = retryCountry;\n if (avsConfig && isAVSFieldVisible(avsConfig.postal_code, retryCC) && zipCodeRef.current.trim()) {\n retryBillingAddress['postal_code'] = zipCodeRef.current.trim();\n } else if (!avsConfig && effectiveAccount.zip) {\n retryBillingAddress['postal_code'] = effectiveAccount.zip;\n }\n if (avsConfig && isAVSFieldVisible(avsConfig.address_line_1, retryCC) && addressLine1Ref.current.trim()) retryBillingAddress['line1'] = addressLine1Ref.current.trim();\n if (avsConfig && isAVSFieldVisible(avsConfig.address_line_2, retryCC) && addressLine2Ref.current.trim()) retryBillingAddress['line2'] = addressLine2Ref.current.trim();\n if (avsConfig && isAVSFieldVisible(avsConfig.city, retryCC) && cityRef.current.trim()) retryBillingAddress['city'] = cityRef.current.trim();\n if (avsConfig && isAVSFieldVisible(avsConfig.state, retryCC) && stateRef.current.trim()) {\n retryBillingAddress['state'] = stateRef.current.trim();\n } else if (\n avsConfig\n && isAVSFieldVisible(avsConfig.address_line_1, retryCC)\n && !isAVSFieldVisible(avsConfig.state, retryCC)\n && isAVSFieldVisible(avsConfig.postal_code, retryCC)\n ) {\n const derivedRetryState = getStateFromPostalCode(retryCC, zipCodeRef.current.trim());\n if (derivedRetryState) retryBillingAddress['state'] = derivedRetryState;\n }\n const result = await flopay.confirmPayment({\n clientSecret: secret,\n returnUrl: window.location.href,\n billingDetails: {\n ...(effectiveAccount.email ? { email: effectiveAccount.email } : {}),\n ...(fullName.trim() ? { name: fullName.trim() } : {}),\n ...(Object.keys(retryBillingAddress).length > 0 ? { address: retryBillingAddress } : {}),\n },\n });\n\n if (result.error) {\n setOverlayStatus('error');\n updateError(result.error.message);\n onError?.(result.error);\n emitDecline('card', result.error);\n return;\n }\n\n if (result.status === 'succeeded' || result.status === 'processing') {\n // Allow re-entry for 3DS retry\n processingRef.current = false;\n await processPaymentInternal({\n id: result.paymentIntentId,\n type: 'card',\n threeDSecureActionResultTokenId: result.paymentIntentId,\n }, {\n completionPaymentMethodId: resolvedCompletionPaymentMethodId,\n });\n }\n } finally {\n setIs3DSActive(false);\n }\n return;\n }\n\n // PayPal redirect required — backend created a PI that needs PayPal authorization.\n // Confirm the payment which triggers redirect to PayPal. On return, the\n // PayPalButtonInner's resume handler picks up the payment_intent URL params.\n if (json?.type === 'paypal_redirect_required') {\n const secret = json['threeDSecureToken'] as string;\n const savedPmId = (json['paymentMethodId'] as string) || tokenizedBody.id || '';\n if (!flopay || !secret) {\n setOverlayStatus('error');\n updateError('PayPal authorization required but no token provided.');\n return;\n }\n\n try {\n // PayPal PaymentIntents live on the PayPal Stripe account — route\n // the confirmation through the PayPal Stripe instance.\n const paypalStripe = paypalFlopay?.getRawProvider() as Stripe | null;\n if (!paypalStripe) {\n updateError('PayPal is not available.');\n return;\n }\n\n const confirmParams: Record<string, unknown> = {\n return_url: window.location.href,\n };\n if (savedPmId) {\n confirmParams['payment_method'] = savedPmId;\n }\n\n const { error: confirmError } = await paypalStripe.confirmPayment({\n clientSecret: secret,\n confirmParams: confirmParams as { return_url: string },\n redirect: 'if_required',\n });\n\n if (confirmError) {\n setOverlayStatus('error');\n const message = confirmError.message ?? 'PayPal payment failed.';\n updateError(message);\n emitDecline('paypal', message, {\n code: confirmError.code,\n });\n }\n } catch (err) {\n setOverlayStatus('error');\n updateError(err instanceof Error ? err.message : 'PayPal authorization failed.');\n }\n return;\n }\n\n setOverlayStatus('error');\n const message = (json?.message as string) ?? 'Payment failed. Please try again.';\n updateError(message);\n emitDecline(tokenizedBody.isPaypal ? 'paypal' : 'card', message, {\n code: (json?.code ?? json?.gatewayErrorCode) as string | undefined,\n declineCode: (json?.declineCode ?? json?.gatewayDeclineReason) as string | undefined,\n });\n await new Promise((r) => setTimeout(r, PROCESSING_OVERLAY_ERROR_DELAY_MS));\n } catch (err) {\n setOverlayStatus('error');\n updateError(err instanceof Error ? err.message : 'An unexpected error occurred');\n await new Promise((r) => setTimeout(r, PROCESSING_OVERLAY_ERROR_DELAY_MS));\n } finally {\n setProcessing(false);\n setOverlayStatus(null);\n processingRef.current = false;\n }\n },\n [baseUrl, sessionId, resolvedAccount, fullName, chv, flopay, paypalFlopay, onComplete, onError, updateError, emitDecline],\n );\n\n const dispatchTokenizedBody = useCallback(\n (tokenizedBody: TokenizedBody, overrides?: TokenizedBodyOverrides) => {\n if (onTokenizedBody) {\n onTokenizedBody(tokenizedBody);\n } else {\n processPaymentInternal(tokenizedBody, overrides);\n }\n },\n [onTokenizedBody, processPaymentInternal],\n );\n\n // ── Imperative 3DS handler ──\n\n useImperativeHandle(innerRef, () => ({\n async handleNextAction(secret: string) {\n if (!flopay) return;\n\n setIs3DSActive(true);\n try {\n const result = await flopay.confirmPayment({\n clientSecret: secret,\n returnUrl: window.location.href,\n });\n\n if (result.error) {\n updateError(result.error.message);\n onError?.(result.error);\n emitDecline('card', result.error);\n } else if (result.status === 'succeeded' || result.status === 'processing') {\n dispatchTokenizedBody({\n id: result.paymentIntentId,\n type: 'card',\n threeDSecureActionResultTokenId: result.paymentIntentId,\n });\n }\n } catch (err) {\n updateError(err instanceof Error ? err.message : 'Payment authentication failed.');\n } finally {\n setIs3DSActive(false);\n }\n },\n }), [flopay, dispatchTokenizedBody, onError, updateError, emitDecline]);\n\n // ── Wallet resume ──\n\n useEffect(() => {\n if (typeof window === 'undefined') return;\n\n const stored = localStorage.getItem(WALLET_RESUME_KEY);\n if (!stored) return;\n\n try {\n const payload = JSON.parse(stored) as {\n sessionId: string;\n paymentIntentId: string;\n tokenType: string;\n tokenId: string;\n status: string;\n };\n\n if (payload.sessionId === sessionId) {\n localStorage.removeItem(WALLET_RESUME_KEY);\n dispatchTokenizedBody({\n id: payload.tokenId,\n type: payload.tokenType,\n threeDSecureActionResultTokenId: payload.paymentIntentId,\n });\n }\n } catch {\n localStorage.removeItem(WALLET_RESUME_KEY);\n }\n }, [sessionId, dispatchTokenizedBody]);\n\n // ── Card submit ──\n\n const handleSubmit = useCallback(\n async (e: React.FormEvent) => {\n e.preventDefault();\n if (!flopay || !elements || isSubmitting || processingRef.current) return;\n\n if (layout !== 'buttons') {\n onButtonClick?.('card');\n }\n setProcessing(true);\n setOverlayStatus('processing');\n updateError(null);\n\n // Track whether we handed off to processPaymentInternal (which manages its own overlay)\n let handedOff = false;\n\n try {\n // Matches checkout/StripeCardForm exactly:\n // 1. createPaymentMethod → 2. createPaymentIntent → 3. confirmCardPayment → 4. onTokenizedBody\n\n // 0. Validate AVS fields — all visible fields are required (except address_line_2).\n // Read from refs for the latest value — state may not have flushed\n // if the user typed and clicked submit in quick succession.\n if (avsConfig) {\n const country = selectedCountryRef.current;\n if (isAVSFieldVisible(avsConfig.postal_code, country) && !zipCodeRef.current.trim()) {\n updateError(getPostalCodeLabel(country) + ' is required');\n return;\n }\n if (isAVSFieldVisible(avsConfig.address_line_1, country) && !addressLine1Ref.current.trim()) {\n updateError('Street address is required');\n return;\n }\n if (isAVSFieldVisible(avsConfig.city, country) && !cityRef.current.trim()) {\n updateError('City is required');\n return;\n }\n if (isAVSFieldVisible(avsConfig.state, country) && !stateRef.current.trim()) {\n updateError(getStateLabel(country) + ' is required');\n return;\n }\n }\n\n // 1. Validate elements\n const submitResult = await flopay.submitElements();\n if (submitResult.error) {\n updateError(submitResult.error.message);\n onError?.(submitResult.error);\n return;\n }\n\n // 2. Create PaymentMethod (tokenize card + AVS billing_details)\n // Only include fields that are currently visible for the selected country.\n const billingAddress: Record<string, string> = {};\n const cc = selectedCountryRef.current;\n const avsCountry = enableAVS ? cc : resolvedAccount.country;\n if (avsCountry) billingAddress['country'] = avsCountry;\n if (avsConfig && isAVSFieldVisible(avsConfig.postal_code, cc) && zipCodeRef.current.trim()) {\n billingAddress['postal_code'] = zipCodeRef.current.trim();\n } else if (!avsConfig && resolvedAccount.zip) {\n billingAddress['postal_code'] = resolvedAccount.zip;\n }\n if (avsConfig && isAVSFieldVisible(avsConfig.address_line_1, cc) && addressLine1Ref.current.trim()) billingAddress['line1'] = addressLine1Ref.current.trim();\n if (avsConfig && isAVSFieldVisible(avsConfig.address_line_2, cc) && addressLine2Ref.current.trim()) billingAddress['line2'] = addressLine2Ref.current.trim();\n if (avsConfig && isAVSFieldVisible(avsConfig.city, cc) && cityRef.current.trim()) billingAddress['city'] = cityRef.current.trim();\n if (avsConfig && isAVSFieldVisible(avsConfig.state, cc) && stateRef.current.trim()) {\n billingAddress['state'] = stateRef.current.trim();\n } else if (\n avsConfig\n && isAVSFieldVisible(avsConfig.address_line_1, cc)\n && !isAVSFieldVisible(avsConfig.state, cc)\n && isAVSFieldVisible(avsConfig.postal_code, cc)\n ) {\n const derivedSubmitState = getStateFromPostalCode(cc, zipCodeRef.current.trim());\n if (derivedSubmitState) billingAddress['state'] = derivedSubmitState;\n }\n\n const billingDetails = {\n ...(resolvedAccount.email ? { email: resolvedAccount.email } : {}),\n ...(fullName.trim() ? { name: fullName.trim() } : {}),\n ...(Object.keys(billingAddress).length > 0 ? { address: billingAddress } : {}),\n };\n const pmResult = await flopay.createPaymentMethod(billingDetails);\n if (pmResult.error || !pmResult.paymentMethodId) {\n updateError(pmResult.error?.message ?? 'Failed to create payment method.');\n return;\n }\n\n if (!sessionId || !resolvedAccount.email) {\n throw new FloPayError('Missing sessionId or email', 'validation_error');\n }\n\n // 3. Create PaymentIntent via billing API (backend uses capture_method: 'manual')\n const intentResponse = await fetch(`${baseUrl}/v1/checkouts/payments/intents`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n sessionId,\n email: resolvedAccount.email,\n paymentMethodType: pmResult.paymentMethodId,\n isPaypal: false,\n }),\n });\n\n if (!intentResponse.ok) {\n const intentError = await buildFloPayApiErrorFromResponse(\n intentResponse,\n 'Failed to create payment intent',\n );\n setOverlayStatus('error');\n updateError(intentError.message);\n onError?.(intentError);\n emitDecline('card', intentError);\n await new Promise((r) => setTimeout(r, PROCESSING_OVERLAY_ERROR_DELAY_MS));\n return;\n }\n\n const intentJson = await intentResponse.json() as { data?: { id?: string } };\n const intentClientSecret = intentJson.data?.id;\n if (!intentClientSecret) throw new FloPayError('No client_secret in payment intent response', 'api_error');\n\n // 4. Confirm card payment (handles 3DS automatically via Stripe)\n const confirmResult = await flopay.confirmCardPayment({\n clientSecret: intentClientSecret,\n paymentMethodId: pmResult.paymentMethodId,\n });\n\n if (confirmResult.error) {\n setOverlayStatus('error');\n updateError(confirmResult.error.message);\n onError?.(confirmResult.error);\n emitDecline('card', confirmResult.error);\n await new Promise((r) => setTimeout(r, PROCESSING_OVERLAY_ERROR_DELAY_MS));\n return;\n }\n\n const rawProvider = typeof flopay.getRawProvider === 'function' ? flopay.getRawProvider() : null;\n const confirmedPaymentIntent = await retrievePaymentIntentFromProvider(\n rawProvider,\n intentClientSecret,\n );\n const paymentIntentId = confirmResult.paymentIntentId ?? confirmedPaymentIntent?.id;\n const paymentMethodId =\n confirmResult.paymentMethodId\n ?? resolvePaymentIntentPaymentMethodId(confirmedPaymentIntent)\n ?? pmResult.paymentMethodId;\n\n if (!paymentIntentId) {\n const error = new FloPayError('No payment intent returned after confirmation.', 'api_error');\n setOverlayStatus('error');\n updateError(error.message);\n onError?.(error);\n await new Promise((r) => setTimeout(r, PROCESSING_OVERLAY_ERROR_DELAY_MS));\n return;\n }\n\n // 5. Send PM + PI to processPaymentInternal (or parent via onTokenizedBody)\n // In self-contained mode, processPaymentInternal manages overlay lifecycle.\n handedOff = isSelfContained;\n dispatchTokenizedBody({\n id: paymentMethodId,\n type: 'card',\n threeDSecureActionResultTokenId: paymentIntentId,\n originalPaymentMethodId: pmResult.paymentMethodId,\n });\n } catch (err) {\n setOverlayStatus('error');\n updateError(err instanceof Error ? err.message : 'An unexpected error occurred');\n await new Promise((r) => setTimeout(r, PROCESSING_OVERLAY_ERROR_DELAY_MS));\n } finally {\n if (!handedOff) {\n setProcessing(false);\n setOverlayStatus(null);\n }\n }\n },\n [flopay, elements, isSubmitting, sessionId, resolvedAccount.email, baseUrl, isSelfContained, dispatchTokenizedBody, onButtonClick, onError, updateError, emitDecline, layout],\n );\n\n const isReady = flopay !== null && elements !== null;\n\n if (!isReady) {\n return <div data-testid=\"flopay-loading\" aria-busy=\"true\">Loading payment form...</div>;\n }\n\n const isButtons = layout === 'buttons';\n const resolvedBorder = isButtons ? (bStyles.cardInputBorder ?? '#e5e7eb') : '#A4A4FF';\n const cardBg = isButtons ? ((bStyles.cardFormContainer?.backgroundColor as string) ?? 'white') : '#EDEDFF';\n const cardInputBg = isButtons ? (bStyles.cardInputBackground ?? 'white') : 'white';\n const hideBackButtonLabel = isEmptySlotContent(cardBackButtonContent);\n const hideTitle = isEmptySlotContent(cardTitleContent);\n const nameInputOverrides = isButtons ? bStyles.nameInput : undefined;\n const resolvedInputFontSize = bStyles.cardInputFontSize\n ?? toCssSize(nameInputOverrides?.fontSize)\n ?? '16px';\n const resolvedInputFontFamily = typeof nameInputOverrides?.fontFamily === 'string'\n ? nameInputOverrides.fontFamily\n : 'Poppins, sans-serif';\n const resolvedInputFontWeight = toCssWeight(nameInputOverrides?.fontWeight) ?? 400;\n const resolvedInputColor = bStyles.cardInputColor\n ?? (typeof nameInputOverrides?.color === 'string' ? nameInputOverrides.color : undefined)\n ?? '#262833';\n const resolvedPlaceholderColor = bStyles.cardInputPlaceholderColor ?? '#9ca3af';\n const sharedInputTypography: React.CSSProperties = {\n fontSize: resolvedInputFontSize,\n fontFamily: resolvedInputFontFamily,\n fontWeight: resolvedInputFontWeight,\n color: resolvedInputColor,\n WebkitFontSmoothing: 'antialiased',\n MozOsxFontSmoothing: 'grayscale',\n };\n const sharedInputPlaceholderVars = {\n '--flopay-input-placeholder-color': resolvedPlaceholderColor,\n '--flopay-input-font-size': resolvedInputFontSize,\n '--flopay-input-font-family': resolvedInputFontFamily,\n '--flopay-input-font-weight': String(resolvedInputFontWeight),\n } as React.CSSProperties;\n\n // Stripe Element style — keeps the iframe typography aligned with the plain text inputs.\n const stripeElementStyle = {\n style: {\n base: {\n ...sharedInputTypography,\n fontSmoothing: 'antialiased',\n '::placeholder': {\n color: resolvedPlaceholderColor,\n fontSize: resolvedInputFontSize,\n fontFamily: resolvedInputFontFamily,\n fontWeight: resolvedInputFontWeight,\n },\n },\n invalid: { color: '#ef4444' },\n },\n };\n\n // ── Card fields block (shared between both layouts) ──\n const cardFormBlock = (\n <div style={{\n backgroundColor: cardBg, borderRadius: '8px',\n padding: isButtons ? '0' : '1rem',\n ...(isButtons ? bStyles.cardFormContainer as React.CSSProperties : {}),\n ...(isButtons ? { padding: bStyles.cardFormContainer?.padding ?? '0' } : {}),\n ...sharedInputPlaceholderVars,\n }}>\n <style>{`\n .flopay-shared-input::placeholder {\n color: var(--flopay-input-placeholder-color);\n opacity: 1;\n font-size: var(--flopay-input-font-size);\n font-family: var(--flopay-input-font-family);\n font-weight: var(--flopay-input-font-weight);\n }\n `}</style>\n {/* Header: back button + title on same row (buttons layout) */}\n {isButtons && showCardForm && (\n <div style={{\n display: 'flex', alignItems: 'center', padding: '0.75rem 0 0.625rem',\n }}>\n <button\n type=\"button\"\n onClick={collapseToButtons}\n style={{\n display: 'inline-flex', alignItems: 'center', gap: hideBackButtonLabel ? 0 : '0.5rem',\n background: 'none', border: 'none', cursor: 'pointer',\n color: '#4b5563', fontSize: bStyles.backButtonFontSize ?? '0.85rem', fontWeight: 500,\n padding: 0, transition: 'color 0.15s', flexShrink: 0,\n ...bStyles.backButton as React.CSSProperties,\n }}\n aria-label=\"Back to payment methods\"\n >\n <span style={{\n display: 'inline-flex', alignItems: 'center', justifyContent: 'center',\n width: 28, height: 28, borderRadius: '50%',\n backgroundColor: '#f3f4f6', transition: 'background-color 0.15s',\n ...bStyles.backButtonIcon as React.CSSProperties,\n }}>\n <svg width=\"14\" height=\"14\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2.5\" strokeLinecap=\"round\" strokeLinejoin=\"round\">\n <path d=\"M15 18l-6-6 6-6\" />\n </svg>\n </span>\n <BackButtonContentSlot content={cardBackButtonContent} />\n </button>\n {hideTitle ? (\n <div style={{ flex: 1 }} />\n ) : (\n <div style={{\n flex: 1, textAlign: 'center', fontWeight: 600,\n fontSize: bStyles.titleFontSize ?? '1.05rem',\n color: '#262833', paddingRight: 80,\n ...bStyles.title as React.CSSProperties,\n }}>\n <TitleContentSlot content={cardTitleContent} />\n </div>\n )}\n </div>\n )}\n\n {/* Title (default layout only) */}\n {!isButtons && !hideTitle && (\n <div style={{ textAlign: 'center', fontWeight: 600, fontSize: '1.1rem', padding: '0.5rem 0', color: '#262833' }}>\n <TitleContentSlot content={cardTitleContent} />\n </div>\n )}\n\n {/* Card Number */}\n <div style={{\n backgroundColor: cardInputBg, border: `1px solid ${resolvedBorder}`,\n borderTopLeftRadius: '8px', borderTopRightRadius: '8px', padding: '10px',\n }}>\n <CardNumberElement onReady={() => setFormReady(true)} options={stripeElementStyle} />\n </div>\n\n {/* Expiry + CVC */}\n <div style={{ display: 'flex' }}>\n <div style={{\n flex: 1, backgroundColor: cardInputBg, border: `1px solid ${resolvedBorder}`,\n borderTop: 'none', borderRight: 'none',\n borderBottomLeftRadius: '8px', padding: '10px',\n }}>\n <CardExpiryElement options={stripeElementStyle} />\n </div>\n <div style={{\n flex: 1, backgroundColor: cardInputBg, border: `1px solid ${resolvedBorder}`,\n borderTop: 'none', borderBottomRightRadius: '8px', padding: '10px',\n }}>\n <CardCvcElement options={stripeElementStyle} />\n </div>\n </div>\n\n {/* Full Name */}\n <div style={{\n backgroundColor: cardInputBg, border: `1px solid ${resolvedBorder}`,\n borderRadius: '8px', marginTop: '0.5rem', padding: '10px',\n }}>\n <input\n className=\"flopay-shared-input\"\n placeholder=\"Full Name on Card\"\n autoComplete=\"cc-name\"\n value={fullName}\n onChange={(e) => handleNameChange(e.target.value)}\n disabled={isSubmitting}\n required\n style={{\n width: '100%', border: 'none', outline: 'none', background: 'transparent',\n ...sharedInputTypography,\n ...(isButtons && bStyles.nameInput ? bStyles.nameInput as React.CSSProperties : {}),\n }}\n />\n </div>\n\n {/* AVS Address Fields */}\n {avsConfig && (() => {\n const cc = selectedCountry;\n const inputWrapStyle = (extraStyle?: Record<string, string | number>): React.CSSProperties => ({\n backgroundColor: cardInputBg, border: `1px solid ${resolvedBorder}`,\n borderRadius: '8px', marginTop: '0.5rem', padding: '10px',\n ...(isButtons && extraStyle ? extraStyle as React.CSSProperties : {}),\n });\n const inputFieldStyle = (): React.CSSProperties => ({\n width: '100%', border: 'none', outline: 'none', background: 'transparent',\n ...sharedInputTypography,\n ...(isButtons && bStyles.nameInput ? bStyles.nameInput as React.CSSProperties : {}),\n });\n const stateOpts = getStateOptions(cc);\n\n return (\n <>\n {/* Street Address (line 1) */}\n {isAVSFieldVisible(avsConfig.address_line_1, cc) && (\n <div style={inputWrapStyle(bStyles.addressLine1Input)}>\n <input\n className=\"flopay-shared-input\"\n placeholder=\"Street Address (e.g. 123 Main St)\"\n autoComplete=\"address-line1\"\n value={addressLine1}\n onChange={(e) => { addressLine1Ref.current = e.target.value; setAddressLine1(e.target.value); }}\n disabled={isSubmitting}\n required\n data-testid=\"flopay-address-line1\"\n style={inputFieldStyle()}\n />\n </div>\n )}\n\n {/* Apt, Suite, etc. (line 2) */}\n {isAVSFieldVisible(avsConfig.address_line_2, cc) && (\n <div style={inputWrapStyle(bStyles.addressLine2Input)}>\n <input\n className=\"flopay-shared-input\"\n placeholder=\"Apt, Suite, Unit (optional)\"\n autoComplete=\"address-line2\"\n value={addressLine2}\n onChange={(e) => { addressLine2Ref.current = e.target.value; setAddressLine2(e.target.value); }}\n disabled={isSubmitting}\n data-testid=\"flopay-address-line2\"\n style={inputFieldStyle()}\n />\n </div>\n )}\n\n {/* City + State row */}\n {(isAVSFieldVisible(avsConfig.city, cc) || isAVSFieldVisible(avsConfig.state, cc)) && (\n <div style={{\n display: 'flex', gap: '0', marginTop: '0.5rem',\n }}>\n {isAVSFieldVisible(avsConfig.city, cc) && (\n <div style={{\n flex: 1, backgroundColor: cardInputBg, border: `1px solid ${resolvedBorder}`,\n padding: '10px',\n borderTopLeftRadius: '8px', borderBottomLeftRadius: '8px',\n ...(isAVSFieldVisible(avsConfig.state, cc) ? { borderRight: 'none', borderTopRightRadius: 0, borderBottomRightRadius: 0 } : { borderRadius: '8px' }),\n ...(isButtons && bStyles.cityInput ? bStyles.cityInput as React.CSSProperties : {}),\n }}>\n <input\n className=\"flopay-shared-input\"\n placeholder=\"City\"\n autoComplete=\"address-level2\"\n value={city}\n onChange={(e) => { cityRef.current = e.target.value; setCity(e.target.value); }}\n disabled={isSubmitting}\n required\n data-testid=\"flopay-city\"\n style={inputFieldStyle()}\n />\n </div>\n )}\n {isAVSFieldVisible(avsConfig.state, cc) && (\n <div style={{\n flex: 1, backgroundColor: cardInputBg, border: `1px solid ${resolvedBorder}`,\n padding: '10px',\n borderTopRightRadius: '8px', borderBottomRightRadius: '8px',\n ...(isAVSFieldVisible(avsConfig.city, cc) ? { borderTopLeftRadius: 0, borderBottomLeftRadius: 0 } : { borderRadius: '8px' }),\n ...(isButtons && bStyles.stateInput ? bStyles.stateInput as React.CSSProperties : {}),\n }}>\n {stateOpts ? (\n <select\n value={stateValue}\n onChange={(e) => { stateRef.current = e.target.value; setStateValue(e.target.value); }}\n disabled={isSubmitting}\n autoComplete=\"address-level1\"\n required\n data-testid=\"flopay-state\"\n style={{ ...inputFieldStyle(), cursor: 'pointer' }}\n >\n <option value=\"\">{getStateLabel(cc)}</option>\n {stateOpts.map((s) => (\n <option key={s.code} value={s.code}>{s.name}</option>\n ))}\n </select>\n ) : (\n <input\n className=\"flopay-shared-input\"\n placeholder={getStateLabel(cc)}\n autoComplete=\"address-level1\"\n value={stateValue}\n onChange={(e) => { stateRef.current = e.target.value; setStateValue(e.target.value); }}\n disabled={isSubmitting}\n required\n data-testid=\"flopay-state\"\n style={inputFieldStyle()}\n />\n )}\n </div>\n )}\n </div>\n )}\n\n {/* Country + ZIP/Postcode row */}\n {(isAVSFieldVisible(avsConfig.country, cc) || isAVSFieldVisible(avsConfig.postal_code, cc)) && (\n <div style={{\n display: 'flex',\n flexDirection: avsLayoutProp === 'column' ? 'column' : 'row',\n gap: avsLayoutProp === 'column' ? '0.5rem' : '0',\n marginTop: '0.5rem',\n }}>\n {isAVSFieldVisible(avsConfig.country, cc) && (\n <div style={{\n flex: avsLayoutProp === 'row' ? 1 : undefined,\n backgroundColor: cardInputBg, border: `1px solid ${resolvedBorder}`,\n padding: '10px',\n ...(avsLayoutProp === 'row' && isAVSFieldVisible(avsConfig.postal_code, cc)\n ? { borderRadius: '0', borderTopLeftRadius: '8px', borderBottomLeftRadius: '8px', borderRight: 'none' }\n : { borderRadius: '8px' }),\n ...(isButtons && bStyles.countrySelect ? bStyles.countrySelect as React.CSSProperties : {}),\n }}>\n <select\n value={selectedCountry}\n onChange={(e) => {\n selectedCountryRef.current = e.target.value;\n setSelectedCountry(e.target.value);\n onCountryChange?.(e.target.value);\n // Reset state when country changes (different state lists)\n stateRef.current = '';\n setStateValue('');\n }}\n disabled={isSubmitting}\n autoComplete=\"country\"\n data-testid=\"flopay-country\"\n style={{ ...inputFieldStyle(), cursor: 'pointer' }}\n >\n {COUNTRY_OPTIONS.map((c) => (\n <option key={c.code} value={c.code}>{c.flag} {c.name}</option>\n ))}\n </select>\n </div>\n )}\n {isAVSFieldVisible(avsConfig.postal_code, cc) && (\n <div style={{\n flex: avsLayoutProp === 'row' ? 1 : undefined,\n backgroundColor: cardInputBg, border: `1px solid ${resolvedBorder}`,\n padding: '10px',\n ...(avsLayoutProp === 'row' && isAVSFieldVisible(avsConfig.country, cc)\n ? { borderRadius: '0', borderTopRightRadius: '8px', borderBottomRightRadius: '8px' }\n : { borderRadius: '8px' }),\n ...(isButtons && bStyles.zipInput ? bStyles.zipInput as React.CSSProperties : {}),\n }}>\n <input\n className=\"flopay-shared-input\"\n placeholder={getPostalCodeLabel(selectedCountry)}\n autoComplete=\"postal-code\"\n value={zipCode}\n onChange={(e) => {\n zipCodeRef.current = e.target.value;\n setZipCode(e.target.value);\n onZipChange?.(e.target.value);\n }}\n disabled={isSubmitting}\n required\n data-testid=\"flopay-zip\"\n style={inputFieldStyle()}\n />\n </div>\n )}\n </div>\n )}\n </>\n );\n })()}\n\n {displayError && (\n <div role=\"alert\" data-testid=\"flopay-error\" style={{\n margin: '0.75rem 0', padding: '0.625rem 0.875rem',\n background: '#FEF2F2', border: '1px solid #FECACA', borderRadius: '8px',\n color: '#991B1B', fontSize: '0.85rem', fontWeight: 600,\n display: 'flex', alignItems: 'center', gap: '0.5rem',\n ...(isButtons && bStyles.errorBanner ? bStyles.errorBanner as React.CSSProperties : {}),\n }}>\n <svg width=\"16\" height=\"16\" viewBox=\"0 0 24 24\" fill=\"none\" style={{ flexShrink: 0 }}>\n <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\" />\n </svg>\n {displayError}\n </div>\n )}\n\n {children ?? (\n <button\n type=\"submit\"\n disabled={!formReady || isSubmitting}\n data-testid=\"flopay-submit\"\n style={{\n width: '100%', padding: '0.875rem', marginTop: '1rem',\n backgroundColor: '#4A49FF', color: 'white', border: 'none',\n borderRadius: '8px',\n fontSize: (isButtons && bStyles.submitButtonFontSize) ? bStyles.submitButtonFontSize : '1rem',\n fontWeight: 600,\n cursor: !formReady || isSubmitting ? 'not-allowed' : 'pointer',\n opacity: !formReady || isSubmitting ? 0.5 : 1,\n ...((isButtons ? bStyles.submitButton : {}) as React.CSSProperties),\n }}\n >\n {isSubmitting ? 'PROCESSING...' : submitLabel}\n </button>\n )}\n\n {/* Security footer — only in default layout */}\n {!isButtons && showSecurityFooter && (\n <div style={{\n backgroundColor: '#EFF9F0', borderRadius: '8px', padding: '0.75rem',\n marginTop: '0.75rem', textAlign: 'center', fontSize: '0.85rem',\n fontWeight: 600, color: '#7DAD3A',\n }}>\n Secure Card Checkout\n </div>\n )}\n </div>\n );\n\n // ── Buttons layout ──\n if (layout === 'buttons') {\n const isButtonsView = viewState === 'buttons' || viewState === 'expanding';\n const isCardView = viewState === 'expanding' || viewState === 'card' || viewState === 'collapsing';\n const cardButtonSizing = cardButtonContent === undefined\n ? { boxSizing: 'border-box' as const, height: DEFAULT_BUTTONS_LAYOUT_BUTTON_HEIGHT, padding: '0 1rem' }\n : { padding: '0.9rem 1rem' };\n\n const buttonsAnim = viewState === 'expanding'\n ? `flopay-buttons-exit ${TRANSITION_MS}ms cubic-bezier(0.4, 0, 0.2, 1) both`\n : viewState === 'collapsing'\n ? `flopay-buttons-enter ${TRANSITION_MS}ms cubic-bezier(0, 0, 0.2, 1) both`\n : undefined;\n\n const cardAnim = viewState === 'expanding'\n ? `flopay-card-enter ${TRANSITION_MS}ms cubic-bezier(0, 0, 0.2, 1) both`\n : viewState === 'collapsing'\n ? `flopay-card-exit ${TRANSITION_MS}ms cubic-bezier(0.4, 0, 0.2, 1) both`\n : undefined;\n\n return (\n <form onSubmit={handleSubmit} className={className} style={{ position: 'relative' }}>\n <FloPayKeyframes />\n {overlayStatus && <ProcessingOverlay status={overlayStatus} errorMessage={displayError} />}\n\n {/* Container — uses grid overlap so both views can coexist during transition */}\n <div style={{ display: 'grid' }}>\n\n {/* Payment method buttons — always mounted to preserve PayPal/wallet Elements */}\n <div style={{\n gridArea: '1 / 1',\n display: 'flex', flexDirection: 'column', gap: '0.5rem',\n // When card form is showing (and not transitioning), hide but keep mounted\n ...(!isButtonsView && !buttonsAnim ? { visibility: 'hidden' as const, position: 'absolute' as const, pointerEvents: 'none' as const, width: '100%' } : {}),\n ...(buttonsAnim ? { animation: buttonsAnim, pointerEvents: 'none' as const } : {}),\n }}>\n {/* PayPal — hidden entirely when no paypalPublishableKey is configured */}\n {showPayPal && paypalStripeInstance && (\n <StripeElements stripe={paypalStripeInstance} options={paypalOptions}>\n <PayPalButtonInner\n sessionId={sessionId}\n email={resolvedAccount.email}\n billingApiUrl={resolvedBillingApiUrl}\n onTokenizedBody={dispatchTokenizedBody}\n onErrorChange={updateError}\n isProcessing={isSubmitting}\n onButtonClick={onButtonClick}\n onDecline={onDecline}\n runBeforeButtonClick={runBeforeButtonClick}\n onLoadStateChange={setPaypalLoadState}\n />\n </StripeElements>\n )}\n\n {/* Wallets (Apple Pay / Google Pay) */}\n {showWallets && stripeInstance ? (\n <StripeElements stripe={stripeInstance} options={walletOptions}>\n <WalletButtonInner\n sessionId={sessionId}\n email={resolvedAccount.email}\n billingApiUrl={resolvedBillingApiUrl}\n showApplePay={showApplePay}\n showGooglePay={showGooglePay}\n onTokenizedBody={dispatchTokenizedBody}\n onErrorChange={updateError}\n onButtonClick={onButtonClick}\n onDecline={onDecline}\n runBeforeButtonClick={runBeforeButtonClick}\n onLoadStateChange={setWalletLoadState}\n />\n </StripeElements>\n ) : showWallets ? (\n <div style={{ height: DEFAULT_BUTTONS_LAYOUT_BUTTON_HEIGHT, borderRadius: 8, background: '#e5e7eb', animation: 'flopay-pulse 1.5s ease-in-out infinite' }} />\n ) : null}\n\n {showInAppBrowserNotice && <InAppBrowserNotice />}\n\n {/* Credit / Debit Card button */}\n <button\n type=\"button\"\n onClick={async () => {\n if (isSubmitting) return;\n const beforeClick = await runBeforeButtonClick('card');\n if (!beforeClick.proceed) return;\n onButtonClick?.('card');\n expandToCard();\n }}\n disabled={isSubmitting}\n style={{\n width: '100%',\n ...cardButtonSizing,\n backgroundColor: 'white', color: '#262833',\n border: '1px solid #d1d5db', borderRadius: '8px',\n fontSize: bStyles.cardButtonFontSize ?? '0.95rem', fontWeight: 600,\n cursor: isSubmitting ? 'not-allowed' : 'pointer', display: 'flex',\n alignItems: 'center', justifyContent: 'center', gap: '0.625rem',\n transition: 'border-color 0.2s, box-shadow 0.2s, transform 0.1s',\n boxShadow: '0 1px 2px rgba(0,0,0,0.04)',\n position: 'relative',\n opacity: isSubmitting ? 0.6 : 1,\n ...bStyles.cardButton as React.CSSProperties,\n }}\n onMouseDown={(e) => { e.currentTarget.style.transform = 'scale(0.985)'; }}\n onMouseUp={(e) => { e.currentTarget.style.transform = 'scale(1)'; }}\n >\n <CardButtonContentSlot content={cardButtonContent} />\n </button>\n\n {displayError && viewState === 'buttons' && (\n <div role=\"alert\" data-testid=\"flopay-error\" style={{\n margin: '0.25rem 0', padding: '0.625rem 0.875rem',\n background: '#FEF2F2', border: '1px solid #FECACA', borderRadius: '8px',\n color: '#991B1B', fontSize: '0.85rem', fontWeight: 600,\n display: 'flex', alignItems: 'center', gap: '0.5rem',\n ...(bStyles.errorBanner ? bStyles.errorBanner as React.CSSProperties : {}),\n }}>\n <svg width=\"16\" height=\"16\" viewBox=\"0 0 24 24\" fill=\"none\" style={{ flexShrink: 0 }}>\n <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\" />\n </svg>\n {displayError}\n </div>\n )}\n </div>\n\n {/* Card form */}\n {isCardView && (\n <div style={{\n gridArea: '1 / 1',\n ...(cardAnim ? { animation: cardAnim } : {}),\n ...(viewState === 'collapsing' ? { pointerEvents: 'none' as const } : {}),\n }}>\n {cardFormBlock}\n </div>\n )}\n </div>\n </form>\n );\n }\n\n // ── Default layout ──\n return (\n <form onSubmit={handleSubmit} className={className} style={{ position: 'relative' }}>\n <FloPayKeyframes />\n {overlayStatus && <ProcessingOverlay status={overlayStatus} errorMessage={displayError} />}\n\n {/* Wallet buttons (Apple Pay / Google Pay) — own Stripe Elements instance */}\n {showWallets && stripeInstance && (\n <StripeElements stripe={stripeInstance} options={walletOptions}>\n <WalletButtonInner\n sessionId={sessionId}\n email={resolvedAccount.email}\n billingApiUrl={resolvedBillingApiUrl}\n showApplePay={showApplePay}\n showGooglePay={showGooglePay}\n onTokenizedBody={dispatchTokenizedBody}\n onErrorChange={updateError}\n onDecline={onDecline}\n onLoadStateChange={setWalletLoadState}\n />\n </StripeElements>\n )}\n\n {/* PayPal — own Stripe Elements instance on the dedicated PayPal Stripe account */}\n {showPayPal && paypalStripeInstance && (\n <StripeElements stripe={paypalStripeInstance} options={paypalOptions}>\n <PayPalButtonInner\n sessionId={sessionId}\n email={resolvedAccount.email}\n billingApiUrl={resolvedBillingApiUrl}\n onTokenizedBody={dispatchTokenizedBody}\n onErrorChange={updateError}\n isProcessing={isSubmitting}\n onDecline={onDecline}\n onLoadStateChange={setPaypalLoadState}\n />\n </StripeElements>\n )}\n\n {showInAppBrowserNotice && <InAppBrowserNotice />}\n\n {/* Divider between wallet/PayPal buttons and card fields */}\n {((showWallets && stripeInstance) || (showPayPal && paypalStripeInstance)) && (\n <div style={{\n display: 'flex', alignItems: 'center', gap: '0.75rem',\n margin: '0.5rem 0 0.75rem', color: '#999', fontSize: '0.85rem',\n }}>\n <div style={{ flex: 1, height: 1, backgroundColor: '#ddd' }} />\n <span>or pay with card</span>\n <div style={{ flex: 1, height: 1, backgroundColor: '#ddd' }} />\n </div>\n )}\n\n {cardFormBlock}\n </form>\n );\n}\n","import { useContext } from 'react';\nimport type { FloPay, FloPayElements } from '@flopay/js';\nimport type { CheckoutSession, FloPayError } from '@flopay/shared';\nimport { resolveBillingApiUrl } from '@flopay/shared';\nimport { FloPayContext, CheckoutContext } from './context.js';\nimport type { CheckoutContextValue } from './context.js';\n\n/**\n * Returns the current `FloPay` instance, or `null` if the provider\n * is still loading (i.e. the `loadFloPay()` promise has not resolved yet).\n *\n * Must be called within a `<FloPayProvider>`.\n */\nexport function useFloPay(): FloPay | null {\n const ctx = useContext(FloPayContext);\n return ctx.flopay;\n}\n\n/**\n * Returns the dedicated PayPal `FloPay` instance (loaded with\n * `gatewayData.paypalPublishableKey`), or `null` if PayPal is disabled\n * for this session.\n *\n * Must be called within a `<FloPayProvider>`.\n */\nexport function usePayPalFloPay(): FloPay | null {\n const ctx = useContext(FloPayContext);\n return ctx.paypalFlopay ?? null;\n}\n\n/**\n * Returns the current `FloPayElements` instance, or `null` if the\n * provider is still loading.\n *\n * Must be called within a `<FloPayProvider>`.\n */\nexport function useElements(): FloPayElements | null {\n const ctx = useContext(FloPayContext);\n return ctx.elements;\n}\n\n/** Checkout state exposed by `useCheckout()`. */\nexport interface CheckoutState {\n session: CheckoutSession | null;\n loading: boolean;\n error: FloPayError | null;\n}\n\n/**\n * Returns the current checkout session state.\n *\n * Must be called within a `<CheckoutProvider>` (typically rendered\n * internally by `<CheckoutForm>`).\n */\nexport function useCheckout(): CheckoutState {\n return useContext(CheckoutContext);\n}\n\n/**\n * Returns the resolved billing API URL from the provider context.\n * Falls back to the default `BILLING_API_URL` constant.\n */\nexport function useBillingApiUrl(): string {\n const ctx = useContext(FloPayContext);\n return ctx.billingApiUrl || resolveBillingApiUrl();\n}\n","import React from 'react';\n\nexport type OverlayStatus = 'processing' | 'success' | 'error';\n\nexport const PROCESSING_OVERLAY_SUCCESS_DELAY_MS = 1200;\nexport const PROCESSING_OVERLAY_ERROR_DELAY_MS = 1500;\n\nexport function ProcessingOverlay({\n status,\n errorMessage,\n}: {\n status: OverlayStatus;\n errorMessage?: string | null;\n}) {\n return (\n <div\n data-testid=\"flopay-processing-overlay\"\n data-status={status}\n role=\"dialog\"\n aria-modal=\"true\"\n style={{\n position: 'fixed',\n inset: 0,\n background: 'rgba(0,0,0,0.35)',\n display: 'flex',\n alignItems: 'center',\n justifyContent: 'center',\n zIndex: 1000,\n backdropFilter: 'blur(2px)',\n }}\n >\n <div\n style={{\n background: 'white',\n borderRadius: 12,\n padding: '2rem 2.5rem',\n textAlign: 'center',\n boxShadow: '0 8px 32px rgba(0,0,0,0.18)',\n minWidth: 240,\n display: 'flex',\n flexDirection: 'column',\n alignItems: 'center',\n gap: 16,\n }}\n >\n <div style={{ width: 48, height: 48, position: 'relative' }}>\n {status === 'processing' && (\n <svg\n width=\"48\"\n height=\"48\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n xmlns=\"http://www.w3.org/2000/svg\"\n style={{ animation: 'flopay-spin 0.8s linear infinite' }}\n >\n <circle cx=\"12\" cy=\"12\" r=\"10\" stroke=\"#e5e7eb\" strokeWidth=\"3\" />\n <path d=\"M4 12a8 8 0 018-8v3a5 5 0 00-5 5H4z\" fill=\"#4A49FF\" />\n </svg>\n )}\n {status === 'success' && (\n <div style={{ animation: 'flopay-pop 0.4s cubic-bezier(0.34,1.56,0.64,1)' }}>\n <svg width=\"48\" height=\"48\" viewBox=\"0 0 24 24\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\">\n <circle cx=\"12\" cy=\"12\" r=\"11\" fill=\"#22c55e\" />\n <path\n d=\"M7 12.5l3 3 7-7\"\n stroke=\"white\"\n strokeWidth=\"2.5\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n style={{\n strokeDasharray: 20,\n strokeDashoffset: 20,\n animation: 'flopay-draw 0.4s 0.15s ease forwards',\n }}\n />\n </svg>\n </div>\n )}\n {status === 'error' && (\n <div style={{ animation: 'flopay-shake 0.4s ease' }}>\n <svg width=\"48\" height=\"48\" viewBox=\"0 0 24 24\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\">\n <circle cx=\"12\" cy=\"12\" r=\"11\" fill=\"#ef4444\" />\n <path\n d=\"M8 8l8 8M16 8l-8 8\"\n stroke=\"white\"\n strokeWidth=\"2.5\"\n strokeLinecap=\"round\"\n style={{\n strokeDasharray: 12,\n strokeDashoffset: 12,\n animation: 'flopay-draw 0.3s 0.1s ease forwards',\n }}\n />\n </svg>\n </div>\n )}\n </div>\n <span\n style={{\n fontSize: 14,\n fontWeight: 600,\n letterSpacing: '0.05em',\n color: status === 'success' ? '#16a34a' : status === 'error' ? '#dc2626' : '#374151',\n }}\n >\n {status === 'processing' && 'PROCESSING...'}\n {status === 'success' && 'PAYMENT SUCCESSFUL'}\n {status === 'error' && 'PAYMENT FAILED'}\n </span>\n {status === 'success' && (\n <p\n style={{\n fontSize: 13,\n color: '#6b7280',\n fontWeight: 400,\n maxWidth: 260,\n lineHeight: 1.4,\n margin: 0,\n }}\n >\n You will be automatically redirected, do not close or navigate away from this window.\n </p>\n )}\n {status === 'error' && errorMessage && (\n <p\n style={{\n fontSize: 13,\n color: '#6b7280',\n fontWeight: 400,\n maxWidth: 260,\n lineHeight: 1.4,\n margin: 0,\n }}\n >\n {errorMessage}\n </p>\n )}\n <style>{`\n @keyframes flopay-spin { to { transform: rotate(360deg); } }\n @keyframes flopay-pop { 0% { transform: scale(0); } 100% { transform: scale(1); } }\n @keyframes flopay-draw { to { stroke-dashoffset: 0; } }\n @keyframes flopay-shake { 0%,100% { transform: translateX(0); } 20%,60% { transform: translateX(-4px); } 40%,80% { transform: translateX(4px); } }\n `}</style>\n </div>\n </div>\n );\n}\n","import type {\n CheckoutAccount,\n CheckoutButtonMethod,\n CheckoutMode,\n CheckoutSession,\n DeclineEvent,\n InlineSessionDraft,\n InlineSessionParams,\n InlineSessionPatch,\n PaymentResult,\n TokenizedBody,\n} from '@flopay/shared';\nimport { FloPayError } from '@flopay/shared';\n\nexport function mergeInlineSessionPatches(\n base: InlineSessionPatch | undefined,\n patch: InlineSessionPatch | undefined,\n): InlineSessionPatch | undefined {\n if (!patch) return base;\n if (!base) return patch;\n\n return {\n account: { ...(base.account ?? {}), ...(patch.account ?? {}) },\n couponCodes: patch.couponCodes ?? base.couponCodes,\n tagsData: {\n ...(base.tagsData ?? {}),\n ...(patch.tagsData ?? {}),\n },\n utmMetadata: patch.utmMetadata ?? base.utmMetadata,\n };\n}\n\nexport function mergeInlineSessionPatch(\n params: InlineSessionDraft,\n patch: InlineSessionPatch | undefined,\n): InlineSessionDraft {\n if (!patch) return params;\n\n return {\n ...params,\n account: {\n ...params.account,\n ...(patch.account ?? {}),\n },\n couponCodes: patch.couponCodes ?? params.couponCodes,\n tagsData: {\n ...(params.tagsData ?? {}),\n ...(patch.tagsData ?? {}),\n },\n utmMetadata: patch.utmMetadata ?? params.utmMetadata,\n };\n}\n\nexport function buildSyntheticSession(\n params: InlineSessionDraft,\n checkoutModeOverride?: CheckoutMode,\n): CheckoutSession {\n const totalAmount = [\n ...(params.items ?? []).map((item) => (item.overrideAmount ?? item.totalAmount) ?? 0),\n ...(params.subscriptions ?? []).map((subscription) => (subscription.overrideAmount ?? subscription.totalAmount) ?? 0),\n ].reduce((sum, value) => sum + value, 0);\n const currency = params.items?.[0]?.currency\n ?? params.subscriptions?.[0]?.currency\n ?? 'USD';\n\n return {\n id: '',\n clientSecret: '',\n mode: 'payment',\n amount: Math.round(totalAmount * 100),\n currency,\n status: 'open',\n customer: {\n id: params.account.userId,\n email: params.account.email ?? '',\n firstName: params.account.firstName,\n lastName: params.account.lastName,\n gender: params.account.gender ?? undefined,\n city: params.account.city ?? undefined,\n state: params.account.state ?? undefined,\n country: params.account.country ?? undefined,\n zip: params.account.zip ?? undefined,\n },\n successUrl: params.successUrl,\n cancelUrl: params.cancelUrl,\n checkoutMode: (checkoutModeOverride ?? params.checkoutMode ?? 'full') as CheckoutMode,\n items: (params.items ?? []).map((item, idx) => ({\n uuid: `synthetic-item-${idx}`,\n checkoutSessionId: '',\n providerItemId: item.providerItemId,\n providerItemName: item.providerItemName ?? item.providerItemId,\n quantity: item.quantity ?? 1,\n totalAmount: item.totalAmount,\n overrideAmount: item.overrideAmount ?? null,\n currency: item.currency ?? currency,\n })),\n subscriptions: (params.subscriptions ?? []).map((subscription, idx) => ({\n uuid: `synthetic-sub-${idx}`,\n checkoutSessionId: '',\n providerPlanId: subscription.providerPlanId,\n providerPlanName: subscription.providerPlanName ?? subscription.providerPlanId,\n quantity: subscription.quantity ?? 1,\n totalAmount: subscription.totalAmount,\n overrideAmount: subscription.overrideAmount ?? null,\n currency: subscription.currency ?? currency,\n })),\n };\n}\n\nexport function ensureInlineSessionReady(\n params: InlineSessionDraft,\n): asserts params is InlineSessionParams {\n if (!params.account.email?.trim()) {\n throw new FloPayError(\n 'Email is required before continuing with card checkout.',\n 'validation_error',\n { param: 'createSession.account.email' },\n );\n }\n}\n\nexport function splitFullName(name: string | null | undefined): {\n firstName?: string;\n lastName?: string;\n} {\n const parts = name?.trim().split(/\\s+/).filter(Boolean) ?? [];\n if (parts.length === 0) return {};\n return {\n firstName: parts[0],\n lastName: parts.length > 1 ? parts.slice(1).join(' ') : undefined,\n };\n}\n\nexport function mergeAccountPatch<T extends {\n userId?: string;\n email?: string;\n firstName?: string;\n lastName?: string;\n country?: string | null;\n zip?: string | null;\n}>(\n base: T,\n patch: Partial<CheckoutAccount> | undefined,\n): T {\n if (!patch) return base;\n return {\n ...base,\n ...patch,\n };\n}\n\nexport function buildDeclineEvent(\n method: CheckoutButtonMethod,\n input: string | FloPayError,\n overrides?: {\n code?: string;\n declineCode?: string;\n },\n): DeclineEvent {\n const message = typeof input === 'string' ? input : input.message;\n const code = typeof input === 'string' ? overrides?.code : overrides?.code ?? input.code;\n const declineCode = typeof input === 'string'\n ? overrides?.declineCode\n : overrides?.declineCode ?? input.declineCode;\n\n return {\n method,\n message,\n ...(code ? { code } : {}),\n ...(declineCode ? { declineCode } : {}),\n };\n}\n\ntype ApiErrorPayload = Record<string, unknown> | null;\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null;\n}\n\nfunction readString(payload: ApiErrorPayload, key: string): string | undefined {\n const value = payload?.[key];\n return typeof value === 'string' && value.trim() ? value : undefined;\n}\n\nexport function buildFloPayApiError(\n payload: ApiErrorPayload,\n fallbackMessage: string,\n): FloPayError {\n const nestedError = isRecord(payload?.error) ? payload.error : null;\n const message =\n readString(payload, 'message') ??\n readString(nestedError, 'message') ??\n fallbackMessage;\n const code =\n readString(payload, 'code') ??\n readString(payload, 'gatewayErrorCode') ??\n readString(nestedError, 'code');\n const declineCode =\n readString(payload, 'declineCode') ??\n readString(payload, 'gatewayDeclineReason') ??\n readString(payload, 'decline_code') ??\n readString(nestedError, 'decline_code');\n\n return new FloPayError(message, 'api_error', {\n ...(code ? { code } : {}),\n ...(declineCode ? { declineCode } : {}),\n });\n}\n\nexport async function buildFloPayApiErrorFromResponse(\n response: Response,\n fallbackMessage: string,\n): Promise<FloPayError> {\n const payload = await response.json().catch(() => null) as ApiErrorPayload;\n return buildFloPayApiError(payload, fallbackMessage);\n}\n\nexport function mapPayPalIntentStatusToPaymentResult(\n status: string | null | undefined,\n): PaymentResult['status'] {\n if (status === 'succeeded') {\n return 'succeeded';\n }\n\n if (status === 'processing' || status === 'requires_capture') {\n return 'processing';\n }\n\n return 'failed';\n}\n\nexport type StripePaymentIntentLike = {\n id?: string;\n status?: string;\n payment_method?: string | { id?: string | null } | null;\n};\n\ntype PaymentIntentRetriever = {\n retrievePaymentIntent?: (clientSecret: string) => Promise<{\n paymentIntent?: StripePaymentIntentLike | null;\n error?: { message?: string; code?: string };\n }>;\n};\n\nexport function resolvePaymentIntentPaymentMethodId(\n paymentIntent: StripePaymentIntentLike | null | undefined,\n): string | undefined {\n const paymentMethod = paymentIntent?.payment_method;\n if (typeof paymentMethod === 'string' && paymentMethod.startsWith('pm_')) {\n return paymentMethod;\n }\n if (paymentMethod && typeof paymentMethod === 'object' && typeof paymentMethod.id === 'string') {\n return paymentMethod.id;\n }\n return undefined;\n}\n\nexport async function retrievePaymentIntentFromProvider(\n provider: unknown,\n clientSecret: string,\n): Promise<StripePaymentIntentLike | null> {\n const retriever = provider as PaymentIntentRetriever | null;\n if (!retriever?.retrievePaymentIntent) {\n return null;\n }\n\n const { paymentIntent, error } = await retriever.retrievePaymentIntent(clientSecret);\n if (error) {\n throw new FloPayError(error.message ?? 'Failed to retrieve payment intent.', 'api_error', {\n ...(error.code ? { code: error.code } : {}),\n });\n }\n\n return paymentIntent ?? null;\n}\n\nexport function resolveTokenizedPaymentMethodId(\n tokenizedBody: TokenizedBody | null | undefined,\n): string | undefined {\n const candidates = [\n tokenizedBody?.id,\n tokenizedBody?.originalPaymentMethodId,\n ];\n\n for (const candidate of candidates) {\n if (typeof candidate === 'string' && candidate.startsWith('pm_')) {\n return candidate;\n }\n }\n\n return undefined;\n}\n","// Cross-component, cross-remount signal for \"this session was just /process'd\n// successfully and is mid-completion.\" Written synchronously by SplitCardForm\n// (and the saved-payment / auto-mode flows in FloPayCheckout) the moment the\n// `/process` response is OK — *before* the 1.2s success-overlay delay — so a\n// bootstrap that re-runs during the overlay window can detect that the cache\n// hit's `status: 'complete'` is from THIS journey rather than treat it as\n// a stale leftover and POST a duplicate session.\n//\n// Backed by `sessionStorage` rather than module state because:\n// 1. SplitCardForm and FloPayCheckout are different modules; sessionStorage\n// is the cheapest cross-module bus.\n// 2. It survives a real component remount (which resets useRef/useState)\n// without needing a module-level Map.\n// 3. The TTL gives natural staleness — a buyer who genuinely returns to\n// `/checkout` long after a previous successful checkout still gets the\n// \"clear stale cache and POST a fresh session\" path.\n\nconst STORAGE_KEY_PREFIX = 'flopay_recent_completion_';\nconst RECENT_COMPLETION_TTL_MS = 60 * 1000;\n\ninterface PersistedRecentCompletion {\n expiresAt: number;\n}\n\nexport function markSessionRecentlyCompleted(sessionId: string | null | undefined): void {\n if (!sessionId || typeof window === 'undefined') return;\n try {\n const payload: PersistedRecentCompletion = {\n expiresAt: Date.now() + RECENT_COMPLETION_TTL_MS,\n };\n window.sessionStorage.setItem(STORAGE_KEY_PREFIX + sessionId, JSON.stringify(payload));\n } catch {\n // sessionStorage unavailable (private mode etc.); not safety-critical.\n }\n}\n\nexport function wasSessionRecentlyCompleted(sessionId: string | null | undefined): boolean {\n if (!sessionId || typeof window === 'undefined') return false;\n try {\n const raw = window.sessionStorage.getItem(STORAGE_KEY_PREFIX + sessionId);\n if (!raw) return false;\n const parsed = JSON.parse(raw) as PersistedRecentCompletion;\n if (typeof parsed?.expiresAt !== 'number') {\n window.sessionStorage.removeItem(STORAGE_KEY_PREFIX + sessionId);\n return false;\n }\n if (parsed.expiresAt <= Date.now()) {\n window.sessionStorage.removeItem(STORAGE_KEY_PREFIX + sessionId);\n return false;\n }\n return true;\n } catch {\n return false;\n }\n}\n","import React, { useCallback, useEffect, useState } from 'react';\nimport { isInAppBrowser } from './in-app-browser.js';\n\nexport interface InAppBrowserNoticeProps {\n /** Custom message override. Defaults to a generic, non-platform-specific copy. */\n message?: React.ReactNode;\n /** Custom button label. Default depends on the detected environment:\n * in-app browser → \"Copy link\"; other → \"Open in browser\". */\n openButtonLabel?: string;\n /** Custom copied-state button label. Default depends on environment. */\n copiedButtonLabel?: string;\n /** Custom CSS overrides for the container, message, and button. */\n containerStyle?: React.CSSProperties;\n buttonStyle?: React.CSSProperties;\n /** Called when the user clicks the open-in-browser button. */\n onOpenInBrowser?: (result: { opened: boolean; copied: boolean }) => void;\n}\n\nconst DEFAULT_MESSAGE\n = \"PayPal and some digital wallets aren't supported in this browser. Open this page in your device's browser to use them.\";\n\n/**\n * Non-disruptive notice rendered when PayPal and digital wallets fail to load\n * — typically because the buyer is in an in-app browser (Instagram, Facebook,\n * TikTok, etc.) or behind an ad-blocker. The card form remains fully\n * functional; this notice just informs the buyer about the unavailable\n * methods and gives them a way to escape to a real browser.\n *\n * Action behavior is environment-dependent because `window.open` is a known\n * liar inside in-app WebViews:\n *\n * - **Detected in-app browser** (Facebook/Instagram/TikTok/etc. via UA):\n * skip `window.open` entirely. It returns a non-null window but the new\n * page opens *inside the same WebView*, which defeats the entire point\n * and makes us mis-report `opened: true` to `onOpenInBrowser`. Instead,\n * copy the URL to clipboard and surface clear paste-in-Safari/Chrome\n * messaging. There is no reliable cross-platform JS API to force a\n * WebView to defer to the system browser; the buyer must use the host\n * app's \"...\" / \"⋮\" menu.\n * - **Other environments** (desktop with ad-blocker, unknown UA):\n * `window.open` may genuinely succeed — try it, fall back to clipboard.\n */\nexport function InAppBrowserNotice({\n message,\n openButtonLabel,\n copiedButtonLabel,\n containerStyle,\n buttonStyle,\n onOpenInBrowser,\n}: InAppBrowserNoticeProps) {\n const [copied, setCopied] = useState(false);\n const [inAppBrowser, setInAppBrowser] = useState(false);\n\n useEffect(() => {\n setInAppBrowser(isInAppBrowser());\n }, []);\n\n const defaultOpenLabel = inAppBrowser ? 'Copy link' : 'Open in browser';\n const defaultCopiedLabel = inAppBrowser\n ? 'Link copied — open Safari/Chrome and paste'\n : 'Link copied — paste in your browser';\n const effectiveOpenLabel = openButtonLabel ?? defaultOpenLabel;\n const effectiveCopiedLabel = copiedButtonLabel ?? defaultCopiedLabel;\n\n const handleClick = useCallback(async () => {\n if (typeof window === 'undefined') return;\n const url = window.location.href;\n\n let opened = false;\n if (!inAppBrowser) {\n // Outside known WebViews `window.open` may genuinely succeed (desktop\n // with ad-blocker, etc.) — try it. Inside a known WebView we skip it\n // because Stripe's iframe / our own testing confirmed: the new tab\n // opens inside the same WebView and we'd mis-report \"opened\" to the\n // consumer while the buyer is no closer to a working PayPal button.\n try {\n const win = window.open(url, '_blank');\n opened = !!win;\n } catch {\n opened = false;\n }\n }\n\n let didCopy = false;\n if (!opened) {\n // Optional-chaining `await navigator.clipboard?.writeText(url)` resolves\n // to `undefined` when `clipboard` is missing (older WebViews, insecure\n // contexts) — without the explicit guard we'd silently mark `didCopy`\n // true even though nothing was copied, mislead the user with the\n // \"Link copied\" label, and emit an incorrect onOpenInBrowser result.\n if (typeof navigator !== 'undefined' && typeof navigator.clipboard?.writeText === 'function') {\n try {\n await navigator.clipboard.writeText(url);\n didCopy = true;\n setCopied(true);\n } catch {\n didCopy = false;\n }\n }\n }\n\n onOpenInBrowser?.({ opened, copied: didCopy });\n }, [inAppBrowser, onOpenInBrowser]);\n\n return (\n <div\n role=\"status\"\n data-testid=\"flopay-in-app-browser-notice\"\n style={{\n marginTop: '0.75rem',\n padding: '0.75rem 0.875rem',\n background: '#FFFBEB',\n border: '1px solid #FDE68A',\n borderRadius: 8,\n color: '#92400E',\n fontSize: '0.85rem',\n lineHeight: 1.4,\n display: 'flex',\n flexDirection: 'column',\n gap: '0.5rem',\n ...containerStyle,\n }}\n >\n <span>{message ?? DEFAULT_MESSAGE}</span>\n <button\n type=\"button\"\n onClick={handleClick}\n style={{\n alignSelf: 'flex-start',\n padding: '0.4rem 0.75rem',\n background: 'transparent',\n border: '1px solid #92400E',\n borderRadius: 6,\n color: '#92400E',\n fontSize: '0.85rem',\n fontWeight: 600,\n cursor: 'pointer',\n ...buttonStyle,\n }}\n >\n {copied ? effectiveCopiedLabel : effectiveOpenLabel}\n </button>\n </div>\n );\n}\n","/**\n * Heuristic detector for in-app browser / WebView environments where PayPal\n * and digital wallets often fail to initialize.\n *\n * Pairs with the load-state classifier in `SplitCardForm`: this gives us a\n * proactive signal (we know we're in a hostile environment before Stripe\n * even tries), while load state covers the long tail (ad-blockers, new\n * WebViews we haven't seen, account-misconfig surfacing as `unavailable`).\n *\n * Tradeoffs:\n * - False positives possible. Some modern WebViews (iOS SFSafariViewController\n * on recent iOS, Chrome Custom Tabs) handle PayPal fine but match these\n * patterns. The notice is non-disruptive — card form keeps working — so we\n * accept it.\n * - False negatives possible. New social-app WebViews ship without us knowing.\n * That's why we also keep the reactive load-state signal.\n *\n * SSR-safe: returns `false` when `navigator` is undefined.\n */\nexport function isInAppBrowser(userAgent?: string): boolean {\n const ua = userAgent ?? (typeof navigator !== 'undefined' ? navigator.userAgent : '');\n if (!ua) return false;\n\n // Named in-app browsers — most common offenders.\n // FBAN/FBAV/FB_IAB/FBIOS = Facebook + Messenger.\n // musical_ly/BytedanceWebview/TikTok = TikTok across regions.\n if (/FBAN|FBAV|FB_IAB|FBIOS|Instagram|musical_ly|BytedanceWebview|TikTok/i.test(ua)) {\n return true;\n }\n if (/Twitter|Snapchat|Pinterest|LinkedInApp|Line\\/|MicroMessenger|GSA\\//i.test(ua)) {\n return true;\n }\n\n // Generic Android WebView: Chrome UA with the `; wv)` token.\n if (/Android.*;\\s?wv\\)/.test(ua)) return true;\n\n // Generic iOS WebView: iPhone/iPad/iPod with AppleWebKit but no `Safari/`\n // token. Real Mobile Safari always emits `Safari/` — WebViews don't.\n if (/(iPhone|iPad|iPod).*AppleWebKit(?!.*Safari)/.test(ua)) return true;\n\n return false;\n}\n","import type {FloPay} from '@flopay/js';\nimport {loadFloPay, PaymentAPI} from '@flopay/js';\nimport type {\n CheckoutButtonMethod,\n CheckoutProcessError,\n CheckoutSession,\n NormalizedCheckoutSession,\n PaymentResult,\n TokenizedBody,\n} from '@flopay/shared';\nimport {FloPayError} from '@flopay/shared';\nimport {\n buildFloPayApiError,\n resolvePaymentIntentPaymentMethodId,\n resolveTokenizedPaymentMethodId,\n retrievePaymentIntentFromProvider,\n} from './checkout-utils.js';\n\nexport const DEFAULT_SAVED_PAYMENT_DECLINE_METHOD: CheckoutButtonMethod = 'card';\n\nexport type ProcessRedirectResult = {\n type: 'paypal_redirect_required' | '3ds_required';\n threeDSecureToken: string;\n paymentMethodId?: string;\n};\n\nexport type SavedPaymentProcessResult =\n | ProcessRedirectResult\n | {\n type: 'success';\n result: PaymentResult;\n };\n\nexport type SavedPaymentFlowError = FloPayError & {\n checkoutMethod?: CheckoutButtonMethod;\n};\n\nexport function getRedirectResultFromCheckoutProcessError(\n error?: CheckoutProcessError | null,\n): ProcessRedirectResult | null {\n if (!error?.type || !error.threeDSecureToken) {\n return null;\n }\n\n if (\n error.type !== '3ds_required' &&\n error.type !== 'paypal_redirect_required'\n ) {\n return null;\n }\n\n return {\n type: error.type,\n threeDSecureToken: error.threeDSecureToken,\n paymentMethodId: error.paymentMethodId,\n };\n}\n\nexport function checkoutProcessErrorToFloPayError(\n error?: CheckoutProcessError | null,\n fallbackMessage = 'Payment failed. Please try again.',\n options?: {\n checkoutMethod?: CheckoutButtonMethod;\n },\n): SavedPaymentFlowError {\n const checkoutMethod = options?.checkoutMethod\n ?? error?.checkoutMethod\n ?? (error?.type === 'paypal_redirect_required'\n ? 'paypal' as const\n : 'card' as const);\n\n return Object.assign(\n new FloPayError(\n error?.message ?? fallbackMessage,\n 'api_error',\n {\n code: error?.gatewayErrorCode,\n },\n ),\n { checkoutMethod },\n ) satisfies SavedPaymentFlowError;\n}\n\nfunction resolveSavedPaymentReturnUrl(session: CheckoutSession): string | undefined {\n if (typeof window !== 'undefined' && window.location.href) {\n return window.location.href;\n }\n\n return session.successUrl || session.cancelUrl || undefined;\n}\n\nfunction isStripePaymentIntentClientSecret(value: unknown): value is string {\n return typeof value === 'string'\n && value.startsWith('pi_')\n && value.includes('_secret_');\n}\n\nasync function retryOnceOnFetchFailure<T>(action: () => Promise<T>): Promise<T> {\n try {\n return await action();\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n if (!/failed to fetch|fetch failed/i.test(message)) {\n throw err;\n }\n\n return action();\n }\n}\n\nfunction getRedirectTokenFromProcessResponse(\n json: Record<string, unknown> | null,\n options?: { requirePaymentIntentClientSecret?: boolean },\n): string | undefined {\n const directCandidates = [\n json?.threeDSecureToken,\n json?.clientSecret,\n json?.stripeClientSecret,\n ];\n for (const candidate of directCandidates) {\n if (\n typeof candidate === 'string'\n && candidate.length > 0\n && (\n !options?.requirePaymentIntentClientSecret\n || isStripePaymentIntentClientSecret(candidate)\n )\n ) {\n return candidate;\n }\n }\n\n const nested = json?.data;\n if (nested && typeof nested === 'object') {\n const nestedRecord = nested as Record<string, unknown>;\n const nestedCandidates = [\n nestedRecord.threeDSecureToken,\n nestedRecord.clientSecret,\n nestedRecord.stripeClientSecret,\n nestedRecord.id,\n ];\n for (const candidate of nestedCandidates) {\n if (\n typeof candidate === 'string'\n && candidate.length > 0\n && (\n !options?.requirePaymentIntentClientSecret\n || isStripePaymentIntentClientSecret(candidate)\n )\n ) {\n return candidate;\n }\n }\n\n const nestedGatewayData = nestedRecord.gatewayData;\n if (nestedGatewayData && typeof nestedGatewayData === 'object') {\n const nestedGatewayDataRecord = nestedGatewayData as Record<string, unknown>;\n const gatewayCandidates = [\n nestedGatewayDataRecord.stripeClientSecret,\n nestedGatewayDataRecord.clientSecret,\n ];\n for (const candidate of gatewayCandidates) {\n if (\n typeof candidate === 'string'\n && candidate.length > 0\n && (\n !options?.requirePaymentIntentClientSecret\n || isStripePaymentIntentClientSecret(candidate)\n )\n ) {\n return candidate;\n }\n }\n }\n }\n\n return undefined;\n}\n\nasync function recover3DSRedirectResult({\n billingApiUrl,\n sessionId,\n responseJson,\n}: {\n billingApiUrl: string;\n sessionId?: string | null;\n responseJson: Record<string, unknown> | null;\n}): Promise<ProcessRedirectResult | null> {\n const directToken = getRedirectTokenFromProcessResponse(responseJson, {\n requirePaymentIntentClientSecret: true,\n });\n if (typeof directToken === 'string' && directToken.length > 0) {\n return {\n type: '3ds_required',\n threeDSecureToken: directToken,\n };\n }\n\n if (!sessionId) {\n return null;\n }\n\n try {\n const api = new PaymentAPI(billingApiUrl);\n const unified = await api.getUnifiedCheckoutSession(sessionId);\n const refreshedToken = unified.provider === 'stripe'\n ? unified.data.stripe?.clientSecret\n : undefined;\n\n if (isStripePaymentIntentClientSecret(refreshedToken)) {\n return {\n type: '3ds_required',\n threeDSecureToken: refreshedToken,\n };\n }\n } catch {\n // Preserve the original authentication_required error if the recovery fetch fails.\n }\n\n return null;\n}\n\nexport async function processSavedPaymentForMode({\n billingApiUrl,\n sessionId,\n session,\n tokenizedData,\n returnUrl,\n}: {\n billingApiUrl: string;\n sessionId?: string | null;\n session: CheckoutSession;\n tokenizedData?: TokenizedBody;\n returnUrl?: string;\n}): Promise<SavedPaymentProcessResult> {\n const baseUrl = billingApiUrl.replace(/\\/+$/, '');\n const resolvedSessionId = sessionId ?? session.id;\n const customerId = session.customer?.id ?? session.accountData?.userId ?? '';\n const customerEmail = session.customer?.email ?? session.accountData?.email ?? '';\n const firstName = session.customer?.firstName ?? session.accountData?.firstName ?? '';\n const lastName = session.customer?.lastName ?? session.accountData?.lastName ?? '';\n const country = session.customer?.country ?? session.accountData?.country ?? undefined;\n const zip = session.customer?.zip ?? session.accountData?.zip ?? undefined;\n\n const response = await retryOnceOnFetchFailure(() => fetch(`${baseUrl}/v1/checkouts/sessions/process`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'x-user-id': customerId,\n },\n body: JSON.stringify({\n sessionId: resolvedSessionId,\n tokenizedData,\n accountData: {\n userId: customerId,\n email: customerEmail,\n firstName,\n lastName,\n country,\n zip,\n },\n returnUrl: returnUrl ?? resolveSavedPaymentReturnUrl(session),\n }),\n }));\n\n if (response.ok) {\n return {\n type: 'success',\n result: {\n status: 'succeeded',\n paymentIntentId: tokenizedData?.threeDSecureActionResultTokenId,\n paymentMethodId: resolveTokenizedPaymentMethodId(tokenizedData),\n checkoutMethod: tokenizedData\n ? tokenizedData.isPaypal ? 'paypal' : 'card'\n : undefined,\n },\n };\n }\n\n const json = (await response.json().catch(() => null)) as Record<string, unknown> | null;\n\n if (\n (json?.type === 'paypal_redirect_required' || json?.type === '3ds_required')\n ) {\n const redirectToken = getRedirectTokenFromProcessResponse(json);\n if (!redirectToken) {\n throw new FloPayError(\n 'Authentication is required but no redirect token was provided.',\n 'api_error',\n { code: 'authentication_required' },\n );\n }\n\n return {\n type: json.type as ProcessRedirectResult['type'],\n threeDSecureToken: redirectToken,\n paymentMethodId: json.paymentMethodId as string | undefined,\n };\n }\n\n if (json?.gatewayErrorCode === 'authentication_required') {\n const recoveredRedirect = await recover3DSRedirectResult({\n billingApiUrl: baseUrl,\n sessionId: resolvedSessionId,\n responseJson: json,\n });\n\n if (recoveredRedirect) {\n return recoveredRedirect;\n }\n\n throw Object.assign(\n new FloPayError(\n 'Your card requires authentication. Please enter your payment details below.',\n 'api_error',\n { code: 'authentication_required' },\n ),\n { checkoutMethod: 'card' as CheckoutButtonMethod },\n ) satisfies SavedPaymentFlowError;\n }\n\n throw new FloPayError(\n (json?.message as string) ?? 'Payment failed. Please try again.',\n 'api_error',\n {\n code: (json?.code ?? json?.gatewayErrorCode) as string | undefined,\n declineCode: (json?.declineCode ?? json?.gatewayDeclineReason) as string | undefined,\n },\n );\n}\n\nexport async function processSavedPaymentWithIntent({\n billingApiUrl,\n sessionId,\n session,\n paymentMethodId,\n flopay,\n returnUrl,\n}: {\n billingApiUrl: string;\n sessionId: string;\n session: CheckoutSession;\n paymentMethodId: string;\n flopay: FloPay;\n returnUrl?: string;\n}): Promise<PaymentResult> {\n const customerEmail = session.customer?.email ?? session.accountData?.email ?? '';\n if (!customerEmail) {\n throw Object.assign(\n new FloPayError('Customer email is required to create a payment intent.', 'validation_error', {\n param: 'email',\n }),\n { checkoutMethod: 'card' as CheckoutButtonMethod },\n ) satisfies SavedPaymentFlowError;\n }\n\n const api = new PaymentAPI(billingApiUrl);\n const intentResponse = await retryOnceOnFetchFailure(() => api.createPaymentIntent(\n sessionId,\n customerEmail,\n paymentMethodId,\n ));\n const intentJson = (await intentResponse.json().catch(() => null)) as Record<string, unknown> | null;\n\n if (!intentResponse.ok) {\n const intentError = buildFloPayApiError(\n intentJson,\n 'Failed to create payment intent.',\n );\n\n throw Object.assign(\n intentError,\n { checkoutMethod: 'card' as CheckoutButtonMethod },\n ) satisfies SavedPaymentFlowError;\n }\n\n const intentClientSecret = getRedirectTokenFromProcessResponse(intentJson, {\n requirePaymentIntentClientSecret: true,\n });\n if (!intentClientSecret) {\n throw Object.assign(\n new FloPayError('No client secret in payment intent response.', 'api_error'),\n { checkoutMethod: 'card' as CheckoutButtonMethod },\n ) satisfies SavedPaymentFlowError;\n }\n\n const confirmResult = await flopay.confirmCardPayment({\n clientSecret: intentClientSecret,\n paymentMethodId,\n });\n\n if (confirmResult.error) {\n throw Object.assign(\n confirmResult.error,\n { checkoutMethod: 'card' as CheckoutButtonMethod },\n ) satisfies SavedPaymentFlowError;\n }\n\n const rawProvider = typeof flopay.getRawProvider === 'function' ? flopay.getRawProvider() : null;\n const confirmedPaymentIntent = await retrievePaymentIntentFromProvider(\n rawProvider,\n intentClientSecret,\n );\n const confirmedPaymentIntentId = confirmResult.paymentIntentId ?? confirmedPaymentIntent?.id;\n const confirmedPaymentMethodId =\n confirmResult.paymentMethodId\n ?? resolvePaymentIntentPaymentMethodId(confirmedPaymentIntent)\n ?? paymentMethodId;\n\n if (\n !confirmedPaymentIntentId\n || (\n confirmResult.status !== 'succeeded'\n && confirmResult.status !== 'processing'\n && confirmResult.status !== 'requires_capture'\n )\n ) {\n throw Object.assign(\n new FloPayError(\n `Unfortunately, your payment could not be processed. Please try again using a different payment method or contact your bank for assistance. If the issue persists, feel free to reach out to us for support.`,\n 'api_error',\n {\n code: confirmResult.status === 'requires_action'\n ? 'authentication_required'\n : undefined,\n },\n ),\n { checkoutMethod: 'card' as CheckoutButtonMethod },\n ) satisfies SavedPaymentFlowError;\n }\n\n const followUp = await processSavedPaymentForMode({\n billingApiUrl,\n sessionId,\n session,\n tokenizedData: {\n id: confirmedPaymentMethodId,\n type: 'card',\n threeDSecureActionResultTokenId: confirmedPaymentIntentId,\n },\n returnUrl,\n });\n\n const finalResult = followUp.type === 'success'\n ? followUp.result\n : await handleSavedPaymentRedirectResult(followUp, {\n flopay,\n paypalFlopay: null,\n attempt3DS: true,\n billingApiUrl,\n sessionId,\n session,\n returnUrl,\n });\n\n return {\n ...finalResult,\n paymentIntentId: finalResult.paymentIntentId ?? confirmedPaymentIntentId,\n paymentMethodId: finalResult.paymentMethodId ?? confirmedPaymentMethodId,\n checkoutMethod: finalResult.checkoutMethod ?? 'card',\n };\n}\n\nexport async function handleSavedPaymentRedirectResult(\n redirectResult: ProcessRedirectResult,\n {\n flopay,\n paypalFlopay,\n attempt3DS,\n billingApiUrl,\n sessionId,\n session,\n returnUrl,\n }: {\n flopay: FloPay | null;\n paypalFlopay: FloPay | null;\n attempt3DS?: boolean;\n billingApiUrl: string;\n sessionId?: string | null;\n session: CheckoutSession;\n returnUrl?: string;\n },\n): Promise<PaymentResult> {\n const stripe = flopay?.getRawProvider() as import('@stripe/stripe-js').Stripe | null;\n if (!stripe) {\n throw new FloPayError('Payment provider is not available.', 'api_error');\n }\n\n if (redirectResult.type === '3ds_required') {\n if (!attempt3DS || !redirectResult.threeDSecureToken) {\n throw Object.assign(\n new FloPayError(\n 'Your card requires authentication. Please enter your payment details below.',\n 'api_error',\n { code: 'authentication_required' },\n ),\n { checkoutMethod: 'card' as CheckoutButtonMethod },\n ) satisfies SavedPaymentFlowError;\n }\n\n let paymentIntent: import('@stripe/stripe-js').PaymentIntent | null = null;\n let savedPaymentMethodId = redirectResult.paymentMethodId;\n\n if (typeof stripe.retrievePaymentIntent === 'function') {\n const { paymentIntent: existingPaymentIntent, error: retrieveError } = await stripe.retrievePaymentIntent(\n redirectResult.threeDSecureToken,\n );\n\n if (retrieveError) {\n throw Object.assign(\n new FloPayError(\n retrieveError.message ?? 'Failed to retrieve 3DS payment status.',\n 'api_error',\n { code: retrieveError.code },\n ),\n { checkoutMethod: 'card' as CheckoutButtonMethod },\n ) satisfies SavedPaymentFlowError;\n }\n\n if (!savedPaymentMethodId && existingPaymentIntent?.payment_method) {\n if (typeof existingPaymentIntent.payment_method === 'string') {\n savedPaymentMethodId = existingPaymentIntent.payment_method;\n } else if ('id' in existingPaymentIntent.payment_method) {\n savedPaymentMethodId = existingPaymentIntent.payment_method.id;\n }\n }\n }\n\n if (savedPaymentMethodId && typeof stripe.confirmCardPayment === 'function') {\n const { error: confirmError, paymentIntent: confirmedPaymentIntent } = await stripe.confirmCardPayment(\n redirectResult.threeDSecureToken,\n {\n payment_method: savedPaymentMethodId,\n return_url: returnUrl ?? resolveSavedPaymentReturnUrl(session) ?? window.location.href,\n },\n );\n\n if (confirmError) {\n throw Object.assign(\n new FloPayError(\n confirmError.message ?? '3DS authentication failed.',\n 'api_error',\n { code: confirmError.code },\n ),\n { checkoutMethod: 'card' as CheckoutButtonMethod },\n ) satisfies SavedPaymentFlowError;\n }\n\n paymentIntent = confirmedPaymentIntent ?? null;\n } else {\n const { error: nextActionError, paymentIntent: nextActionPaymentIntent } = await stripe.handleNextAction({\n clientSecret: redirectResult.threeDSecureToken,\n });\n\n if (nextActionError) {\n throw Object.assign(\n new FloPayError(\n nextActionError.message ?? '3DS authentication failed.',\n 'api_error',\n { code: nextActionError.code },\n ),\n { checkoutMethod: 'card' as CheckoutButtonMethod },\n ) satisfies SavedPaymentFlowError;\n }\n\n paymentIntent = nextActionPaymentIntent ?? null;\n }\n\n if (paymentIntent && (\n paymentIntent.status === 'requires_capture' ||\n paymentIntent.status === 'succeeded' ||\n paymentIntent.status === 'processing'\n )) {\n const followUp = await processSavedPaymentForMode({\n billingApiUrl,\n sessionId,\n session,\n tokenizedData: {\n id: paymentIntent.id,\n type: 'card',\n threeDSecureActionResultTokenId: paymentIntent.id,\n },\n returnUrl,\n });\n\n if (followUp.type === 'success') {\n return {\n ...followUp.result,\n paymentIntentId: followUp.result.paymentIntentId ?? paymentIntent.id,\n paymentMethodId: followUp.result.paymentMethodId ?? savedPaymentMethodId,\n };\n }\n\n return handleSavedPaymentRedirectResult(followUp, {\n flopay,\n paypalFlopay,\n attempt3DS,\n billingApiUrl,\n sessionId,\n session,\n returnUrl,\n });\n }\n\n throw Object.assign(\n new FloPayError('3DS authentication did not complete successfully.', 'api_error'),\n { checkoutMethod: 'card' as CheckoutButtonMethod },\n ) satisfies SavedPaymentFlowError;\n }\n\n if (redirectResult.type === 'paypal_redirect_required') {\n const paypalStripe = (paypalFlopay ?? flopay)?.getRawProvider() as import('@stripe/stripe-js').Stripe | null;\n if (!paypalStripe) {\n throw Object.assign(\n new FloPayError('PayPal is not available.', 'api_error'),\n { checkoutMethod: 'paypal' as CheckoutButtonMethod },\n ) satisfies SavedPaymentFlowError;\n }\n\n if (redirectResult.paymentMethodId) {\n // Backend attached the saved PM and confirmed the PI server-side, so\n // the PI is in `requires_action` with the PayPal redirect baked into\n // next_action.redirect_to_url. Use `handleNextAction` to drive that\n // redirect — `confirmPayment` would error with\n // `payment_intent_unexpected_state` on a PI that's already past the\n // confirmation step.\n const { error } = await paypalStripe.handleNextAction({\n clientSecret: redirectResult.threeDSecureToken,\n });\n\n if (error) {\n throw Object.assign(\n new FloPayError(\n error.message ?? 'PayPal authorization failed.',\n 'api_error',\n { code: error.code },\n ),\n { checkoutMethod: 'paypal' as CheckoutButtonMethod },\n ) satisfies SavedPaymentFlowError;\n }\n\n return {\n status: 'succeeded',\n checkoutMethod: 'paypal',\n };\n }\n\n // No `paymentMethodId` on the redirect result: backend created the PI\n // without attaching a PM, so it's sitting in `requires_payment_method`.\n // Drive the redirect by passing `payment_method_data: { type: 'paypal' }`\n // — Stripe creates a fresh PayPal PM during the redirect and attaches it\n // to the PI. No Elements instance needed; no saved-PM reference needed\n // either, so this works for true cross-account scenarios as well.\n const { error } = await paypalStripe.confirmPayment({\n clientSecret: redirectResult.threeDSecureToken,\n confirmParams: {\n return_url: returnUrl ?? resolveSavedPaymentReturnUrl(session) ?? window.location.href,\n payment_method_data: { type: 'paypal' },\n } as { return_url: string },\n redirect: 'if_required',\n });\n\n if (error) {\n throw Object.assign(\n new FloPayError(\n error.message ?? 'PayPal authorization failed.',\n 'api_error',\n { code: error.code },\n ),\n { checkoutMethod: 'paypal' as CheckoutButtonMethod },\n ) satisfies SavedPaymentFlowError;\n }\n\n return {\n status: 'succeeded',\n checkoutMethod: 'paypal',\n };\n }\n\n throw new FloPayError('Unsupported payment redirect state.', 'api_error');\n}\n\nexport function normalizeSavedPaymentError(err: unknown): SavedPaymentFlowError {\n if (err instanceof FloPayError) {\n return err as SavedPaymentFlowError;\n }\n\n return new FloPayError(\n err instanceof Error ? err.message : 'Payment failed. Please try again.',\n 'api_error',\n ) as SavedPaymentFlowError;\n}\n\nexport function resolveSavedPaymentPublishableKeys(\n unified: NormalizedCheckoutSession,\n): {\n publishableKey: string;\n paypalPublishableKey?: string;\n} {\n let publishableKey: string | undefined;\n let paypalPublishableKey: string | undefined;\n\n if (unified.provider === 'stripe') {\n publishableKey = unified.data.stripe?.publishableKey;\n paypalPublishableKey = unified.data.stripe?.paypalPublishableKey ?? undefined;\n }\n\n if (!publishableKey) {\n throw new FloPayError(\n 'No publishable key found in the checkout session. Ensure the session includes gatewayData.publishableKey.',\n 'validation_error',\n );\n }\n\n return {\n publishableKey,\n paypalPublishableKey,\n };\n}\n\nexport async function loadSavedPaymentProviders({\n publishableKey,\n paypalPublishableKey,\n billingApiUrl,\n locale,\n}: {\n publishableKey: string;\n paypalPublishableKey?: string;\n billingApiUrl: string;\n locale?: string;\n}): Promise<{\n flopay: FloPay;\n paypalFlopay: FloPay | null;\n}> {\n const needsSeparatePaypal =\n Boolean(paypalPublishableKey) && paypalPublishableKey !== publishableKey;\n\n const [instance, paypalInstanceOrError] = await Promise.all([\n loadFloPay(publishableKey, {\n billingApiUrl,\n locale,\n }),\n needsSeparatePaypal\n ? loadFloPay(paypalPublishableKey!, {\n billingApiUrl,\n locale,\n }).catch((err: unknown) => {\n console.warn('[FloPay] Failed to load PayPal Stripe instance:', err);\n return null;\n })\n : Promise.resolve(null),\n ]);\n\n return {\n flopay: instance,\n paypalFlopay: paypalPublishableKey\n ? needsSeparatePaypal\n ? (paypalInstanceOrError as FloPay | null)\n : instance\n : null,\n };\n}\n","import type {\n DeclineEvent,\n PaymentResult,\n TokenizedBody,\n} from '@flopay/shared';\nimport { FloPayError } from '@flopay/shared';\nimport React, { forwardRef, useCallback, useEffect, useImperativeHandle, useState } from 'react';\nimport { useFloPay, usePayPalFloPay, useElements, useBillingApiUrl } from './hooks.js';\nimport { PaymentElement } from './elements.js';\nimport { AddressElement } from './elements.js';\nimport {\n buildDeclineEvent,\n buildFloPayApiErrorFromResponse,\n resolvePaymentIntentPaymentMethodId,\n resolveTokenizedPaymentMethodId,\n retrievePaymentIntentFromProvider,\n} from './checkout-utils.js';\n\n/** localStorage key for persisting wallet payment state across redirects. */\nconst WALLET_RESUME_KEY = 'flopay_wallet_resume';\n\n/** Methods exposed via ref for external 3DS handling. */\nexport interface CheckoutFormRef {\n handleNextAction: (clientSecret: string) => Promise<void>;\n}\n\n/** Props for the drop-in `CheckoutForm` component. */\nexport interface CheckoutFormProps {\n /** The checkout session ID (UUID from billing API). */\n sessionId: string;\n /** Billing API base URL. Optional — defaults to the value from FloPayProvider or the shared constant. */\n billingApiUrl?: string;\n /** User's email (required for creating payment intents). */\n email?: string;\n /** User ID (required for processing payments). */\n userId?: string;\n /**\n * Called when the full payment flow completes successfully.\n * By default the form handles everything: tokenize → create intent →\n * confirm → processPayment → 3DS retry. You just handle the success.\n */\n onComplete?: (result: PaymentResult) => void;\n /** Called when a payment error occurs. */\n onError?: (error: FloPayError) => void;\n /** Called when a payment is declined or the authentication step fails. */\n onDecline?: (decline: DeclineEvent) => void;\n /**\n * **Override**: If provided, the form tokenizes the card and confirms\n * the payment, but delegates backend submission to the caller.\n * When omitted, the form calls `processPayment` internally.\n */\n onTokenizedBody?: (tokenizedBody: TokenizedBody) => void;\n /** Layout style for the PaymentElement. */\n layout?: 'tabs' | 'accordion' | 'auto';\n /** Label for the submit button. */\n submitLabel?: string;\n /** Whether to show an address element. */\n showAddress?: boolean | 'billing' | 'shipping';\n /** Additional CSS class for the form wrapper. */\n className?: string;\n /** Custom children (e.g. a custom submit button). Overrides the default button. */\n children?: React.ReactNode;\n /** First name for billing. */\n firstName?: string;\n /** Last name for billing. */\n lastName?: string;\n /** Checkout version for A/B tracking. */\n chv?: string;\n /** External processing state (used when onTokenizedBody is provided). */\n isProcessing?: boolean;\n /** External error message (used when onTokenizedBody is provided). */\n error?: string | null;\n /** Called when internal error state changes. */\n onErrorChange?: (error: string | null) => void;\n}\n\n/**\n * Drop-in checkout form that handles the full payment lifecycle by default.\n *\n * **Default (self-contained) mode** — just provide config + onComplete:\n * ```tsx\n * <CheckoutForm\n * sessionId=\"uuid\"\n * billingApiUrl=\"https://api.example.com\"\n * email=\"user@example.com\"\n * userId=\"user_1\"\n * onComplete={(result) => router.push('/success')}\n * />\n * ```\n *\n * The form handles internally:\n * 1. Validate → tokenize card → create PaymentIntent → confirm (3DS)\n * 2. Submit token to `POST /v1/checkouts/sessions/process`\n * 3. If backend returns `3ds_required` → re-confirm with new client secret\n * 4. Wallet resume after redirect (PayPal, etc.)\n *\n * **Override mode** — provide `onTokenizedBody` to handle backend submission yourself:\n * ```tsx\n * <CheckoutForm\n * ...\n * onTokenizedBody={(body) => myCustomProcessPayment(body)}\n * />\n * ```\n */\nexport const CheckoutForm = forwardRef<CheckoutFormRef, CheckoutFormProps>(\n function CheckoutForm(props, ref) {\n return <CheckoutFormInner {...props} innerRef={ref} />;\n },\n);\n\n// ─── Internal implementation ────────────────────────────────────────────────\n\nfunction CheckoutFormInner({\n sessionId,\n billingApiUrl,\n email,\n userId,\n onComplete,\n onError,\n onDecline,\n onTokenizedBody,\n layout = 'auto',\n submitLabel = 'Pay',\n showAddress = false,\n className,\n children,\n firstName,\n lastName,\n chv,\n isProcessing: externalProcessing,\n error: externalError,\n onErrorChange,\n innerRef,\n}: CheckoutFormProps & { innerRef: React.Ref<CheckoutFormRef> }) {\n const flopay = useFloPay();\n const paypalFlopay = usePayPalFloPay();\n const elements = useElements();\n const contextBillingUrl = useBillingApiUrl();\n const [processing, setProcessing] = useState(false);\n const [error, setError] = useState<string | null>(null);\n const [is3DSActive, setIs3DSActive] = useState(false);\n\n const displayError = externalError ?? error;\n const isSubmitting = externalProcessing ?? processing;\n const isSelfContained = !onTokenizedBody;\n const baseUrl = (billingApiUrl || contextBillingUrl).replace(/\\/+$/, '');\n\n const updateError = useCallback(\n (err: string | null) => {\n setError(err);\n onErrorChange?.(err);\n },\n [onErrorChange],\n );\n\n const emitDecline = useCallback(\n (\n input: string | FloPayError,\n overrides?: { code?: string; declineCode?: string },\n ) => {\n onDecline?.(buildDeclineEvent('card', input, overrides));\n },\n [onDecline],\n );\n\n // ── Internal: call processPayment and handle 3DS/PayPal responses ──\n\n const processPaymentInternal = useCallback(\n async (\n tokenizedBody: TokenizedBody,\n completionPaymentMethodId?: string,\n ) => {\n setProcessing(true);\n updateError(null);\n\n const resolvedCompletionPaymentMethodId =\n completionPaymentMethodId ?? resolveTokenizedPaymentMethodId(tokenizedBody);\n const requestTokenizedBody = tokenizedBody.originalPaymentMethodId\n ? { ...tokenizedBody, originalPaymentMethodId: undefined }\n : tokenizedBody;\n\n try {\n const response = await fetch(`${baseUrl}/v1/checkouts/sessions/process`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'x-user-id': userId ?? '',\n },\n body: JSON.stringify({\n sessionId,\n tokenizedData: requestTokenizedBody,\n accountData: {\n userId: userId ?? '',\n email: email ?? '',\n firstName: firstName ?? '',\n lastName: lastName ?? '',\n },\n chv,\n }),\n });\n\n if (response.ok) {\n onComplete?.({\n status: 'succeeded',\n paymentIntentId: tokenizedBody.threeDSecureActionResultTokenId,\n paymentMethodId: resolvedCompletionPaymentMethodId,\n checkoutMethod: tokenizedBody.isPaypal ? 'paypal' : 'card',\n });\n return;\n }\n\n const json = await response.json().catch(() => null) as Record<string, unknown> | null;\n\n // 3DS required — confirm with new client secret, then resubmit\n if (json?.type === '3ds_required') {\n const secret = json['threeDSecureToken'] as string;\n if (!flopay || !secret) {\n updateError('3DS authentication required but no token provided.');\n return;\n }\n\n setIs3DSActive(true);\n try {\n const retryFullName = `${firstName ?? ''} ${lastName ?? ''}`.trim();\n const result = await flopay.confirmPayment({\n clientSecret: secret,\n returnUrl: window.location.href,\n billingDetails: {\n ...(email ? { email } : {}),\n ...(retryFullName ? { name: retryFullName } : {}),\n },\n });\n\n if (result.error) {\n updateError(result.error.message);\n onError?.(result.error);\n emitDecline(result.error);\n return;\n }\n\n if (result.status === 'succeeded' || result.status === 'processing') {\n // Resubmit with the 3DS result. Keep the original reusable PM for\n // completion callbacks, but do not resend it in the process body:\n // the billing API may derive idempotency keys from that PM.\n await processPaymentInternal({\n id: result.paymentIntentId,\n type: 'card',\n threeDSecureActionResultTokenId: result.paymentIntentId,\n }, resolvedCompletionPaymentMethodId);\n }\n } finally {\n setIs3DSActive(false);\n }\n return;\n }\n\n // PayPal redirect required — the PaymentIntent lives on the PayPal\n // Stripe account (gatewayData.paypalPublishableKey), so confirmation\n // must be routed through the PayPal FloPay instance. Falls back to\n // the primary instance when the PayPal account matches the primary.\n if (json?.type === 'paypal_redirect_required') {\n const secret = (json['threeDSecureToken'] ?? json['clientSecret']) as string | undefined;\n const pmId = json['paymentMethodId'] as string | undefined;\n const paypalStripe = (paypalFlopay ?? flopay)?.getRawProvider() as\n | import('@stripe/stripe-js').Stripe\n | null;\n\n if (!paypalStripe || !secret) {\n const message = 'PayPal is not available.';\n updateError(message);\n onDecline?.(buildDeclineEvent('paypal', message));\n return;\n }\n\n // Store state for resume after redirect.\n localStorage.setItem(WALLET_RESUME_KEY, JSON.stringify({\n sessionId,\n paymentIntentId: '',\n tokenType: 'card',\n tokenId: pmId ?? '',\n status: 'pending_redirect',\n }));\n\n const confirmParams: Record<string, unknown> = {\n return_url: window.location.href,\n };\n if (pmId) confirmParams['payment_method'] = pmId;\n\n const { error: confirmError } = await paypalStripe.confirmPayment({\n clientSecret: secret,\n confirmParams: confirmParams as { return_url: string },\n redirect: 'if_required',\n });\n\n if (confirmError) {\n const message = confirmError.message ?? 'PayPal payment failed.';\n updateError(message);\n onDecline?.(buildDeclineEvent('paypal', message, { code: confirmError.code }));\n }\n return;\n }\n\n // Generic error\n const errorMessage = (json?.message as string) ?? 'Payment failed. Please try again.';\n updateError(errorMessage);\n emitDecline(errorMessage, {\n code: json?.code as string | undefined,\n declineCode: (json?.declineCode ?? json?.gatewayDeclineReason) as string | undefined,\n });\n } catch (err) {\n updateError(err instanceof Error ? err.message : 'An unexpected error occurred');\n } finally {\n setProcessing(false);\n }\n },\n [baseUrl, sessionId, userId, email, firstName, lastName, chv, flopay, paypalFlopay, onComplete, onError, onDecline, updateError, emitDecline],\n );\n\n // ── Dispatch tokenized body: self-contained or delegated ──\n\n const dispatchTokenizedBody = useCallback(\n (tokenizedBody: TokenizedBody) => {\n if (onTokenizedBody) {\n // Delegated mode — caller handles backend submission\n onTokenizedBody(tokenizedBody);\n } else {\n // Self-contained mode — process internally\n processPaymentInternal(tokenizedBody);\n }\n },\n [onTokenizedBody, processPaymentInternal],\n );\n\n // ── Expose imperative 3DS handler (for delegated mode) ──\n\n useImperativeHandle(innerRef, () => ({\n async handleNextAction(secret: string) {\n if (!flopay) return;\n\n setIs3DSActive(true);\n try {\n const result = await flopay.confirmPayment({\n clientSecret: secret,\n returnUrl: window.location.href,\n });\n\n if (result.error) {\n updateError(result.error.message);\n onError?.(result.error);\n emitDecline(result.error);\n } else if (result.status === 'succeeded' || result.status === 'processing') {\n dispatchTokenizedBody({\n id: result.paymentIntentId,\n type: 'card',\n threeDSecureActionResultTokenId: result.paymentIntentId,\n });\n }\n } catch (err) {\n updateError(err instanceof Error ? err.message : 'Payment authentication failed.');\n } finally {\n setIs3DSActive(false);\n }\n },\n }), [flopay, dispatchTokenizedBody, onError, updateError, emitDecline]);\n\n // ── Resume wallet payments after redirect ──\n\n useEffect(() => {\n if (typeof window === 'undefined') return;\n\n const stored = localStorage.getItem(WALLET_RESUME_KEY);\n if (!stored) return;\n\n try {\n const payload = JSON.parse(stored) as {\n sessionId: string;\n paymentIntentId: string;\n tokenType: string;\n tokenId: string;\n status: string;\n };\n\n if (payload.sessionId === sessionId) {\n localStorage.removeItem(WALLET_RESUME_KEY);\n dispatchTokenizedBody({\n id: payload.tokenId,\n type: payload.tokenType,\n threeDSecureActionResultTokenId: payload.paymentIntentId,\n });\n }\n } catch {\n localStorage.removeItem(WALLET_RESUME_KEY);\n }\n }, [sessionId, dispatchTokenizedBody]);\n\n // ── Submit: tokenize → create intent → confirm → dispatch ──\n\n const handleSubmit = useCallback(\n async (e: React.FormEvent) => {\n e.preventDefault();\n if (!flopay || !elements || isSubmitting) return;\n\n setProcessing(true);\n updateError(null);\n let handedOff = false;\n\n try {\n // Matches checkout/StripeCardForm exactly:\n // 1. createPaymentMethod → 2. createPaymentIntent → 3. confirmCardPayment → 4. onTokenizedBody\n\n // 1. Validate\n const submitResult = await flopay.submitElements();\n if (submitResult.error) {\n updateError(submitResult.error.message);\n onError?.(submitResult.error);\n return;\n }\n\n // 2. Tokenize card → PaymentMethod\n const fullName = `${firstName ?? ''} ${lastName ?? ''}`.trim();\n const pmResult = await flopay.createPaymentMethod({\n ...(email ? { email } : {}),\n ...(fullName ? { name: fullName } : {}),\n });\n if (pmResult.error || !pmResult.paymentMethodId) {\n updateError(pmResult.error?.message ?? 'Failed to create payment method.');\n return;\n }\n\n if (!sessionId || !email) {\n throw new FloPayError('Missing sessionId or email', 'validation_error');\n }\n\n // 3. Create PaymentIntent via billing API (backend uses capture_method: 'manual')\n const intentResponse = await fetch(`${baseUrl}/v1/checkouts/payments/intents`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n sessionId,\n email,\n paymentMethodType: pmResult.paymentMethodId,\n isPaypal: false,\n }),\n });\n\n if (!intentResponse.ok) {\n const intentError = await buildFloPayApiErrorFromResponse(\n intentResponse,\n 'Failed to create payment intent',\n );\n updateError(intentError.message);\n onError?.(intentError);\n emitDecline(intentError);\n return;\n }\n\n const intentJson = await intentResponse.json() as { data?: { id?: string } };\n const intentClientSecret = intentJson.data?.id;\n if (!intentClientSecret) throw new FloPayError('No client_secret in payment intent response', 'api_error');\n\n // 4. Confirm card payment (handles 3DS automatically via Stripe)\n const confirmResult = await flopay.confirmCardPayment({\n clientSecret: intentClientSecret,\n paymentMethodId: pmResult.paymentMethodId,\n });\n\n if (confirmResult.error) {\n updateError(confirmResult.error.message);\n onError?.(confirmResult.error);\n emitDecline(confirmResult.error);\n return;\n }\n\n const rawProvider = typeof flopay.getRawProvider === 'function' ? flopay.getRawProvider() : null;\n const confirmedPaymentIntent = await retrievePaymentIntentFromProvider(\n rawProvider,\n intentClientSecret,\n );\n const paymentIntentId = confirmResult.paymentIntentId ?? confirmedPaymentIntent?.id;\n const paymentMethodId =\n confirmResult.paymentMethodId\n ?? resolvePaymentIntentPaymentMethodId(confirmedPaymentIntent)\n ?? pmResult.paymentMethodId;\n\n if (!paymentIntentId) {\n const error = new FloPayError('No payment intent returned after confirmation.', 'api_error');\n updateError(error.message);\n onError?.(error);\n return;\n }\n\n // 5. Send PM + PI to processPaymentInternal (or parent via onTokenizedBody)\n handedOff = isSelfContained;\n dispatchTokenizedBody({\n id: paymentMethodId,\n type: 'card',\n threeDSecureActionResultTokenId: paymentIntentId,\n originalPaymentMethodId: pmResult.paymentMethodId,\n });\n } catch (err) {\n updateError(err instanceof Error ? err.message : 'An unexpected error occurred');\n } finally {\n if (!handedOff) {\n setProcessing(false);\n }\n }\n },\n [flopay, elements, isSubmitting, sessionId, email, baseUrl, isSelfContained, dispatchTokenizedBody, onError, updateError, emitDecline],\n );\n\n const isReady = flopay !== null && elements !== null;\n\n return (\n <form onSubmit={handleSubmit} className={className} style={{ position: 'relative' }}>\n {(is3DSActive || isSubmitting) && (\n <div data-testid=\"flopay-overlay\" style={{\n position: 'absolute', inset: 0,\n background: 'rgba(255,255,255,0.7)',\n display: 'flex', alignItems: 'center', justifyContent: 'center',\n zIndex: 10,\n }}>\n {is3DSActive ? 'Verifying payment...' : 'Processing...'}\n </div>\n )}\n\n {!isReady && (\n <div data-testid=\"flopay-loading\" aria-busy=\"true\">\n Loading payment form...\n </div>\n )}\n\n {isReady && (\n <>\n <PaymentElement options={{ layout }} />\n\n {showAddress && (\n <AddressElement options={{ mode: showAddress === true ? 'billing' : showAddress }} />\n )}\n\n {displayError && (\n <div role=\"alert\" data-testid=\"flopay-error\" style={{ color: 'red', margin: '0.75rem 0' }}>\n {displayError}\n </div>\n )}\n\n {children ?? (\n <button\n type=\"submit\"\n disabled={isSubmitting || !isReady}\n data-testid=\"flopay-submit\"\n >\n {isSubmitting ? 'Processing...' : submitLabel}\n </button>\n )}\n </>\n )}\n </form>\n );\n}\n","import type { TokenizedBody } from '@flopay/shared';\nimport { FloPayError } from '@flopay/shared';\nimport React, { useCallback, useEffect, useRef, useState } from 'react';\nimport { useFloPay, useElements, useBillingApiUrl } from './hooks.js';\n\n/**\n * Props for the `PayPalButton` component.\n *\n * Must be rendered inside its own `FloPayProvider` with `paymentMethodCreation: undefined`\n * (not 'manual') — PayPal cannot share the same Elements instance as card fields.\n */\nexport interface PayPalButtonProps {\n /** The checkout session ID (UUID from billing API). */\n sessionId: string;\n /** Billing API base URL. Optional — defaults to the value from FloPayProvider or the shared constant. */\n billingApiUrl?: string;\n /** User's email. */\n email?: string;\n /** User ID for processing payments. */\n userId?: string;\n /** First name for billing. */\n firstName?: string;\n /** Last name for billing. */\n lastName?: string;\n /** Checkout version for tracking. */\n chv?: string;\n /**\n * Called with tokenized data after PayPal authorization.\n * If omitted, the component calls processPayment internally.\n */\n onTokenizedBody?: (body: TokenizedBody) => void;\n /** Called on successful payment (self-contained mode). */\n onComplete?: () => void;\n /** Called when an error occurs. */\n onErrorChange?: (error: string | null) => void;\n /** External processing state. */\n isProcessing?: boolean;\n}\n\n/**\n * PayPal button that handles the full PayPal payment flow.\n *\n * **Important**: PayPal requires its own `FloPayProvider` — it cannot share\n * the same Stripe Elements instance as card fields when they use\n * `paymentMethodCreation: 'manual'`. This matches `checkout/StripeCardForm`\n * which renders PayPal in a separate `<Elements>` wrapper.\n *\n * ```tsx\n * {/* Card fields provider (paymentMethodCreation: 'manual') *\\/}\n * <FloPayProvider flopay={flopay} options={{ amount, currency }}>\n * <SplitCardForm ... />\n * </FloPayProvider>\n *\n * {/* PayPal provider (no paymentMethodCreation) *\\/}\n * <FloPayProvider flopay={flopay} options={{ amount, currency, paymentMethodCreation: 'auto' }}>\n * <PayPalButton ... />\n * </FloPayProvider>\n * ```\n */\nexport function PayPalButton({\n sessionId,\n billingApiUrl,\n email,\n userId,\n firstName,\n lastName,\n chv,\n onTokenizedBody,\n onComplete,\n onErrorChange,\n isProcessing = false,\n}: PayPalButtonProps): React.ReactElement {\n const flopay = useFloPay();\n const elements = useElements();\n const contextBillingUrl = useBillingApiUrl();\n const [ready, setReady] = useState(false);\n const [submitting, setSubmitting] = useState(false);\n const paypalResumeAttempted = useRef(false);\n const baseUrl = (billingApiUrl || contextBillingUrl).replace(/\\/+$/, '');\n\n // ── Internal processPayment (self-contained mode) ──\n\n const processPaymentInternal = useCallback(\n async (tokenizedBody: TokenizedBody) => {\n try {\n const response = await fetch(`${baseUrl}/v1/checkouts/sessions/process`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'x-user-id': userId ?? '',\n },\n body: JSON.stringify({\n sessionId,\n tokenizedData: tokenizedBody,\n accountData: {\n userId: userId ?? '',\n email: email ?? '',\n firstName: firstName ?? '',\n lastName: lastName ?? '',\n },\n chv,\n }),\n });\n\n if (response.ok) {\n onComplete?.();\n return;\n }\n\n const json = await response.json().catch(() => null) as Record<string, unknown> | null;\n onErrorChange?.((json?.message as string) ?? 'Payment failed. Please try again.');\n } catch (err) {\n onErrorChange?.(err instanceof Error ? err.message : 'An unexpected error occurred');\n }\n },\n [baseUrl, sessionId, userId, email, firstName, lastName, chv, onComplete, onErrorChange],\n );\n\n const dispatchTokenizedBody = useCallback(\n (body: TokenizedBody) => {\n if (onTokenizedBody) {\n onTokenizedBody(body);\n } else {\n processPaymentInternal(body);\n }\n },\n [onTokenizedBody, processPaymentInternal],\n );\n\n // ── Resume PayPal redirect return ──\n\n useEffect(() => {\n if (!flopay || paypalResumeAttempted.current) return;\n\n const params = new URLSearchParams(window.location.search);\n const paymentIntentId = params.get('payment_intent');\n const clientSecret = params.get('payment_intent_client_secret');\n const redirectStatus = params.get('redirect_status');\n\n if (!paymentIntentId || !clientSecret) return;\n paypalResumeAttempted.current = true;\n\n (async () => {\n try {\n setSubmitting(true);\n\n if (redirectStatus === 'failed') {\n onErrorChange?.('PayPal payment was declined. Please try again.');\n return;\n }\n\n // Retrieve the PaymentIntent to check status (matches checkout/StripeCardForm resume)\n const provider = flopay.getRawProvider() as { retrievePaymentIntent?: (cs: string) => Promise<{ paymentIntent?: { id: string; status: string; payment_method: string | { id: string } }; error?: { message: string } }> } | null;\n if (!provider?.retrievePaymentIntent) {\n onErrorChange?.('Cannot retrieve PayPal payment status.');\n return;\n }\n\n const { paymentIntent, error: retrieveError } = await provider.retrievePaymentIntent(clientSecret);\n if (retrieveError) {\n onErrorChange?.(retrieveError.message ?? 'Failed to retrieve PayPal payment status.');\n return;\n }\n\n if (paymentIntent && (paymentIntent.status === 'requires_capture' || paymentIntent.status === 'succeeded')) {\n const pmId = typeof paymentIntent.payment_method === 'string'\n ? paymentIntent.payment_method\n : paymentIntent.payment_method?.id;\n\n dispatchTokenizedBody({\n id: pmId ?? paymentIntent.id,\n type: 'card',\n threeDSecureActionResultTokenId: paymentIntent.id,\n isPaypal: true,\n });\n\n // Clean up URL params\n const url = new URL(window.location.href);\n url.searchParams.delete('payment_intent');\n url.searchParams.delete('payment_intent_client_secret');\n url.searchParams.delete('redirect_status');\n window.history.replaceState({}, '', url.toString());\n } else {\n onErrorChange?.('PayPal payment was not completed. Please try again.');\n }\n } catch (err) {\n onErrorChange?.(err instanceof Error ? err.message : 'Failed to complete PayPal payment.');\n } finally {\n setSubmitting(false);\n }\n })();\n }, [flopay, dispatchTokenizedBody, onErrorChange]);\n\n // ── PayPal confirm handler ──\n\n const handlePayPalConfirm = useCallback(async () => {\n if (!flopay || !elements) return;\n\n try {\n setSubmitting(true);\n onErrorChange?.(null);\n\n if (!sessionId || !email) {\n throw new FloPayError('Missing sessionId or email for PayPal payment', 'validation_error');\n }\n\n const result = await flopay.confirmPayPalPayment({\n billingApiUrl: baseUrl,\n sessionId,\n email,\n returnUrl: window.location.href,\n });\n\n if (result.error) {\n onErrorChange?.(result.error.message);\n return;\n }\n\n // Defensive future inline-completion path: `confirmPayPalPayment` currently\n // redirects and returns no `paymentIntentId`, so the redirect-resume effect\n // is what normally reaches `dispatchTokenizedBody`. If\n // `confirmPayPalPayment` ever starts completing inline, it must also return\n // `paymentIntentId` so this branch can finish the checkout immediately.\n if (\n result.paymentIntentId\n && (result.status === 'succeeded' || result.status === 'processing' || result.status === 'requires_capture')\n ) {\n dispatchTokenizedBody({\n id: result.paymentMethodId ?? result.paymentIntentId,\n type: 'card',\n threeDSecureActionResultTokenId: result.paymentIntentId,\n isPaypal: true,\n });\n }\n } catch (err) {\n onErrorChange?.(err instanceof Error ? err.message : 'PayPal payment failed. Please try again.');\n } finally {\n setSubmitting(false);\n }\n }, [flopay, elements, sessionId, email, baseUrl, dispatchTokenizedBody, onErrorChange]);\n\n if (!flopay || !elements) {\n return <div style={{ height: 45, background: '#f0f0f0', borderRadius: 6, animation: 'pulse 1.5s infinite' }} />;\n }\n\n return (\n <>\n {!ready && (\n <div style={{ height: 45, background: '#f0f0f0', borderRadius: 6 }} />\n )}\n <div style={ready ? {} : { display: 'none' }}>\n <button\n type=\"button\"\n onClick={handlePayPalConfirm}\n disabled={submitting || isProcessing}\n style={{\n width: '100%',\n height: 45,\n backgroundColor: '#ffc439',\n color: '#003087',\n border: 'none',\n borderRadius: 6,\n fontSize: '1rem',\n fontWeight: 700,\n cursor: submitting || isProcessing ? 'not-allowed' : 'pointer',\n opacity: submitting || isProcessing ? 0.6 : 1,\n }}\n ref={() => setReady(true)}\n >\n {submitting ? 'Processing...' : 'PayPal'}\n </button>\n </div>\n\n {(submitting || isProcessing) && (\n <div style={{\n position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.4)',\n display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 1000,\n }}>\n <div style={{\n background: 'white', borderRadius: 8, padding: '1.5rem',\n textAlign: 'center', boxShadow: '0 4px 24px rgba(0,0,0,0.15)', width: 280,\n }}>\n Processing PayPal payment...\n </div>\n </div>\n )}\n </>\n );\n}\n","import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport { PaymentAPI } from '@flopay/js';\nimport type {\n CheckoutButtonMethod,\n CheckoutSession,\n DeclineEvent,\n InlineSessionDraft,\n PaymentResult,\n} from '@flopay/shared';\nimport type { ButtonsLayoutStyles, ButtonsLayoutTheme, CheckoutItem, CheckoutSubscription } from '@flopay/shared';\nimport { FloPayError, resolveBillingApiUrl, resolveButtonsLayoutTheme } from '@flopay/shared';\nimport { CardButtonContentSlot } from './card-button-content.js';\nimport { buildDeclineEvent, mapPayPalIntentStatusToPaymentResult } from './checkout-utils.js';\nimport { FloPayCheckout } from './flopay-checkout.js';\nimport {\n PROCESSING_OVERLAY_ERROR_DELAY_MS,\n PROCESSING_OVERLAY_SUCCESS_DELAY_MS,\n ProcessingOverlay,\n type OverlayStatus,\n} from './processing-overlay.js';\nimport {\n checkoutProcessErrorToFloPayError,\n DEFAULT_SAVED_PAYMENT_DECLINE_METHOD,\n getRedirectResultFromCheckoutProcessError,\n handleSavedPaymentRedirectResult,\n loadSavedPaymentProviders,\n normalizeSavedPaymentError,\n processSavedPaymentForMode,\n processSavedPaymentWithIntent,\n resolveSavedPaymentPublishableKeys,\n} from './saved-payment-flow.js';\n\nconst DEFAULT_BUTTONS_LAYOUT_BUTTON_HEIGHT = 44;\nconst PAYPAL_RESUME_STORAGE_KEY = 'flopay_automatic_payment_button_resume';\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nfunction coerceError(err: unknown, fallbackMessage: string): FloPayError {\n if (err instanceof FloPayError) {\n return err;\n }\n\n return new FloPayError(\n err instanceof Error ? err.message : fallbackMessage,\n 'api_error',\n );\n}\n\nfunction canUseStorage() {\n return typeof window !== 'undefined' && typeof window.sessionStorage !== 'undefined';\n}\n\ninterface PayPalResumeState {\n sessionId: string | null;\n publishableKey: string;\n paypalPublishableKey?: string;\n}\n\nfunction shouldShowFallbackCheckout(\n error: FloPayError & { checkoutMethod?: CheckoutButtonMethod },\n sessionId: string | null,\n): boolean {\n if (!sessionId) return false;\n if (error.type === 'validation_error') return false;\n if (error.checkoutMethod && error.checkoutMethod !== 'card' && error.checkoutMethod !== 'paypal') {\n return false;\n }\n return true;\n}\n\nfunction readPayPalResumeState(): PayPalResumeState | null {\n if (!canUseStorage()) return null;\n\n try {\n const raw = window.sessionStorage.getItem(PAYPAL_RESUME_STORAGE_KEY);\n if (!raw) return null;\n return JSON.parse(raw) as PayPalResumeState;\n } catch {\n return null;\n }\n}\n\nfunction persistPayPalResumeState(state: PayPalResumeState) {\n if (!canUseStorage()) return;\n try {\n window.sessionStorage.setItem(PAYPAL_RESUME_STORAGE_KEY, JSON.stringify(state));\n } catch (error) {\n console.warn('[FloPayAutomaticPaymentButton] Failed to persist PayPal resume state.', error);\n }\n}\n\nfunction clearPayPalResumeState() {\n if (!canUseStorage()) return;\n try {\n window.sessionStorage.removeItem(PAYPAL_RESUME_STORAGE_KEY);\n } catch (error) {\n console.warn('[FloPayAutomaticPaymentButton] Failed to clear PayPal resume state.', error);\n }\n}\n\nfunction clearPayPalRedirectParams() {\n if (typeof window === 'undefined') return;\n\n const url = new URL(window.location.href);\n const keys = ['payment_intent', 'payment_intent_client_secret', 'redirect_status'];\n let changed = false;\n\n for (const key of keys) {\n if (url.searchParams.has(key)) {\n url.searchParams.delete(key);\n changed = true;\n }\n }\n\n if (changed) {\n window.history.replaceState({}, '', url.toString());\n }\n}\n\nexport interface FloPayAutomaticPaymentSuccessEvent {\n result: PaymentResult;\n session: CheckoutSession | null;\n sessionId: string | null;\n autoCompleted: boolean;\n}\n\nexport interface FloPayAutomaticPaymentButtonProps\n extends Omit<React.ButtonHTMLAttributes<HTMLButtonElement>, 'children' | 'onError'> {\n sessionId?: string;\n createSession?: InlineSessionDraft;\n paymentMethodId?: string;\n checkoutMethod?: CheckoutButtonMethod;\n clientId?: string;\n items?: CheckoutItem[];\n subscriptions?: CheckoutSubscription[];\n account?: InlineSessionDraft['account'];\n successUrl?: string;\n cancelUrl?: string;\n couponCodes?: string[];\n tagsData?: InlineSessionDraft['tagsData'];\n utmMetadata?: InlineSessionDraft['utmMetadata'];\n billingApiUrl?: string;\n locale?: string;\n buttonsTheme?: ButtonsLayoutTheme;\n buttonsStyles?: ButtonsLayoutStyles;\n onSuccess?: (event: FloPayAutomaticPaymentSuccessEvent) => void;\n onError?: (error: FloPayError) => void;\n onDecline?: (decline: DeclineEvent) => void;\n children?: React.ReactNode;\n}\n\nfunction resolveCreateSessionDraft(props: FloPayAutomaticPaymentButtonProps): InlineSessionDraft | null {\n if (props.createSession) {\n return {\n ...props.createSession,\n checkoutMode: 'auto',\n };\n }\n\n if (!props.clientId || !props.account || !props.successUrl || !props.cancelUrl) {\n return null;\n }\n\n return {\n clientId: props.clientId,\n items: props.items,\n subscriptions: props.subscriptions,\n account: props.account,\n successUrl: props.successUrl,\n cancelUrl: props.cancelUrl,\n couponCodes: props.couponCodes,\n tagsData: props.tagsData,\n utmMetadata: props.utmMetadata,\n checkoutMode: 'auto',\n };\n}\n\nexport function FloPayAutomaticPaymentButton({\n sessionId,\n createSession,\n paymentMethodId,\n checkoutMethod,\n clientId,\n items,\n subscriptions,\n account,\n successUrl,\n cancelUrl,\n couponCodes,\n tagsData,\n utmMetadata,\n billingApiUrl,\n locale,\n buttonsTheme,\n buttonsStyles: stylesOverride,\n onSuccess,\n onError,\n onDecline,\n children,\n disabled = false,\n type = 'button',\n style,\n ...buttonProps\n}: FloPayAutomaticPaymentButtonProps) {\n const resolvedBillingUrl = useMemo(\n () => resolveBillingApiUrl(billingApiUrl),\n [billingApiUrl],\n );\n const createSessionDraft = useMemo(\n () => resolveCreateSessionDraft({\n createSession,\n clientId,\n items,\n subscriptions,\n account,\n successUrl,\n cancelUrl,\n couponCodes,\n tagsData,\n utmMetadata,\n }),\n [\n account,\n cancelUrl,\n clientId,\n couponCodes,\n createSession,\n items,\n subscriptions,\n successUrl,\n tagsData,\n utmMetadata,\n ],\n );\n const [isProcessing, setIsProcessing] = useState(false);\n const [overlayStatus, setOverlayStatus] = useState<OverlayStatus | null>(null);\n const [overlayError, setOverlayError] = useState<string | null>(null);\n const [fallbackSession, setFallbackSession] = useState<{\n sessionId: string;\n errorMessage: string;\n } | null>(null);\n const automaticPaymentToken = useMemo(\n () => paymentMethodId\n ? {\n id: paymentMethodId,\n type: 'card' as const,\n ...(checkoutMethod === 'paypal' ? { isPaypal: true } : {}),\n }\n : undefined,\n [checkoutMethod, paymentMethodId],\n );\n\n const isMountedRef = useRef(true);\n const resumeAttemptedRef = useRef(false);\n const fallbackSessionRef = useRef(fallbackSession);\n const onSuccessRef = useRef(onSuccess);\n const onErrorRef = useRef(onError);\n const onDeclineRef = useRef(onDecline);\n\n useEffect(() => {\n fallbackSessionRef.current = fallbackSession;\n }, [fallbackSession]);\n\n useEffect(() => {\n onSuccessRef.current = onSuccess;\n }, [onSuccess]);\n\n useEffect(() => {\n onErrorRef.current = onError;\n }, [onError]);\n\n useEffect(() => {\n onDeclineRef.current = onDecline;\n }, [onDecline]);\n\n useEffect(() => {\n isMountedRef.current = true;\n return () => {\n isMountedRef.current = false;\n };\n }, []);\n\n useEffect(() => {\n if (!fallbackSession || typeof window === 'undefined') {\n return;\n }\n\n const handleKeyDown = (event: KeyboardEvent) => {\n if (event.key === 'Escape') {\n setFallbackSession(null);\n }\n };\n\n window.addEventListener('keydown', handleKeyDown);\n return () => {\n window.removeEventListener('keydown', handleKeyDown);\n };\n }, [fallbackSession]);\n\n const emitDecline = useCallback((error: FloPayError, method = DEFAULT_SAVED_PAYMENT_DECLINE_METHOD) => {\n onDeclineRef.current?.(buildDeclineEvent(method, error, {\n code: error.code,\n declineCode: error.declineCode,\n }));\n }, []);\n\n const showSuccess = useCallback(async (event: FloPayAutomaticPaymentSuccessEvent) => {\n if (!isMountedRef.current) return;\n\n setOverlayError(null);\n setOverlayStatus('success');\n await sleep(PROCESSING_OVERLAY_SUCCESS_DELAY_MS);\n\n if (!isMountedRef.current) return;\n onSuccessRef.current?.(event);\n }, []);\n\n const showError = useCallback(async (\n error: FloPayError,\n options?: {\n emitDecline?: boolean;\n method?: CheckoutButtonMethod;\n },\n ) => {\n if (!isMountedRef.current) return;\n\n onErrorRef.current?.(error);\n if (options?.emitDecline) {\n emitDecline(error, options.method);\n }\n\n setOverlayError(error.message);\n setOverlayStatus('error');\n await sleep(PROCESSING_OVERLAY_ERROR_DELAY_MS);\n }, [emitDecline]);\n\n const processResolvedSession = useCallback(async (\n apiResult: Awaited<ReturnType<PaymentAPI['getUnifiedCheckoutSession']>>,\n resolvedSessionId: string | null,\n options?: {\n fromCreateSession?: boolean;\n },\n ) => {\n const session = apiResult.data.session ?? null;\n if (!session) {\n throw new FloPayError('No session data returned', 'api_error');\n }\n\n if (session.status === 'complete') {\n await showSuccess({\n result: { status: 'succeeded' },\n session,\n sessionId: session.id || resolvedSessionId,\n autoCompleted: false,\n });\n return;\n }\n\n if (session.status === 'expired') {\n throw new FloPayError('Checkout session has expired.', 'api_error', {\n code: 'checkout_session_expired',\n });\n }\n\n try {\n let paymentResult: PaymentResult | null = null;\n const redirectResult = getRedirectResultFromCheckoutProcessError(apiResult.autoProcessingError);\n const shouldTreatCreateSessionFlowAsServerAutoAttempt =\n options?.fromCreateSession\n && (\n apiResult.autoProcessingAttempted === true\n || !!apiResult.autoProcessingError\n || !!redirectResult\n );\n const shouldRetryPayPalClientSide =\n checkoutMethod === 'paypal'\n && automaticPaymentToken?.isPaypal === true\n && options?.fromCreateSession === true;\n\n if (redirectResult) {\n const {\n publishableKey,\n paypalPublishableKey,\n } = resolveSavedPaymentPublishableKeys(apiResult);\n\n if (redirectResult.type === 'paypal_redirect_required') {\n persistPayPalResumeState({\n sessionId: session.id || resolvedSessionId,\n publishableKey,\n paypalPublishableKey,\n });\n }\n\n const {\n flopay,\n paypalFlopay,\n } = await loadSavedPaymentProviders({\n publishableKey,\n paypalPublishableKey,\n billingApiUrl: resolvedBillingUrl,\n locale,\n });\n\n paymentResult = await handleSavedPaymentRedirectResult(redirectResult, {\n flopay,\n paypalFlopay,\n attempt3DS: true,\n billingApiUrl: resolvedBillingUrl,\n sessionId: session.id || resolvedSessionId,\n session,\n });\n\n if (redirectResult.type === 'paypal_redirect_required') {\n clearPayPalResumeState();\n }\n } else if (apiResult.autoProcessingError && !shouldRetryPayPalClientSide) {\n throw checkoutProcessErrorToFloPayError(\n apiResult.autoProcessingError,\n 'Automatic payment failed. Please try again.',\n {\n checkoutMethod: apiResult.autoProcessingError.checkoutMethod,\n },\n );\n } else if (shouldTreatCreateSessionFlowAsServerAutoAttempt && !shouldRetryPayPalClientSide) {\n throw checkoutProcessErrorToFloPayError(\n {\n type: 'unknown',\n message: 'Automatic payment failed. Please try again.',\n },\n 'Automatic payment failed. Please try again.',\n );\n } else {\n const result = await processSavedPaymentForMode({\n billingApiUrl: resolvedBillingUrl,\n sessionId: resolvedSessionId ?? session.id,\n session,\n tokenizedData: automaticPaymentToken,\n });\n\n paymentResult = result.type === 'success'\n ? result.result\n : null;\n\n if (result.type !== 'success') {\n const {\n publishableKey,\n paypalPublishableKey,\n } = resolveSavedPaymentPublishableKeys(apiResult);\n\n if (result.type === 'paypal_redirect_required') {\n persistPayPalResumeState({\n sessionId: session.id || resolvedSessionId,\n publishableKey,\n paypalPublishableKey,\n });\n }\n\n const {\n flopay,\n paypalFlopay,\n } = await loadSavedPaymentProviders({\n publishableKey,\n paypalPublishableKey,\n billingApiUrl: resolvedBillingUrl,\n locale,\n });\n\n paymentResult = await handleSavedPaymentRedirectResult(result, {\n flopay,\n paypalFlopay,\n attempt3DS: true,\n billingApiUrl: resolvedBillingUrl,\n sessionId: session.id || resolvedSessionId,\n session,\n });\n\n if (result.type === 'paypal_redirect_required') {\n clearPayPalResumeState();\n }\n }\n }\n\n await showSuccess({\n result: paymentResult\n ? {\n ...paymentResult,\n paymentMethodId: paymentResult.paymentMethodId ?? paymentMethodId,\n checkoutMethod: paymentResult.checkoutMethod ?? checkoutMethod,\n }\n : {\n status: 'succeeded',\n paymentMethodId: paymentMethodId ?? undefined,\n checkoutMethod,\n },\n session,\n sessionId: session.id || resolvedSessionId,\n autoCompleted: false,\n });\n } catch (err) {\n let floPayErr = normalizeSavedPaymentError(err);\n const fallbackSessionId = session.id || resolvedSessionId;\n const shouldTreatCreateSessionFlowAsServerAutoAttempt =\n options?.fromCreateSession\n && apiResult.autoProcessingAttempted === true;\n\n if (\n !shouldTreatCreateSessionFlowAsServerAutoAttempt &&\n floPayErr.code === 'authentication_required'\n && fallbackSessionId\n && automaticPaymentToken?.id\n && automaticPaymentToken.id.startsWith('pm_')\n ) {\n try {\n const {\n publishableKey,\n paypalPublishableKey,\n } = resolveSavedPaymentPublishableKeys(apiResult);\n const {\n flopay,\n } = await loadSavedPaymentProviders({\n publishableKey,\n paypalPublishableKey,\n billingApiUrl: resolvedBillingUrl,\n locale,\n });\n\n const paymentResult = await processSavedPaymentWithIntent({\n billingApiUrl: resolvedBillingUrl,\n sessionId: fallbackSessionId,\n session,\n paymentMethodId: automaticPaymentToken.id,\n flopay,\n });\n\n await showSuccess({\n result: {\n ...paymentResult,\n paymentMethodId: paymentResult.paymentMethodId ?? paymentMethodId,\n checkoutMethod: paymentResult.checkoutMethod ?? checkoutMethod,\n },\n session,\n sessionId: fallbackSessionId,\n autoCompleted: false,\n });\n return;\n } catch (intentRecoveryErr) {\n floPayErr = normalizeSavedPaymentError(intentRecoveryErr);\n }\n }\n\n // When `confirmPayment` resumes after a PayPal redirect and the PI is\n // already past `requires_action` (manual-capture PayPal lands at\n // `requires_capture` post-authorization), Stripe.js rejects the original\n // promise with `payment_intent_unexpected_state`. The redirect itself\n // succeeded — the resume `useEffect` below will pick up the URL params\n // and finish the capture via /process. Don't open the fallback in that\n // case, otherwise we'd double-charge by re-running PayPal in the modal.\n const inResumeWindow = typeof window !== 'undefined'\n && new URLSearchParams(window.location.search).has('payment_intent_client_secret')\n && !!readPayPalResumeState();\n if (floPayErr.code === 'payment_intent_unexpected_state' && inResumeWindow) {\n return;\n }\n\n // Silent-fallback for cross-account PayPal saved-PM auto attempts: the\n // backend can't attach the saved PM to a PI on the dedicated PayPal\n // gateway, so it returns `paypal_redirect_required` without a\n // `paymentMethodId`. `handleSavedPaymentRedirectResult` recognizes this\n // and throws `paypal_requires_user_interaction` for us. The recovery\n // path is the full-checkout fallback (where `ExpressCheckoutElement`\n // mints a fresh PM during user-driven PayPal click) — open it directly\n // without surfacing an error toast or a decline event, since this\n // isn't a real failure, just a flow handoff.\n //\n // We also catch `payment_intent_unexpected_state` outside the resume\n // window as a defense-in-depth: if Stripe.js returns it for any other\n // reason on the saved-payment auto path, the fallback can recover.\n const isSilentFallbackCase =\n (floPayErr.code === 'paypal_requires_user_interaction'\n || floPayErr.code === 'payment_intent_unexpected_state')\n && shouldShowFallbackCheckout(floPayErr, fallbackSessionId)\n && !!fallbackSessionId\n && isMountedRef.current;\n if (isSilentFallbackCase) {\n setFallbackSession({\n sessionId: fallbackSessionId,\n errorMessage: '',\n });\n return;\n }\n\n await showError(floPayErr, {\n emitDecline: true,\n method: floPayErr.checkoutMethod ?? DEFAULT_SAVED_PAYMENT_DECLINE_METHOD,\n });\n if (\n shouldShowFallbackCheckout(floPayErr, fallbackSessionId) &&\n fallbackSessionId &&\n isMountedRef.current\n ) {\n setFallbackSession({\n sessionId: fallbackSessionId,\n errorMessage: floPayErr.message,\n });\n }\n }\n }, [\n checkoutMethod,\n locale,\n automaticPaymentToken,\n paymentMethodId,\n resolvedBillingUrl,\n showError,\n showSuccess,\n ]);\n\n const handleButtonClick = useCallback(async (event: React.MouseEvent<HTMLButtonElement>) => {\n buttonProps.onClick?.(event);\n\n if (event.defaultPrevented || disabled || isProcessing) {\n return;\n }\n\n setFallbackSession(null);\n\n if (sessionId && createSessionDraft) {\n const error = new FloPayError(\n 'Provide either sessionId or create-session props, not both.',\n 'validation_error',\n );\n await showError(error);\n if (isMountedRef.current) {\n setOverlayStatus(null);\n setOverlayError(null);\n }\n return;\n }\n\n if (!sessionId && !createSessionDraft) {\n const error = new FloPayError(\n 'Provide a sessionId or the props required to create an automatic payment session.',\n 'validation_error',\n );\n await showError(error);\n if (isMountedRef.current) {\n setOverlayStatus(null);\n setOverlayError(null);\n }\n return;\n }\n\n setIsProcessing(true);\n setOverlayError(null);\n setOverlayStatus('processing');\n\n try {\n const api = new PaymentAPI(resolvedBillingUrl);\n\n if (sessionId) {\n const result = await api.getUnifiedCheckoutSession(sessionId);\n await processResolvedSession(result, sessionId);\n return;\n }\n\n try {\n const result = await api.createAndFetchSession({\n ...createSessionDraft!,\n ...(automaticPaymentToken ? { tokenizedData: automaticPaymentToken } : {}),\n });\n await processResolvedSession(result, result.data.session?.id ?? null, {\n fromCreateSession: true,\n });\n } catch (err) {\n if (err instanceof FloPayError && err.code === 'session_auto_completed') {\n await showSuccess({\n result: { status: 'succeeded' },\n session: null,\n sessionId: null,\n autoCompleted: true,\n });\n return;\n }\n\n throw err;\n }\n } catch (err) {\n await showError(\n coerceError(err, 'Automatic payment failed. Please try again.'),\n );\n } finally {\n if (isMountedRef.current) {\n setOverlayStatus(null);\n setOverlayError(null);\n setIsProcessing(false);\n }\n }\n }, [\n buttonProps,\n createSessionDraft,\n disabled,\n isProcessing,\n processResolvedSession,\n resolvedBillingUrl,\n sessionId,\n showError,\n showSuccess,\n ]);\n\n const handleFallbackComplete = useCallback((result: PaymentResult) => {\n const activeFallback = fallbackSessionRef.current;\n setFallbackSession(null);\n onSuccessRef.current?.({\n result,\n session: null,\n sessionId: activeFallback?.sessionId ?? null,\n autoCompleted: false,\n });\n }, []);\n\n const handleFallbackError = useCallback((error: FloPayError) => {\n onErrorRef.current?.(error);\n }, []);\n\n const handleFallbackDecline = useCallback((decline: DeclineEvent) => {\n onDeclineRef.current?.(decline);\n }, []);\n\n useEffect(() => {\n if (typeof window === 'undefined' || resumeAttemptedRef.current) {\n return;\n }\n\n const params = new URLSearchParams(window.location.search);\n const clientSecret = params.get('payment_intent_client_secret');\n if (!clientSecret) {\n return;\n }\n\n const resumeState = readPayPalResumeState();\n if (!resumeState) {\n return;\n }\n\n resumeAttemptedRef.current = true;\n\n void (async () => {\n setIsProcessing(true);\n setOverlayError(null);\n setOverlayStatus('processing');\n\n try {\n if (params.get('redirect_status') === 'failed') {\n throw Object.assign(\n new FloPayError('PayPal payment was declined. Please try again.', 'api_error'),\n { checkoutMethod: 'paypal' as const },\n );\n }\n\n const {\n flopay,\n paypalFlopay,\n } = await loadSavedPaymentProviders({\n publishableKey: resumeState.publishableKey,\n paypalPublishableKey: resumeState.paypalPublishableKey,\n billingApiUrl: resolvedBillingUrl,\n locale,\n });\n\n const paypalStripe = (paypalFlopay ?? flopay).getRawProvider() as import('@stripe/stripe-js').Stripe | null;\n if (!paypalStripe) {\n throw Object.assign(\n new FloPayError('PayPal is not available.', 'api_error'),\n { checkoutMethod: 'paypal' as const },\n );\n }\n\n const { paymentIntent, error } = await paypalStripe.retrievePaymentIntent(clientSecret);\n if (error) {\n throw Object.assign(\n new FloPayError(\n error.message ?? 'Failed to retrieve PayPal payment status.',\n 'api_error',\n { code: error.code },\n ),\n { checkoutMethod: 'paypal' as const },\n );\n }\n\n const resultStatus = mapPayPalIntentStatusToPaymentResult(paymentIntent?.status);\n\n if (!paymentIntent || resultStatus === 'failed') {\n throw Object.assign(\n new FloPayError('PayPal payment was not completed. Please try again.', 'api_error'),\n { checkoutMethod: 'paypal' as const },\n );\n }\n\n const paymentMethodId = typeof paymentIntent.payment_method === 'string'\n ? paymentIntent.payment_method\n : paymentIntent.payment_method?.id;\n\n // Backend has manual capture mode, so PayPal-authorized PIs land at\n // `requires_capture` and the backend must be told to capture via\n // POST /v1/checkouts/sessions/process. Without this call the PI sits\n // at requires_capture forever (\"Uncaptured\" in Stripe).\n if (!resumeState.sessionId) {\n throw Object.assign(\n new FloPayError('Missing session id on PayPal resume.', 'api_error'),\n { checkoutMethod: 'paypal' as const },\n );\n }\n\n const api = new PaymentAPI(resolvedBillingUrl);\n const sessionResult = await api.getUnifiedCheckoutSession(resumeState.sessionId);\n let resumeSession = sessionResult.data.session;\n if (!resumeSession) {\n throw Object.assign(\n new FloPayError('Could not load session to capture PayPal payment.', 'api_error'),\n { checkoutMethod: 'paypal' as const },\n );\n }\n\n let finalResultStatus: PaymentResult['status'] = resultStatus;\n if (resumeSession.status !== 'complete') {\n const processResult = await processSavedPaymentForMode({\n billingApiUrl: resolvedBillingUrl,\n sessionId: resumeState.sessionId,\n session: resumeSession,\n tokenizedData: {\n id: paymentMethodId ?? paymentIntent.id,\n type: 'card',\n threeDSecureActionResultTokenId: paymentIntent.id,\n isPaypal: true,\n },\n });\n\n if (processResult.type !== 'success') {\n throw Object.assign(\n new FloPayError('Failed to finalize PayPal payment.', 'api_error'),\n { checkoutMethod: 'paypal' as const },\n );\n }\n\n // /process succeeded -> backend captured the PI and marked the\n // session complete. Refresh the session so the snapshot we hand to\n // `onSuccess` reflects the post-capture state instead of the\n // pre-capture one we fetched above. Trust /process's result.status\n // ('succeeded') over the PI's pre-capture status mapping.\n finalResultStatus = processResult.result.status;\n try {\n const refreshed = await api.getUnifiedCheckoutSession(resumeState.sessionId);\n if (refreshed.data.session) {\n resumeSession = refreshed.data.session;\n }\n } catch {\n // Refresh is best-effort; if it fails the buyer is still captured\n // and we'll fall back to the pre-capture session snapshot rather\n // than failing the whole flow.\n }\n }\n\n await showSuccess({\n result: {\n status: finalResultStatus,\n paymentIntentId: paymentIntent.id,\n paymentMethodId,\n checkoutMethod: 'paypal',\n },\n session: resumeSession,\n sessionId: resumeState.sessionId,\n autoCompleted: false,\n });\n } catch (err) {\n const floPayErr = normalizeSavedPaymentError(err);\n await showError(floPayErr, {\n emitDecline: true,\n method: floPayErr.checkoutMethod ?? 'paypal',\n });\n } finally {\n clearPayPalResumeState();\n clearPayPalRedirectParams();\n\n if (isMountedRef.current) {\n setOverlayStatus(null);\n setOverlayError(null);\n setIsProcessing(false);\n }\n }\n })();\n }, [locale, resolvedBillingUrl, showError, showSuccess]);\n\n const bStyles = useMemo<ButtonsLayoutStyles>(() => {\n const base = resolveButtonsLayoutTheme(buttonsTheme);\n if (!stylesOverride) return base;\n return {\n ...base,\n ...stylesOverride,\n cardButton: { ...base.cardButton, ...stylesOverride.cardButton },\n };\n }, [buttonsTheme, stylesOverride]);\n\n const cardButtonSizing = children === undefined\n ? { boxSizing: 'border-box' as const, height: DEFAULT_BUTTONS_LAYOUT_BUTTON_HEIGHT, padding: '0 1rem' }\n : { padding: '0.9rem 1rem' };\n\n return (\n <>\n <button\n {...buttonProps}\n type={type}\n onClick={handleButtonClick}\n disabled={disabled || isProcessing}\n aria-busy={isProcessing}\n style={{\n width: '100%',\n ...cardButtonSizing,\n backgroundColor: 'white',\n color: '#262833',\n border: '1px solid #d1d5db',\n borderRadius: '8px',\n fontSize: bStyles.cardButtonFontSize ?? '0.95rem',\n fontWeight: 600,\n cursor: disabled || isProcessing ? 'not-allowed' : 'pointer',\n display: 'flex',\n alignItems: 'center',\n justifyContent: 'center',\n gap: '0.625rem',\n boxShadow: '0 1px 2px rgba(0,0,0,0.04)',\n transition: 'border-color 0.2s, box-shadow 0.2s, transform 0.1s',\n position: 'relative',\n opacity: disabled || isProcessing ? 0.6 : 1,\n ...bStyles.cardButton as React.CSSProperties,\n ...style,\n }}\n onMouseDown={(e) => {\n buttonProps.onMouseDown?.(e);\n if (!e.defaultPrevented) {\n e.currentTarget.style.transform = 'scale(0.985)';\n }\n }}\n onMouseUp={(e) => {\n buttonProps.onMouseUp?.(e);\n if (!e.defaultPrevented) {\n e.currentTarget.style.transform = 'scale(1)';\n }\n }}\n >\n <CardButtonContentSlot content={children} />\n </button>\n {overlayStatus && (\n <ProcessingOverlay\n status={overlayStatus}\n errorMessage={overlayError}\n />\n )}\n {fallbackSession && (\n <div\n data-testid=\"flopay-automatic-payment-fallback\"\n role=\"dialog\"\n aria-modal=\"true\"\n onClick={(event) => {\n if (event.target === event.currentTarget) {\n setFallbackSession(null);\n }\n }}\n style={{\n position: 'fixed',\n inset: 0,\n background: 'rgba(0, 0, 0, 0.45)',\n display: 'flex',\n alignItems: 'center',\n justifyContent: 'center',\n padding: '1.5rem',\n zIndex: 1100,\n }}\n >\n <div\n style={{\n width: '100%',\n maxWidth: 520,\n maxHeight: '90vh',\n overflowY: 'auto',\n background: 'white',\n borderRadius: 20,\n padding: '1.5rem',\n boxShadow: '0 24px 80px rgba(15, 23, 42, 0.28)',\n display: 'flex',\n flexDirection: 'column',\n gap: '1rem',\n }}\n >\n <FloPayCheckout\n sessionId={fallbackSession.sessionId}\n checkoutMode=\"full\"\n billingApiUrl={resolvedBillingUrl}\n initialErrorMessage={fallbackSession.errorMessage}\n cardTitleContent={null}\n showSecurityFooter={false}\n onComplete={handleFallbackComplete}\n onError={handleFallbackError}\n onDecline={handleFallbackDecline}\n />\n </div>\n </div>\n )}\n </>\n );\n}\n"],"mappings":";AAAA,SAAgB,WAAW,UAAU,eAAe;AAGpD,SAAS,4BAA4B;;;ACHrC,SAAS,qBAAqB;AAmCvB,IAAM,gBAAgB,cAAkC;AAAA,EAC7D,QAAQ;AAAA,EACR,cAAc;AAAA,EACd,UAAU;AAAA,EACV,eAAe;AACjB,CAAC;AAEM,IAAM,kBAAkB,cAAoC;AAAA,EACjE,SAAS;AAAA,EACT,SAAS;AAAA,EACT,OAAO;AACT,CAAC;;;AD+FG;AA/FG,SAAS,eAAe;AAAA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AAAA,YAEA,0BAAAA;AAAA,cAAC;AAAA;AAAA,gBACC,WAAW,gBAAgB;AAAA,gBAC3B,cAAa;AAAA,gBACb,eAAe;AAAA,gBACf,qBAAqB,gBAAgB;AAAA,gBACrC,kBAAkB;AAAA,gBAClB,oBAAoB;AAAA,gBACpB,YAAY;AAAA,gBACZ,SAAS;AAAA,gBACT,WAAW;AAAA;AAAA,YACb;AAAA;AAAA,QACF;AAAA;AAAA,IACF;AAAA,KAEJ;AAEJ;","names":["React","useCallback","useEffect","useMemo","useRef","useState","PaymentAPI","FloPayError","resolveBillingApiUrl","resolveButtonsLayoutTheme","jsx","useEffect","jsx","useEffect","useCallback","useContext","useEffect","useMemo","useRef","useState","useContext","resolveBillingApiUrl","useContext","resolveBillingApiUrl","jsx","jsxs","useEffect","useState","jsx","jsxs","useState","useEffect","FloPayError","Fragment","jsx","jsxs","SplitCardForm","useState","useRef","useEffect","useCallback","useContext","useMemo","stateValue","message","error","FloPayError","FloPayError","error","Fragment","jsx","jsxs","DEFAULT_BUTTONS_LAYOUT_BUTTON_HEIGHT","resolveBillingApiUrl","useState","useRef","useEffect","useMemo","useCallback","activeSessionId","FloPayError","PaymentAPI","React","resolveButtonsLayoutTheme","FloPayError","forwardRef","useCallback","useEffect","useImperativeHandle","useState","Fragment","jsx","jsxs","WALLET_RESUME_KEY","forwardRef","CheckoutForm","useState","useCallback","useImperativeHandle","useEffect","FloPayError","error","FloPayError","useCallback","useEffect","useRef","useState","Fragment","jsx","jsxs","useState","useRef","useCallback","useEffect","FloPayError","useCallback","useEffect","useMemo","useRef","useState","PaymentAPI","FloPayError","resolveBillingApiUrl","resolveButtonsLayoutTheme","Fragment","jsx","jsxs","DEFAULT_BUTTONS_LAYOUT_BUTTON_HEIGHT","PAYPAL_RESUME_STORAGE_KEY","sleep","FloPayError","canUseStorage","readPayPalResumeState","persistPayPalResumeState","clearPayPalResumeState","clearPayPalRedirectParams","useMemo","resolveBillingApiUrl","useState","useRef","useEffect","useCallback","PaymentAPI","paymentMethodId","resolveButtonsLayoutTheme"]}
|
|
1
|
+
{"version":3,"sources":["../src/provider.tsx","../src/context.ts","../src/flopay-checkout.tsx","../src/card-button-content.tsx","../src/elements.tsx","../src/split-card-form.tsx","../src/hooks.ts","../src/processing-overlay.tsx","../src/checkout-utils.ts","../src/recent-completion.ts","../src/in-app-browser.ts","../src/saved-payment-flow.ts","../src/checkout-form.tsx","../src/paypal-button.tsx","../src/automatic-payment-button.tsx"],"sourcesContent":["import React, { useEffect, useState, useMemo } from 'react';\nimport type { FloPay, FloPayElements } from '@flopay/js';\nimport type { FloPayAppearance } from '@flopay/shared';\nimport { resolveBillingApiUrl } from '@flopay/shared';\nimport { FloPayContext } from './context.js';\n\n/** Props for the `FloPayProvider` component. */\nexport interface FloPayProviderProps {\n /** A `FloPay` instance or a promise that resolves to one (from `loadFloPay()`). */\n flopay: Promise<FloPay> | FloPay;\n /**\n * Optional dedicated `FloPay` instance for PayPal, loaded with\n * `gatewayData.paypalPublishableKey`. When omitted or `null`, PayPal is\n * disabled (the button is not rendered).\n */\n paypalFlopay?: Promise<FloPay> | FloPay | null;\n /** Optional configuration applied when creating the elements group. */\n options?: {\n locale?: string;\n appearance?: FloPayAppearance;\n clientSecret?: string;\n /** Total amount in smallest currency unit (cents). Used when no clientSecret. */\n amount?: number;\n /** ISO 4217 currency code (lowercase). Used when no clientSecret. */\n currency?: string;\n /** How payment methods are created. 'manual' (default for cards) or 'auto' (needed for PayPal). */\n paymentMethodCreation?: 'manual' | 'auto';\n /** Requests reusable payment credentials for future payments. */\n setupFutureUsage?: 'off_session' | 'on_session';\n /** Billing API base URL. Set once here so child components don't need to repeat it. */\n billingApiUrl?: string;\n };\n children: React.ReactNode;\n}\n\n/**\n * Provides FloPay SDK context to the component tree.\n *\n * Wrap your checkout page (or your entire app) with this provider:\n *\n * ```tsx\n * <FloPayProvider flopay={loadFloPay('pk_test_...')}>\n * <CheckoutForm />\n * </FloPayProvider>\n * ```\n */\nexport function FloPayProvider({\n flopay: floPayProp,\n paypalFlopay: paypalFloPayProp,\n options,\n children,\n}: FloPayProviderProps): React.ReactElement {\n const [flopay, setFloPay] = useState<FloPay | null>(\n floPayProp instanceof Promise ? null : floPayProp,\n );\n const [paypalFlopay, setPaypalFloPay] = useState<FloPay | null>(\n paypalFloPayProp instanceof Promise || !paypalFloPayProp ? null : paypalFloPayProp,\n );\n const [elements, setElements] = useState<FloPayElements | null>(null);\n\n // Resolve the promise if needed\n useEffect(() => {\n let cancelled = false;\n\n if (floPayProp instanceof Promise) {\n floPayProp.then((instance) => {\n if (!cancelled) {\n setFloPay(instance);\n }\n });\n } else {\n setFloPay(floPayProp);\n }\n\n return () => {\n cancelled = true;\n };\n }, [floPayProp]);\n\n // Resolve the PayPal promise / prop\n useEffect(() => {\n let cancelled = false;\n\n if (!paypalFloPayProp) {\n setPaypalFloPay(null);\n return;\n }\n\n if (paypalFloPayProp instanceof Promise) {\n paypalFloPayProp.then((instance) => {\n if (!cancelled) {\n setPaypalFloPay(instance);\n }\n });\n } else {\n setPaypalFloPay(paypalFloPayProp);\n }\n\n return () => {\n cancelled = true;\n };\n }, [paypalFloPayProp]);\n\n // Create elements group once FloPay is ready\n useEffect(() => {\n if (!flopay) {\n setElements(null);\n return;\n }\n\n const els = flopay.elements({\n appearance: options?.appearance,\n clientSecret: options?.clientSecret,\n amount: options?.amount,\n currency: options?.currency,\n paymentMethodCreation: options?.paymentMethodCreation,\n setupFutureUsage: options?.setupFutureUsage,\n });\n setElements(els);\n\n return () => {\n els.destroy();\n };\n }, [\n flopay,\n options?.appearance,\n options?.clientSecret,\n options?.amount,\n options?.currency,\n options?.paymentMethodCreation,\n options?.setupFutureUsage,\n ]);\n\n const resolvedBillingApiUrl = resolveBillingApiUrl(options?.billingApiUrl);\n\n const value = useMemo(\n () => ({ flopay, paypalFlopay, elements, billingApiUrl: resolvedBillingApiUrl }),\n [flopay, paypalFlopay, elements, resolvedBillingApiUrl],\n );\n\n return (\n <FloPayContext.Provider value={value}>\n {children}\n </FloPayContext.Provider>\n );\n}\n","import { createContext } from 'react';\nimport type { FloPay, FloPayElements } from '@flopay/js';\nimport type {\n CheckoutMode,\n CheckoutSession,\n FloPayError,\n InlineSessionDraft,\n InlineSessionPatch,\n} from '@flopay/shared';\n\n/** Internal context value for the FloPay provider. */\nexport interface FloPayContextValue {\n flopay: FloPay | null;\n /**\n * Dedicated FloPay instance for PayPal, loaded with `gatewayData.paypalPublishableKey`.\n * `null` or absent means PayPal is disabled for the current session.\n */\n paypalFlopay?: FloPay | null;\n elements: FloPayElements | null;\n billingApiUrl: string;\n}\n\n/** Internal context value for checkout state. */\nexport interface CheckoutContextValue {\n session: CheckoutSession | null;\n loading: boolean;\n error: FloPayError | null;\n checkoutMode?: CheckoutMode;\n inlineSessionDraft?: InlineSessionDraft;\n applyInlineSessionPatch?: (\n patch: InlineSessionPatch,\n ) => Promise<{ sessionId: string; session: CheckoutSession | null }>;\n inlineSessionPatchProcessing?: boolean;\n}\n\nexport const FloPayContext = createContext<FloPayContextValue>({\n flopay: null,\n paypalFlopay: null,\n elements: null,\n billingApiUrl: '',\n});\n\nexport const CheckoutContext = createContext<CheckoutContextValue>({\n session: null,\n loading: false,\n error: null,\n});\n","import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport { PaymentAPI } from '@flopay/js';\nimport type { FloPay } from '@flopay/js';\nimport type {\n BeforeButtonClickEvent,\n CheckoutButtonMethod,\n FloPayAppearance,\n DeclineEvent,\n InlineSessionDraft,\n InlineSessionParams,\n InlineSessionPatch,\n PaymentResult,\n CheckoutSession,\n CheckoutMode,\n NormalizedCheckoutSession,\n} from '@flopay/shared';\nimport { SDK_VERSION, FloPayError, resolveBillingApiUrl, buildCheckoutDisplayData, resolveButtonsLayoutTheme } from '@flopay/shared';\nimport type { ButtonsLayoutStyles, ButtonsLayoutTheme } from '@flopay/shared';\nimport {\n BackButtonContentSlot,\n CardButtonContentSlot,\n TitleContentSlot,\n isEmptySlotContent,\n} from './card-button-content.js';\nimport { FloPayProvider } from './provider.js';\nimport { SplitCardForm } from './split-card-form.js';\nimport { CheckoutContext } from './context.js';\nimport {\n buildDeclineEvent,\n buildSyntheticSession,\n mapPayPalIntentStatusToPaymentResult,\n mergeInlineSessionPatch,\n mergeInlineSessionPatches,\n} from './checkout-utils.js';\nimport {\n PROCESSING_OVERLAY_ERROR_DELAY_MS,\n PROCESSING_OVERLAY_SUCCESS_DELAY_MS,\n ProcessingOverlay,\n type OverlayStatus,\n} from './processing-overlay.js';\nimport {\n checkoutProcessErrorToFloPayError,\n DEFAULT_SAVED_PAYMENT_DECLINE_METHOD,\n getRedirectResultFromCheckoutProcessError,\n handleSavedPaymentRedirectResult,\n loadSavedPaymentProviders,\n normalizeSavedPaymentError,\n processSavedPaymentForMode,\n resolveSavedPaymentPublishableKeys,\n} from './saved-payment-flow.js';\nimport { markSessionRecentlyCompleted, wasSessionRecentlyCompleted } from './recent-completion.js';\n\nconst DEFAULT_BUTTONS_LAYOUT_BUTTON_HEIGHT = 44;\nconst PAYPAL_RESUME_STORAGE_KEY = 'flopay_checkout_saved_payment_resume';\n\n// Module-scoped dedup map: cache key → in-flight `POST /v1/checkouts/sessions`\n// promise. Lives for the page-load only. Shared across every FloPayCheckout\n// instance so two mounts that race (StrictMode dev double-mount, Suspense\n// remount, navigation flicker, etc.) await the same POST instead of starting\n// their own and producing two backend sessions for the same cart.\n// `sessionStorage[cacheKey]` is the durable cross-page-load layer; this Map\n// is the within-page-load layer that closes the window between \"POST is in\n// flight\" and \"POST result has been written to sessionStorage\".\nconst sessionInflightMap: Map<string, Promise<{ sid: string; result: NormalizedCheckoutSession }>> = new Map();\n\n// Cross-module signal for \"this session was just /process'd successfully and\n// is mid-completion.\" Lives in sessionStorage (see `recent-completion.ts`) so\n// it survives both real component remounts and the cross-module boundary\n// between SplitCardForm (where /process succeeds) and this file (where\n// `resolveInlineSession` decides whether to clear a complete-status cache\n// hit). Marker is written *before* the 1.2s overlay delay in SplitCardForm,\n// so a bootstrap that re-runs during that delay still detects the session\n// as \"this journey's completion\" and reuses it.\ntype CheckoutLogType = 'standard_checkout' | 'embedded_checkout';\ntype CheckoutLogLayout = 'default_layout' | 'buttons_layout' | 'custom_layout';\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\ninterface PayPalResumeState {\n sessionId: string | null;\n publishableKey: string;\n paypalPublishableKey?: string;\n}\n\nfunction canUseStorage() {\n return typeof window !== 'undefined' && typeof window.sessionStorage !== 'undefined';\n}\n\nfunction readPayPalResumeState(): PayPalResumeState | null {\n if (!canUseStorage()) return null;\n\n try {\n const raw = window.sessionStorage.getItem(PAYPAL_RESUME_STORAGE_KEY);\n if (!raw) return null;\n return JSON.parse(raw) as PayPalResumeState;\n } catch {\n return null;\n }\n}\n\nfunction persistPayPalResumeState(state: PayPalResumeState) {\n if (!canUseStorage()) return;\n\n try {\n window.sessionStorage.setItem(PAYPAL_RESUME_STORAGE_KEY, JSON.stringify(state));\n } catch (error) {\n console.warn('[FloPayCheckout] Failed to persist PayPal resume state.', error);\n }\n}\n\nfunction clearPayPalResumeState() {\n if (!canUseStorage()) return;\n\n try {\n window.sessionStorage.removeItem(PAYPAL_RESUME_STORAGE_KEY);\n } catch (error) {\n console.warn('[FloPayCheckout] Failed to clear PayPal resume state.', error);\n }\n}\n\nfunction clearPayPalRedirectParams() {\n if (typeof window === 'undefined') return;\n\n const url = new URL(window.location.href);\n const keys = ['payment_intent', 'payment_intent_client_secret', 'redirect_status'];\n let changed = false;\n\n for (const key of keys) {\n if (url.searchParams.has(key)) {\n url.searchParams.delete(key);\n changed = true;\n }\n }\n\n if (changed) {\n window.history.replaceState(window.history.state, '', url.toString());\n }\n}\n\nfunction replaceCheckoutModeQueryParam(mode: CheckoutMode) {\n if (typeof window === 'undefined') return;\n\n const url = new URL(window.location.href);\n url.searchParams.set('mode', mode);\n window.history.replaceState(window.history.state, '', url.toString());\n}\n\n/** Props for the all-in-one `FloPayCheckout` wrapper. */\nexport interface FloPayCheckoutProps {\n /** The checkout session ID (UUID from billing API). Required unless `createSession` is provided. */\n sessionId?: string;\n /**\n * Create a checkout session inline — no separate API route needed.\n * The component POSTs to the billing API, gets the full session back, and renders the form.\n * Alternative to `sessionId` (provide one or the other).\n */\n createSession?: InlineSessionDraft;\n /** Billing API base URL. Defaults to the shared `BILLING_API_URL` constant. */\n billingApiUrl?: string;\n /** Visual appearance for payment elements. */\n appearance?: FloPayAppearance;\n /** Locale for payment elements (default: 'auto'). */\n locale?: string;\n /** Custom loading UI. Defaults to a simple centered spinner. */\n loading?: React.ReactNode;\n /** Custom error UI. Receives the error. Defaults to showing the error message. */\n error?: (error: FloPayError) => React.ReactNode;\n /** Called when the full payment flow completes successfully. */\n onComplete?: (result: PaymentResult) => void;\n /** Called when a payment error occurs. */\n onError?: (error: FloPayError) => void;\n /** Called when a payment is declined or the authentication step fails. */\n onDecline?: (decline: DeclineEvent) => void;\n /** Called when the full cardholder name input changes. */\n onFullNameChange?: (value: string) => void;\n /** Called when the AVS country dropdown changes. */\n onCountryChange?: (country: string) => void;\n /** Called when the AVS ZIP/postcode input changes. */\n onZipChange?: (zip: string) => void;\n /** Whether to show the PayPal button (default: true). */\n showPayPal?: boolean;\n /** Whether to show Apple Pay button (default: true). Only renders on supported devices. */\n showApplePay?: boolean;\n /** Whether to show Google Pay button (default: true). Only renders on supported devices. */\n showGooglePay?: boolean;\n /** Layout mode: 'default' (all visible) or 'buttons' (PayPal/wallets + expandable card form). */\n layout?: 'default' | 'buttons';\n /** Theme preset for the buttons layout: 'default', 'minimal', 'rounded', or 'dark'. */\n buttonsTheme?: import('@flopay/shared').ButtonsLayoutTheme;\n /** Custom style overrides for the buttons layout. Merged on top of the theme preset. */\n buttonsStyles?: import('@flopay/shared').ButtonsLayoutStyles;\n /** Custom React content rendered inside the card button when `layout=\"buttons\"`. */\n cardButtonContent?: React.ReactNode;\n /** Custom React content rendered for the buttons-layout card back button label. */\n cardBackButtonContent?: React.ReactNode;\n /** Custom React content rendered for the card-form title. */\n cardTitleContent?: React.ReactNode;\n /** Whether to show the default security footer in `layout=\"default\"`. Defaults to `true`. */\n showSecurityFooter?: boolean;\n /**\n * Called when a payment method button is clicked.\n * `method`: `'card'` | `'paypal'` | `'apple_pay'` | `'google_pay'`\n */\n onButtonClick?: (method: CheckoutButtonMethod) => void;\n /**\n * Called before a payment button continues in `layout=\"buttons\"`.\n * Runs for card, PayPal, Apple Pay, and Google Pay.\n * In `layout=\"buttons\"` with `createSession`, the returned patch is merged\n * into the inline session params before the selected flow continues.\n */\n onBeforeButtonClick?: (\n event: BeforeButtonClickEvent,\n ) => void | false | Promise<void | false | InlineSessionPatch> | InlineSessionPatch;\n /**\n * Enable AVS (Address Verification).\n * - `true` — show country + postal code (backward compatible default)\n * - `AVSFieldConfig` — granular per-field control, optionally scoped to country codes\n * - `false` / omitted — AVS disabled\n */\n enableAVS?: boolean | import('@flopay/shared').AVSFieldConfig;\n /** Layout for AVS fields: 'row' (side-by-side, default) or 'column' (stacked). */\n avsLayout?: 'row' | 'column';\n /** Label for the submit button. */\n submitLabel?: string;\n /** Additional CSS class for the wrapper. */\n className?: string;\n /** Seed an initial checkout error message for the rendered payment form. */\n initialErrorMessage?: string | null;\n /**\n * Override the default `SplitCardForm`. When provided, children are rendered\n * inside the initialized `FloPayProvider` with session props auto-injected.\n */\n children?: React.ReactNode;\n\n // ── Checkout mode props ──\n\n /**\n * Override the session's checkoutMode.\n * - `'full'` — show payment form (default)\n * - `'confirm'` — show confirm button, uses saved payment method\n * - `'auto'` — auto-submit with saved PM, falls back to `'full'` on failure\n */\n checkoutMode?: CheckoutMode;\n /** Label for the confirm button in `confirm` mode. Default: `'Confirm Purchase'`. */\n confirmLabel?: string;\n /** Custom confirm button renderer for `confirm` mode. */\n renderConfirmButton?: (props: {\n onConfirm: () => void;\n isProcessing: boolean;\n }) => React.ReactNode;\n /** Called when the session has already been completed. Receives the successUrl. */\n onSessionCompleted?: (successUrl: string) => void;\n\n /**\n * @deprecated No longer used. The Stripe publishable key is sourced exclusively\n * from the checkout session's `gatewayData.publishableKey`. Accepted only for\n * backward compatibility with older consumer code — the value is ignored.\n */\n fallbackPublishableKey?: string;\n}\n\nfunction hasInlineSessionPatchData(\n patch: InlineSessionPatch | undefined,\n): boolean {\n if (!patch) return false;\n\n return Boolean(\n (patch.account && Object.keys(patch.account).length > 0)\n || patch.couponCodes !== undefined\n || patch.tagsData !== undefined\n || patch.utmMetadata !== undefined,\n );\n}\n\n/**\n * All-in-one checkout component. Fetches the session, initializes the\n * payment provider, and renders the appropriate UI based on checkout mode.\n *\n * **Modes:**\n * - `full` (default) — renders `SplitCardForm` with card fields + wallet buttons\n * - `confirm` — renders a \"Confirm Purchase\" button, uses saved payment method\n * - `auto` — auto-submits with saved PM, falls back to `full` on failure\n *\n * ```tsx\n * <FloPayCheckout\n * sessionId=\"sess_abc123\"\n * onComplete={(result) => router.push('/success')}\n * onError={(err) => console.error(err)}\n * />\n * ```\n */\nexport function FloPayCheckout({\n sessionId: sessionIdProp,\n createSession: createSessionParams,\n billingApiUrl,\n appearance,\n locale,\n loading: loadingNode,\n error: errorNode,\n onComplete,\n onError,\n onDecline,\n onFullNameChange,\n onCountryChange,\n onZipChange,\n showPayPal = true,\n showApplePay = true,\n showGooglePay = true,\n layout,\n buttonsTheme,\n buttonsStyles,\n cardButtonContent,\n cardBackButtonContent,\n cardTitleContent,\n showSecurityFooter = true,\n onButtonClick,\n onBeforeButtonClick,\n enableAVS,\n avsLayout,\n submitLabel,\n className,\n initialErrorMessage = null,\n children,\n checkoutMode: checkoutModeProp,\n confirmLabel,\n renderConfirmButton,\n onSessionCompleted,\n}: FloPayCheckoutProps): React.ReactElement {\n const resolvedBillingUrl = resolveBillingApiUrl(billingApiUrl);\n const checkoutType: CheckoutLogType = createSessionParams ? 'embedded_checkout' : 'standard_checkout';\n const checkoutLayout: CheckoutLogLayout = children\n ? 'custom_layout'\n : layout === 'buttons'\n ? 'buttons_layout'\n : 'default_layout';\n\n const [unified, setUnified] = useState<NormalizedCheckoutSession | null>(null);\n const [flopay, setFloPay] = useState<FloPay | null>(null);\n const flopayRef = useRef<FloPay | null>(null);\n const [paypalFlopay, setPaypalFloPay] = useState<FloPay | null>(null);\n const paypalFlopayRef = useRef<FloPay | null>(null);\n const [session, setSession] = useState<CheckoutSession | null>(null);\n const [resolvedSessionId, setResolvedSessionId] = useState<string>(sessionIdProp ?? '');\n const activeSessionId = sessionIdProp ?? resolvedSessionId;\n const initSessionDependency = createSessionParams ? '' : activeSessionId;\n const [isLoading, setIsLoading] = useState(true);\n const [loadError, setLoadError] = useState<FloPayError | null>(null);\n const [currentMode, setCurrentMode] = useState<CheckoutMode>('full');\n const [confirmProcessing, setConfirmProcessing] = useState(false);\n const [modeError, setModeError] = useState<string | null>(initialErrorMessage);\n const [modeOverlayStatus, setModeOverlayStatus] = useState<OverlayStatus | null>(null);\n const [modeOverlayError, setModeOverlayError] = useState<string | null>(null);\n const [createSessionPatch, setCreateSessionPatch] = useState<InlineSessionPatch | undefined>(undefined);\n const [createSessionPatchBaseHash, setCreateSessionPatchBaseHash] = useState('');\n const [cardBootstrapPending, setCardBootstrapPending] = useState(false);\n const autoCheckoutAttempted = useRef(false);\n const paypalResumeAttempted = useRef(false);\n const savedPaymentKeysRef = useRef<{\n publishableKey: string;\n paypalPublishableKey?: string;\n } | null>(null);\n\n // Store callbacks in refs to avoid re-triggering the init useEffect\n const onCompleteRef = useRef(onComplete);\n onCompleteRef.current = onComplete;\n const onErrorRef = useRef(onError);\n onErrorRef.current = onError;\n const onDeclineRef = useRef(onDecline);\n onDeclineRef.current = onDecline;\n const onSessionCompletedRef = useRef(onSessionCompleted);\n onSessionCompletedRef.current = onSessionCompleted;\n\n useEffect(() => {\n console.info('[FloPay] Checkout initialized', {\n sdk_version: SDK_VERSION,\n checkout_type: checkoutType,\n checkout_layout: checkoutLayout,\n billing_api_url: resolvedBillingUrl,\n });\n }, [checkoutLayout, checkoutType, resolvedBillingUrl]);\n\n const baseCreateSessionHash = useMemo(\n () => createSessionParams ? hashCreateParams(createSessionParams) : '',\n [createSessionParams],\n );\n const activeCreateSessionPatch = useMemo(\n () => createSessionPatchBaseHash === baseCreateSessionHash\n ? createSessionPatch\n : undefined,\n [createSessionPatch, createSessionPatchBaseHash, baseCreateSessionHash],\n );\n const effectiveCreateSessionBase = useMemo(\n () => createSessionParams\n ? mergeInlineSessionPatch(createSessionParams, activeCreateSessionPatch)\n : undefined,\n [createSessionParams, activeCreateSessionPatch],\n );\n const effectiveCreateSessionMode = checkoutModeProp ?? effectiveCreateSessionBase?.checkoutMode ?? 'full';\n const effectiveCreateSession = useMemo(\n () => effectiveCreateSessionBase\n ? {\n ...effectiveCreateSessionBase,\n checkoutMode: effectiveCreateSessionMode,\n }\n : undefined,\n [effectiveCreateSessionBase, effectiveCreateSessionMode],\n );\n\n useEffect(() => {\n setCreateSessionPatch(undefined);\n setCreateSessionPatchBaseHash(baseCreateSessionHash);\n }, [baseCreateSessionHash]);\n\n useEffect(() => {\n setModeError(initialErrorMessage);\n }, [initialErrorMessage]);\n\n const emitDecline = useCallback(\n (\n method: CheckoutButtonMethod,\n input: string | FloPayError,\n overrides?: { code?: string; declineCode?: string },\n ) => {\n onDeclineRef.current?.(buildDeclineEvent(method, input, overrides));\n },\n [],\n );\n\n const runSavedPaymentFlow = useCallback(\n async (\n sess: CheckoutSession,\n options?: {\n attempt3DS?: boolean;\n fallbackToFull?: boolean;\n ensureProvidersReady?: () => Promise<unknown>;\n fromCreateSession?: boolean;\n initialAutoProcessingError?: NormalizedCheckoutSession['autoProcessingError'];\n initialAutoProcessingPending?: NormalizedCheckoutSession['autoProcessingPending'];\n autoProcessingAttempted?: boolean;\n sessionId?: string;\n },\n ): Promise<boolean> => {\n setModeError(null);\n setModeOverlayError(null);\n setModeOverlayStatus('processing');\n\n const activeSessionId = options?.sessionId ?? sess.id;\n\n try {\n const redirectResult = getRedirectResultFromCheckoutProcessError(options?.initialAutoProcessingError);\n let paymentResult: PaymentResult;\n\n if (redirectResult) {\n if (\n redirectResult.type === 'paypal_redirect_required'\n && savedPaymentKeysRef.current\n ) {\n persistPayPalResumeState({\n sessionId: activeSessionId,\n publishableKey: savedPaymentKeysRef.current.publishableKey,\n paypalPublishableKey: savedPaymentKeysRef.current.paypalPublishableKey,\n });\n }\n\n paymentResult = await handleSavedPaymentRedirectResult(redirectResult, {\n flopay: flopayRef.current,\n paypalFlopay: paypalFlopayRef.current,\n attempt3DS: options?.attempt3DS,\n billingApiUrl: resolvedBillingUrl,\n sessionId: activeSessionId,\n session: sess,\n });\n\n if (redirectResult.type === 'paypal_redirect_required') {\n clearPayPalResumeState();\n }\n } else if (options?.initialAutoProcessingPending) {\n const api = new PaymentAPI(resolvedBillingUrl);\n const completed = await api.waitForCheckoutSessionCompletion(options.initialAutoProcessingPending.sessionId, {\n initialDelayMs: options.initialAutoProcessingPending.retryAfterMs,\n });\n\n if (completed.data.session?.status !== 'complete') {\n throw new FloPayError('Automatic payment failed. Please try again.', 'api_error', {\n code: completed.data.session?.status === 'expired'\n ? 'checkout_session_expired'\n : 'checkout_processing_timeout',\n });\n }\n\n paymentResult = { status: 'succeeded' };\n } else if (options?.initialAutoProcessingError) {\n throw checkoutProcessErrorToFloPayError(\n options.initialAutoProcessingError,\n 'Automatic payment failed. Please try again.',\n {\n checkoutMethod: options.initialAutoProcessingError.checkoutMethod,\n },\n );\n } else if (options?.fromCreateSession) {\n if (options?.fallbackToFull) {\n setCurrentMode('full');\n replaceCheckoutModeQueryParam('full');\n }\n return false;\n } else {\n const result = await processSavedPaymentForMode({\n billingApiUrl: resolvedBillingUrl,\n sessionId: activeSessionId,\n session: sess,\n });\n if (result.type === 'success') {\n paymentResult = result.result;\n } else {\n if (\n result.type === 'paypal_redirect_required'\n && savedPaymentKeysRef.current\n ) {\n persistPayPalResumeState({\n sessionId: activeSessionId,\n publishableKey: savedPaymentKeysRef.current.publishableKey,\n paypalPublishableKey: savedPaymentKeysRef.current.paypalPublishableKey,\n });\n }\n\n paymentResult = await handleSavedPaymentRedirectResult(result, {\n flopay: flopayRef.current,\n paypalFlopay: paypalFlopayRef.current,\n attempt3DS: options?.attempt3DS,\n billingApiUrl: resolvedBillingUrl,\n sessionId: activeSessionId,\n session: sess,\n });\n\n if (result.type === 'paypal_redirect_required') {\n clearPayPalResumeState();\n }\n }\n }\n\n // Mark before the overlay delay so a bootstrap that re-runs during\n // the delay window detects the completion and reuses the session.\n if (activeSessionId) markSessionRecentlyCompleted(activeSessionId);\n setModeOverlayStatus('success');\n await sleep(PROCESSING_OVERLAY_SUCCESS_DELAY_MS);\n onCompleteRef.current?.(paymentResult);\n return true;\n } catch (err) {\n const floPayErr = normalizeSavedPaymentError(err);\n const method = floPayErr.checkoutMethod ?? DEFAULT_SAVED_PAYMENT_DECLINE_METHOD;\n\n setModeError(floPayErr.message);\n setModeOverlayError(floPayErr.message);\n if (options?.fallbackToFull) {\n setCurrentMode('full');\n replaceCheckoutModeQueryParam('full');\n }\n onErrorRef.current?.(floPayErr);\n emitDecline(method, floPayErr, {\n code: floPayErr.code,\n declineCode: floPayErr.declineCode,\n });\n setModeOverlayStatus('error');\n\n await Promise.allSettled([\n sleep(PROCESSING_OVERLAY_ERROR_DELAY_MS),\n options?.ensureProvidersReady ? options.ensureProvidersReady() : Promise.resolve(),\n ]);\n return false;\n } finally {\n setModeOverlayStatus(null);\n setModeOverlayError(null);\n }\n },\n [\n emitDecline,\n normalizeSavedPaymentError,\n resolvedBillingUrl,\n ],\n );\n\n useEffect(() => {\n if (typeof window === 'undefined' || paypalResumeAttempted.current) {\n return;\n }\n\n const params = new URLSearchParams(window.location.search);\n const clientSecret = params.get('payment_intent_client_secret');\n if (!clientSecret) {\n return;\n }\n\n const resumeState = readPayPalResumeState();\n if (!resumeState) {\n return;\n }\n\n paypalResumeAttempted.current = true;\n\n void (async () => {\n setModeError(null);\n setModeOverlayError(null);\n setModeOverlayStatus('processing');\n setConfirmProcessing(true);\n\n try {\n if (params.get('redirect_status') === 'failed') {\n throw Object.assign(\n new FloPayError('PayPal payment was declined. Please try again.', 'api_error'),\n { checkoutMethod: 'paypal' as const },\n );\n }\n\n const {\n flopay: resumeFlopay,\n paypalFlopay: resumePaypalFlopay,\n } = await loadSavedPaymentProviders({\n publishableKey: resumeState.publishableKey,\n paypalPublishableKey: resumeState.paypalPublishableKey,\n billingApiUrl: resolvedBillingUrl,\n locale,\n });\n\n const paypalStripe = (resumePaypalFlopay ?? resumeFlopay).getRawProvider() as import('@stripe/stripe-js').Stripe | null;\n if (!paypalStripe) {\n throw Object.assign(\n new FloPayError('PayPal is not available.', 'api_error'),\n { checkoutMethod: 'paypal' as const },\n );\n }\n\n const { paymentIntent, error } = await paypalStripe.retrievePaymentIntent(clientSecret);\n if (error) {\n throw Object.assign(\n new FloPayError(\n error.message ?? 'Failed to retrieve PayPal payment status.',\n 'api_error',\n { code: error.code },\n ),\n { checkoutMethod: 'paypal' as const },\n );\n }\n\n const resultStatus = mapPayPalIntentStatusToPaymentResult(paymentIntent?.status);\n\n if (!paymentIntent || resultStatus === 'failed') {\n throw Object.assign(\n new FloPayError('PayPal payment was not completed. Please try again.', 'api_error'),\n { checkoutMethod: 'paypal' as const },\n );\n }\n\n const paymentMethodId = typeof paymentIntent.payment_method === 'string'\n ? paymentIntent.payment_method\n : paymentIntent.payment_method?.id;\n\n // Manual-capture PayPal PIs land at `requires_capture` after PayPal\n // authorization. Backend must capture via /process, otherwise the PI\n // sits at requires_capture forever (\"Uncaptured\" in Stripe).\n let finalResultStatus: PaymentResult['status'] = resultStatus;\n if (resumeState.sessionId) {\n const resumeApi = new PaymentAPI(resolvedBillingUrl);\n const resumeSessionResult = await resumeApi.getUnifiedCheckoutSession(resumeState.sessionId);\n const resumeSession = resumeSessionResult.data.session;\n if (resumeSession && resumeSession.status !== 'complete') {\n const processResult = await processSavedPaymentForMode({\n billingApiUrl: resolvedBillingUrl,\n sessionId: resumeState.sessionId,\n session: resumeSession,\n tokenizedData: {\n id: paymentMethodId ?? paymentIntent.id,\n type: 'card',\n threeDSecureActionResultTokenId: paymentIntent.id,\n isPaypal: true,\n },\n });\n if (processResult.type !== 'success') {\n throw Object.assign(\n new FloPayError('Failed to finalize PayPal payment.', 'api_error'),\n { checkoutMethod: 'paypal' as const },\n );\n }\n // /process's result.status reflects post-capture state; the\n // pre-capture PI status mapping would otherwise leak through.\n finalResultStatus = processResult.result.status;\n }\n }\n\n if (resumeState.sessionId) markSessionRecentlyCompleted(resumeState.sessionId);\n setModeOverlayStatus('success');\n await sleep(PROCESSING_OVERLAY_SUCCESS_DELAY_MS);\n onCompleteRef.current?.({\n status: finalResultStatus,\n paymentIntentId: paymentIntent.id,\n paymentMethodId,\n checkoutMethod: 'paypal',\n });\n } catch (err) {\n const floPayErr = normalizeSavedPaymentError(err);\n const method = floPayErr.checkoutMethod ?? 'paypal';\n\n setModeError(floPayErr.message);\n setModeOverlayError(floPayErr.message);\n onErrorRef.current?.(floPayErr);\n emitDecline(method, floPayErr, {\n code: floPayErr.code,\n declineCode: floPayErr.declineCode,\n });\n setModeOverlayStatus('error');\n await sleep(PROCESSING_OVERLAY_ERROR_DELAY_MS);\n } finally {\n clearPayPalResumeState();\n clearPayPalRedirectParams();\n setModeOverlayStatus(null);\n setModeOverlayError(null);\n setConfirmProcessing(false);\n }\n })();\n }, [emitDecline, locale, normalizeSavedPaymentError, resolvedBillingUrl]);\n\n // ── Session creation dedup ──\n // Uses the module-level `sessionInflightMap` (declared near the top of this\n // file) so two FloPayCheckout instances mounted in the same page-load —\n // including React StrictMode's dev double-mount, a Suspense remount, or a\n // navigation that briefly remounts the parent — share the same in-flight\n // POST instead of each starting their own and producing duplicate sessions.\n // A per-component useRef would be reset on each remount and cannot dedupe\n // across instances.\n // Tracks whether init has already completed — prevents redundant re-runs\n // when createSessionParams is a new object ref but semantically identical.\n const initializedHashRef = useRef<string | null>(null);\n\n // ── Deterministic hash for session caching ──\n\n function hashCreateParams(params: InlineSessionDraft | undefined): string {\n // Include only a compact buyer fingerprint in the cache key. The resulting\n // sessionStorage key is hashed, but the checkout session itself is account-\n // bound on the backend; reusing it across emails/users can route payment\n // processing through the wrong persisted gateway.\n //\n // Note: `account.userId` is intentionally excluded. It is a consumer-\n // generated identifier and many consumers (e.g. funnels-next) regenerate\n // it per component mount via `crypto.randomUUID()` — including it here\n // would produce a new hash on every mount, miss the sessionStorage cache,\n // and POST a duplicate session every time. Email + country are sufficient\n // buyer-identity for cross-buyer cache safety.\n const key = JSON.stringify({\n c: params?.clientId,\n a: {\n e: params?.account?.email?.trim().toLowerCase() ?? '',\n country: params?.account?.country ?? '',\n },\n successUrl: params?.successUrl,\n cancelUrl: params?.cancelUrl,\n i: params?.items?.map(x => `${x.providerItemId}:${x.totalAmount}:${x.overrideAmount ?? ''}:${x.quantity ?? 1}`).sort(),\n s: params?.subscriptions?.map(x => `${x.providerPlanId}:${x.totalAmount}:${x.overrideAmount ?? ''}:${x.quantity ?? 1}`).sort(),\n couponCodes: params?.couponCodes,\n tagsData: params?.tagsData,\n utmMetadata: params?.utmMetadata,\n tokenizedData: params?.tokenizedData,\n m: params?.checkoutMode ?? 'full',\n });\n let h = 0;\n for (let i = 0; i < key.length; i++) {\n h = ((h << 5) - h + key.charCodeAt(i)) | 0;\n }\n return `flopay_session_${Math.abs(h).toString(36)}`;\n }\n\n // Stable hash of createSession params — used as effect dependency instead\n // of the raw object, so a new object reference with the same values\n // doesn't re-trigger the effect.\n const createSessionHash = useMemo(\n () => effectiveCreateSession ? hashCreateParams(effectiveCreateSession) : '',\n [effectiveCreateSession],\n );\n // Keep a ref to the latest params so the effect closure always sees them.\n const createSessionParamsRef = useRef(effectiveCreateSession);\n createSessionParamsRef.current = effectiveCreateSession;\n\n useEffect(() => {\n setResolvedSessionId(sessionIdProp ?? '');\n }, [sessionIdProp]);\n\n useEffect(() => {\n autoCheckoutAttempted.current = false;\n setModeError(initialErrorMessage);\n setModeOverlayError(null);\n setModeOverlayStatus(null);\n }, [createSessionHash, initialErrorMessage, sessionIdProp]);\n\n async function resolveInlineSession(\n params: InlineSessionDraft,\n cacheKey: string,\n ): Promise<{ sid: string; result: NormalizedCheckoutSession }> {\n const api = new PaymentAPI(resolvedBillingUrl);\n let sid: string | null = typeof window !== 'undefined'\n ? window.sessionStorage.getItem(cacheKey)\n : null;\n let realResult: NormalizedCheckoutSession | null = null;\n\n if (sid) {\n try {\n realResult = await api.getUnifiedCheckoutSession(sid);\n const status = realResult.data.session?.status;\n if (status === 'complete') {\n // If this session was completed inside the current page-load — the\n // marker is written synchronously in SplitCardForm the moment\n // /process succeeds, *before* the 1.2s overlay delay — return the\n // completed session as-is. Otherwise the parent's mid-flight\n // onComplete + navigation could race a re-mounted bootstrap into\n // clearing the cache and POSTing a duplicate session that would\n // then be /process'd with the same PI (the source of the\n // duplicate-subscription bug).\n if (wasSessionRecentlyCompleted(sid)) {\n return { sid, result: realResult };\n }\n // Otherwise the cached session is genuinely stale (e.g. user\n // revisits /checkout in a new page-load after a previous successful\n // checkout). Clear and create a new one as before.\n if (typeof window !== 'undefined') window.sessionStorage.removeItem(cacheKey);\n sid = null;\n realResult = null;\n }\n } catch {\n if (typeof window !== 'undefined') window.sessionStorage.removeItem(cacheKey);\n sid = null;\n }\n }\n\n if (!sid) {\n // Inject checkout analytics metadata into the session creation payload\n const paramsWithAnalytics: InlineSessionParams = {\n ...(params as InlineSessionParams),\n avsCheck: !!enableAVS,\n avsConfig: typeof enableAVS === 'object' ? enableAVS : undefined,\n checkoutType: 'embedded_checkout',\n checkoutLayout: children ? 'custom_layout' : layout === 'buttons' ? 'buttons_layout' : 'default_layout',\n };\n realResult = await api.createAndFetchSession(paramsWithAnalytics);\n sid = realResult.data.session?.id ?? '';\n if (sid && typeof window !== 'undefined') {\n window.sessionStorage.setItem(cacheKey, sid);\n }\n }\n\n return { sid: sid ?? '', result: realResult! };\n }\n\n const bootstrapInlineSession = useCallback(\n async (patch?: InlineSessionPatch) => {\n const baseParams = createSessionParamsRef.current;\n if (!baseParams) {\n throw new FloPayError('createSession is required to bootstrap checkout.', 'validation_error');\n }\n\n const mergedParams = mergeInlineSessionPatch(baseParams, patch);\n // The cache key includes a compact buyer fingerprint because backend\n // sessions are account-bound. Account, coupon, tag, UTM, or cart changes\n // should bootstrap a fresh session instead of reusing a stale gateway.\n const cacheKey = hashCreateParams(mergedParams);\n\n let promise = sessionInflightMap.get(cacheKey);\n if (!promise) {\n promise = resolveInlineSession(mergedParams, cacheKey);\n sessionInflightMap.set(cacheKey, promise);\n }\n\n let resolved: { sid: string; result: NormalizedCheckoutSession };\n try {\n resolved = await promise;\n } finally {\n // Only the inserter clears the map entry — but `delete` on a missing\n // key is a no-op so this is safe to call from every awaiter.\n sessionInflightMap.delete(cacheKey);\n }\n\n initializedHashRef.current = cacheKey;\n\n try {\n if (patch) {\n setCreateSessionPatchBaseHash(baseCreateSessionHash);\n setCreateSessionPatch((prev) => mergeInlineSessionPatches(prev, patch));\n }\n\n const { sid, result: realResult } = resolved;\n\n setUnified(realResult);\n if (realResult.data.session) {\n setSession(realResult.data.session);\n }\n if (sid) {\n setResolvedSessionId(sid);\n }\n\n const {\n publishableKey,\n paypalPublishableKey,\n } = resolveSavedPaymentPublishableKeys(realResult);\n const {\n flopay: instance,\n paypalFlopay: paypalInstance,\n } = await loadSavedPaymentProviders({\n publishableKey,\n paypalPublishableKey,\n billingApiUrl: resolvedBillingUrl,\n locale,\n });\n\n flopayRef.current = instance;\n setFloPay(instance);\n paypalFlopayRef.current = paypalInstance;\n setPaypalFloPay(paypalInstance);\n\n setIsLoading(false);\n } catch (err) {\n if (initializedHashRef.current === cacheKey) {\n initializedHashRef.current = null;\n }\n throw err;\n }\n\n return resolved;\n },\n [locale, resolvedBillingUrl],\n );\n\n const handleInlineSessionPatch = useCallback(async (patch: InlineSessionPatch) => {\n if (!hasInlineSessionPatchData(patch) || cardBootstrapPending) {\n return {\n sessionId: resolvedSessionId,\n session,\n };\n }\n\n setCardBootstrapPending(true);\n try {\n const resolved = await bootstrapInlineSession(patch);\n return {\n sessionId: resolved.sid,\n session: resolved.result.data.session ?? null,\n };\n } finally {\n setCardBootstrapPending(false);\n }\n }, [\n bootstrapInlineSession,\n cardBootstrapPending,\n resolvedSessionId,\n session,\n ]);\n\n // ── Fetch session + initialize ──\n\n useEffect(() => {\n let cancelled = false;\n setLoadError(null);\n\n // ── createSession path: render immediately, resolve in background ──\n if (createSessionHash) {\n const params = createSessionParamsRef.current!;\n setSession(buildSyntheticSession(params, checkoutModeProp));\n setCurrentMode(effectiveCreateSessionMode);\n setIsLoading(false);\n\n // Already initialized with the same params — skip the network bootstrap\n // but keep the synthetic session in sync with any mode override.\n if (initializedHashRef.current === createSessionHash) {\n return () => { cancelled = true; };\n }\n\n (async () => {\n // Skip auto-checkout when resuming from a PayPal redirect — the\n // PayPal-resume effect (above) is the canonical completer for that\n // path. Without this guard, runSavedPaymentFlow races the resume\n // effect and triggers a duplicate POST /v1/checkouts/sessions/process.\n const hasPayPalRedirectParams =\n typeof window !== 'undefined' &&\n new URLSearchParams(window.location.search).has('payment_intent');\n\n const shouldAutoProcessInlineSession =\n effectiveCreateSessionMode === 'auto' &&\n !autoCheckoutAttempted.current &&\n !hasPayPalRedirectParams;\n\n if (shouldAutoProcessInlineSession) {\n setModeError(null);\n setModeOverlayError(null);\n setModeOverlayStatus('processing');\n }\n\n try {\n const resolved = await bootstrapInlineSession();\n const resolvedSession = resolved.result.data.session ?? null;\n savedPaymentKeysRef.current = resolveSavedPaymentPublishableKeys(resolved.result);\n\n if (\n !cancelled &&\n shouldAutoProcessInlineSession &&\n resolvedSession\n ) {\n autoCheckoutAttempted.current = true;\n await runSavedPaymentFlow(resolvedSession, {\n attempt3DS: true,\n fallbackToFull: true,\n fromCreateSession: true,\n initialAutoProcessingError: resolved.result.autoProcessingError,\n initialAutoProcessingPending: resolved.result.autoProcessingPending,\n autoProcessingAttempted: resolved.result.autoProcessingAttempted,\n sessionId: resolved.sid || resolvedSession.id,\n });\n return;\n }\n\n if (!cancelled && shouldAutoProcessInlineSession) {\n setModeOverlayStatus(null);\n setModeOverlayError(null);\n }\n } catch (err) {\n if (cancelled) return;\n\n const errorCode = err instanceof FloPayError\n ? err.code\n : typeof err === 'object' && err !== null && 'code' in err\n ? (err as { code?: string }).code\n : undefined;\n\n if (\n shouldAutoProcessInlineSession &&\n errorCode === 'session_auto_completed'\n ) {\n autoCheckoutAttempted.current = true;\n setModeOverlayStatus('success');\n await sleep(PROCESSING_OVERLAY_SUCCESS_DELAY_MS);\n\n if (!cancelled) {\n onCompleteRef.current?.({ status: 'succeeded' });\n setModeOverlayStatus(null);\n setModeOverlayError(null);\n }\n return;\n }\n\n if (shouldAutoProcessInlineSession) {\n setModeOverlayStatus(null);\n setModeOverlayError(null);\n }\n\n const floPayErr = err instanceof FloPayError ? err\n : new FloPayError(err instanceof Error ? err.message : 'Failed to create session', 'api_error');\n setLoadError(floPayErr);\n }\n })();\n\n return () => { cancelled = true; };\n }\n\n // ── Existing sessionId flow ──\n setIsLoading(true);\n\n async function init() {\n try {\n const api = new PaymentAPI(resolvedBillingUrl);\n const result = await api.getUnifiedCheckoutSession(activeSessionId);\n\n if (cancelled) return;\n setUnified(result);\n\n const sess = result.data.session ?? null;\n setSession(sess);\n\n if (!sess) {\n throw new FloPayError('No session data returned', 'api_error');\n }\n\n if (sess.status === 'complete') {\n setIsLoading(false);\n onSessionCompletedRef.current?.(sess.successUrl ?? '');\n return;\n }\n\n if (sess.status === 'expired') {\n throw new FloPayError('Checkout session has expired.', 'api_error', {\n code: 'checkout_session_expired',\n });\n }\n\n const effectiveMode = checkoutModeProp ?? sess.checkoutMode ?? 'full';\n setCurrentMode(effectiveMode);\n\n const hasPayPalRedirectParams =\n typeof window !== 'undefined' &&\n new URLSearchParams(window.location.search).has('payment_intent');\n\n if (\n effectiveMode === 'auto' &&\n !autoCheckoutAttempted.current &&\n !hasPayPalRedirectParams\n ) {\n autoCheckoutAttempted.current = true;\n const stripeInitPromise = initStripe(result);\n\n try {\n await runSavedPaymentFlow(sess, {\n attempt3DS: true,\n fallbackToFull: true,\n ensureProvidersReady: () => stripeInitPromise,\n sessionId: activeSessionId || sess.id,\n });\n if (cancelled) return;\n await stripeInitPromise;\n if (!cancelled) {\n setIsLoading(false);\n }\n return;\n } catch {\n if (cancelled) return;\n await stripeInitPromise;\n if (!cancelled) setIsLoading(false);\n return;\n }\n }\n\n await initStripe(result);\n if (!cancelled) setIsLoading(false);\n } catch (err) {\n if (cancelled) return;\n const floPayErr = err instanceof FloPayError ? err\n : new FloPayError(err instanceof Error ? err.message : 'Failed to initialize checkout', 'api_error');\n setLoadError(floPayErr);\n setIsLoading(false);\n }\n }\n\n async function initStripe(result: NormalizedCheckoutSession) {\n const {\n publishableKey,\n paypalPublishableKey,\n } = resolveSavedPaymentPublishableKeys(result);\n savedPaymentKeysRef.current = {\n publishableKey,\n paypalPublishableKey,\n };\n const {\n flopay: instance,\n paypalFlopay: paypalInstance,\n } = await loadSavedPaymentProviders({\n publishableKey,\n paypalPublishableKey,\n billingApiUrl: resolvedBillingUrl,\n locale,\n });\n\n flopayRef.current = instance;\n setFloPay(instance);\n paypalFlopayRef.current = paypalInstance;\n setPaypalFloPay(paypalInstance);\n }\n\n init();\n return () => {\n cancelled = true;\n };\n // Only re-run when the session/config identity changes — NOT when callbacks change.\n // Callbacks are accessed via refs (onCompleteRef, onSessionCompletedRef).\n // `createSessionHash` is a stable string derived from createSessionParams,\n // so a new object reference with the same values won't re-trigger.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [\n bootstrapInlineSession,\n checkoutModeProp,\n createSessionHash,\n effectiveCreateSessionMode,\n initSessionDependency,\n runSavedPaymentFlow,\n ]);\n\n // ── Confirm mode handler ──\n\n const handleConfirmCheckout = useCallback(async () => {\n if (confirmProcessing || !session) return;\n setConfirmProcessing(true);\n setModeError(null);\n\n try {\n await runSavedPaymentFlow(session, {\n fallbackToFull: true,\n sessionId: activeSessionId || session.id,\n });\n } finally {\n setConfirmProcessing(false);\n }\n }, [activeSessionId, confirmProcessing, runSavedPaymentFlow, session]);\n\n // Provider options from session data\n const providerOptions = useMemo(() => {\n if (!unified || !session) return undefined;\n\n const opts: {\n appearance?: FloPayAppearance;\n paymentMethodCreation: 'manual';\n billingApiUrl: string;\n clientSecret?: string;\n amount?: number;\n currency?: string;\n } = {\n appearance,\n paymentMethodCreation: 'manual',\n billingApiUrl: resolvedBillingUrl,\n };\n\n if (\n unified.provider === 'stripe' &&\n unified.data.stripe?.clientSecret\n ) {\n opts.clientSecret = unified.data.stripe.clientSecret;\n } else {\n // Use display total (respects hideItems logic) instead of raw session.amount\n const displayTotal = buildCheckoutDisplayData(session).total;\n opts.amount = Math.round(displayTotal * 100) || session.amount;\n opts.currency = session.currency?.toLowerCase();\n }\n\n return opts;\n }, [unified, session, appearance, resolvedBillingUrl]);\n\n const shouldHandleInlineSessionPatch = Boolean(\n createSessionParams &&\n !children &&\n layout === 'buttons' &&\n onBeforeButtonClick &&\n effectiveCreateSessionMode === 'full',\n );\n\n // Checkout context\n const checkoutValue = useMemo(\n () => ({\n session,\n loading: isLoading,\n error: loadError,\n checkoutMode: currentMode,\n inlineSessionDraft: effectiveCreateSession,\n applyInlineSessionPatch: shouldHandleInlineSessionPatch\n ? handleInlineSessionPatch\n : undefined,\n inlineSessionPatchProcessing: cardBootstrapPending,\n }),\n [\n session,\n isLoading,\n loadError,\n currentMode,\n effectiveCreateSession,\n shouldHandleInlineSessionPatch,\n handleInlineSessionPatch,\n cardBootstrapPending,\n ],\n );\n const shouldShowInterimButtons =\n Boolean(createSessionParams) &&\n layout === 'buttons' &&\n (!flopay || !providerOptions);\n const modeOverlay = modeOverlayStatus\n ? (\n <ProcessingOverlay\n status={modeOverlayStatus}\n errorMessage={modeOverlayError}\n />\n )\n : null;\n\n // ── Loading state ──\n if (isLoading) {\n if (loadingNode) {\n return (\n <>\n {loadingNode}\n {modeOverlay}\n </>\n );\n }\n\n // Buttons layout: show button-shaped skeletons\n if (layout === 'buttons') {\n const skeletonBar = (h: number) => (\n <div style={{\n height: h, borderRadius: 8, background: '#e5e7eb',\n animation: 'flopay-loading-pulse 1.5s ease-in-out infinite',\n }} />\n );\n return (\n <>\n <div style={{ display: 'flex', flexDirection: 'column', gap: '0.5rem' }}>\n {showPayPal && skeletonBar(DEFAULT_BUTTONS_LAYOUT_BUTTON_HEIGHT)}\n {(showApplePay || showGooglePay) && skeletonBar(DEFAULT_BUTTONS_LAYOUT_BUTTON_HEIGHT)}\n {skeletonBar(DEFAULT_BUTTONS_LAYOUT_BUTTON_HEIGHT)}\n <style>{`@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }`}</style>\n </div>\n {modeOverlay}\n </>\n );\n }\n\n // Default layout: centered spinner\n return (\n <>\n <div style={{ display: 'flex', justifyContent: 'center', padding: 32 }}>\n <div style={{\n width: 24, height: 24,\n border: '2px solid #e5e7eb', borderTopColor: '#6b7280',\n borderRadius: '50%', animation: 'spin 0.6s linear infinite',\n }} />\n <style>{`@keyframes spin { to { transform: rotate(360deg); } }`}</style>\n </div>\n {modeOverlay}\n </>\n );\n }\n\n // ── Error state ──\n if (loadError) {\n if (errorNode) {\n return (\n <CheckoutContext.Provider value={checkoutValue}>\n {errorNode(loadError)}\n </CheckoutContext.Provider>\n );\n }\n return (\n <CheckoutContext.Provider value={checkoutValue}>\n <div\n style={{\n padding: 24,\n textAlign: 'center',\n color: '#dc2626',\n fontSize: 14,\n }}\n >\n {loadError.message}\n </div>\n </CheckoutContext.Provider>\n );\n }\n\n // When using createSession + buttons layout, render an interim buttons view\n // while Stripe initializes in the background. The Credit/Debit Card button\n // is fully interactive (expands card form); PayPal/wallets show as skeletons.\n // Once flopay loads, the real SplitCardForm replaces this seamlessly.\n if (shouldShowInterimButtons) {\n return (\n <>\n <CheckoutContext.Provider value={checkoutValue}>\n <InterimButtonsView\n onButtonClick={onButtonClick}\n showPayPal={showPayPal}\n showApplePay={showApplePay}\n showGooglePay={showGooglePay}\n buttonsTheme={buttonsTheme}\n buttonsStyles={buttonsStyles}\n cardButtonContent={cardButtonContent}\n cardBackButtonContent={cardBackButtonContent}\n cardTitleContent={cardTitleContent}\n />\n </CheckoutContext.Provider>\n {modeOverlay}\n </>\n );\n }\n\n if (!flopay || !providerOptions) {\n return <>{modeOverlay}</>;\n }\n\n // ── Confirm mode ──\n if (currentMode === 'confirm') {\n return (\n <>\n <CheckoutContext.Provider value={checkoutValue}>\n <FloPayProvider flopay={flopay} paypalFlopay={paypalFlopay} options={providerOptions}>\n <div className={className}>\n {modeError && (\n <div\n style={{\n color: '#dc2626',\n fontSize: '0.875rem',\n marginBottom: '0.75rem',\n textAlign: 'center',\n }}\n >\n {modeError}\n </div>\n )}\n {renderConfirmButton ? (\n renderConfirmButton({\n onConfirm: handleConfirmCheckout,\n isProcessing: confirmProcessing,\n })\n ) : (\n <button\n type=\"button\"\n onClick={handleConfirmCheckout}\n disabled={confirmProcessing}\n style={{\n width: '100%',\n padding: '0.875rem',\n backgroundColor: '#4A49FF',\n color: 'white',\n border: 'none',\n borderRadius: '8px',\n fontSize: '1rem',\n fontWeight: 600,\n cursor: confirmProcessing ? 'not-allowed' : 'pointer',\n opacity: confirmProcessing ? 0.6 : 1,\n }}\n >\n {confirmProcessing\n ? 'Processing...'\n : confirmLabel ?? 'Confirm Purchase'}\n </button>\n )}\n </div>\n </FloPayProvider>\n </CheckoutContext.Provider>\n {modeOverlay}\n </>\n );\n }\n\n // ── Full mode (default / fallback) ──\n return (\n <>\n <CheckoutContext.Provider value={checkoutValue}>\n <FloPayProvider flopay={flopay} paypalFlopay={paypalFlopay} options={providerOptions}>\n {children ? (\n <>\n {modeError && (\n <div\n style={{\n padding: '0.75rem 1rem',\n marginBottom: '0.75rem',\n backgroundColor: '#FEF3C7',\n border: '1px solid #F59E0B',\n borderRadius: '8px',\n color: '#92400E',\n fontSize: '0.875rem',\n }}\n >\n {modeError}\n </div>\n )}\n <SessionInjector\n sessionId={activeSessionId}\n billingApiUrl={resolvedBillingUrl}\n session={session}\n >\n {children}\n </SessionInjector>\n </>\n ) : (\n <SplitCardForm\n sessionId={activeSessionId}\n email={session?.customer?.email}\n userId={session?.customer?.id}\n firstName={session?.customer?.firstName}\n lastName={session?.customer?.lastName}\n totalAmount={session ? Math.round(buildCheckoutDisplayData(session).total * 100) : 0}\n currency={session?.currency?.toLowerCase() ?? 'usd'}\n onComplete={onComplete}\n onError={onError}\n onDecline={onDecline}\n error={modeError}\n onErrorChange={setModeError}\n onFullNameChange={onFullNameChange}\n showPayPal={showPayPal}\n showApplePay={showApplePay}\n showGooglePay={showGooglePay}\n layout={layout}\n buttonsTheme={buttonsTheme}\n buttonsStyles={buttonsStyles}\n cardButtonContent={cardButtonContent}\n cardBackButtonContent={cardBackButtonContent}\n cardTitleContent={cardTitleContent}\n showSecurityFooter={showSecurityFooter}\n onButtonClick={onButtonClick}\n onBeforeButtonClick={onBeforeButtonClick}\n enableAVS={enableAVS}\n avsLayout={avsLayout}\n country={session?.customer?.country}\n city={session?.customer?.city}\n state={session?.customer?.state}\n onCountryChange={onCountryChange}\n onZipChange={onZipChange}\n avsCheck={!!enableAVS}\n checkoutType={createSessionParams ? 'embedded_checkout' : 'standard_checkout'}\n checkoutLayout={children ? 'custom_layout' : layout === 'buttons' ? 'buttons_layout' : 'default_layout'}\n submitLabel={submitLabel}\n className={className}\n />\n )}\n </FloPayProvider>\n </CheckoutContext.Provider>\n {modeOverlay}\n </>\n );\n}\n\n/**\n * Auto-injects session props into child form components.\n * Explicit props on children take precedence over injected values.\n */\nfunction SessionInjector({\n sessionId,\n billingApiUrl,\n session,\n children,\n}: {\n sessionId: string;\n billingApiUrl: string;\n session: CheckoutSession | null;\n children: React.ReactNode;\n}) {\n return (\n <>\n {React.Children.map(children, (child) => {\n if (!React.isValidElement(child)) return child;\n\n const existing = child.props as Record<string, unknown>;\n const injected: Record<string, unknown> = {};\n\n if (!existing.sessionId) injected.sessionId = sessionId;\n if (!existing.billingApiUrl) injected.billingApiUrl = billingApiUrl;\n\n if (session?.customer) {\n if (!existing.email) injected.email = session.customer.email;\n if (!existing.userId) injected.userId = session.customer.id;\n if (!existing.firstName)\n injected.firstName = session.customer.firstName;\n if (!existing.lastName)\n injected.lastName = session.customer.lastName;\n }\n\n if (Object.keys(injected).length === 0) return child;\n return React.cloneElement(child, injected);\n })}\n </>\n );\n}\n\n/**\n * Interim buttons view rendered while Stripe initializes in the background.\n * Shows skeleton bars for PayPal/wallets and a fully interactive Credit/Debit Card button.\n */\nfunction InterimButtonsView({\n onButtonClick,\n onCardButtonClick,\n cardLoading = false,\n cardOpen,\n errorMessage,\n showPayPal,\n showApplePay,\n showGooglePay,\n buttonsTheme,\n buttonsStyles: stylesOverride,\n cardButtonContent,\n cardBackButtonContent,\n cardTitleContent,\n}: {\n onButtonClick?: (method: CheckoutButtonMethod) => void;\n onCardButtonClick?: () => void | Promise<void>;\n cardLoading?: boolean;\n cardOpen?: boolean;\n errorMessage?: string | null;\n showPayPal: boolean;\n showApplePay: boolean;\n showGooglePay: boolean;\n buttonsTheme?: ButtonsLayoutTheme;\n buttonsStyles?: ButtonsLayoutStyles;\n cardButtonContent?: React.ReactNode;\n cardBackButtonContent?: React.ReactNode;\n cardTitleContent?: React.ReactNode;\n}) {\n const [showCardForm, setShowCardForm] = useState(false);\n const isCardOpenControlled = typeof cardOpen === 'boolean';\n\n useEffect(() => {\n if (isCardOpenControlled) {\n setShowCardForm(cardOpen);\n }\n }, [cardOpen, isCardOpenControlled]);\n\n const bStyles = useMemo<ButtonsLayoutStyles>(() => {\n const base = resolveButtonsLayoutTheme(buttonsTheme);\n if (!stylesOverride) return base;\n return {\n ...base,\n ...stylesOverride,\n cardButton: { ...base.cardButton, ...stylesOverride.cardButton },\n cardFormContainer: { ...base.cardFormContainer, ...stylesOverride.cardFormContainer },\n backButton: { ...base.backButton, ...stylesOverride.backButton },\n backButtonIcon: { ...base.backButtonIcon, ...stylesOverride.backButtonIcon },\n submitButton: { ...base.submitButton, ...stylesOverride.submitButton },\n title: { ...base.title, ...stylesOverride.title },\n };\n }, [buttonsTheme, stylesOverride]);\n\n const skeleton = (h: number) => (\n <div style={{\n height: h, borderRadius: 8, background: '#e5e7eb',\n animation: 'flopay-interim-pulse 1.5s ease-in-out infinite',\n }} />\n );\n const cardButtonSizing = cardButtonContent === undefined\n ? { boxSizing: 'border-box' as const, height: DEFAULT_BUTTONS_LAYOUT_BUTTON_HEIGHT, padding: '0 1rem' }\n : { padding: '0.9rem 1rem' };\n\n if (showCardForm) {\n // Show a card form placeholder with back button — real form takes over when Stripe loads\n const inputBorder = bStyles.cardInputBorder ?? '#e5e7eb';\n const inputBg = bStyles.cardInputBackground ?? 'white';\n const hideBackButtonLabel = isEmptySlotContent(cardBackButtonContent);\n const hideTitle = isEmptySlotContent(cardTitleContent);\n return (\n <div style={{\n backgroundColor: (bStyles.cardFormContainer?.backgroundColor as string) ?? 'white',\n borderRadius: '8px',\n animation: 'flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both',\n overflow: 'hidden',\n ...bStyles.cardFormContainer as React.CSSProperties,\n }}>\n <div style={{ display: 'flex', alignItems: 'center', padding: '0.75rem 0 0.625rem' }}>\n <button\n type=\"button\"\n onClick={() => {\n if (!isCardOpenControlled) {\n setShowCardForm(false);\n }\n }}\n aria-label=\"Back to payment methods\"\n disabled={isCardOpenControlled || cardLoading}\n style={{\n display: 'inline-flex', alignItems: 'center', gap: hideBackButtonLabel ? 0 : '0.5rem',\n background: 'none', border: 'none',\n color: '#4b5563', fontSize: '0.85rem', fontWeight: 500,\n padding: 0, flexShrink: 0, opacity: isCardOpenControlled || cardLoading ? 0.6 : 1,\n cursor: isCardOpenControlled || cardLoading ? 'not-allowed' : 'pointer',\n ...bStyles.backButton as React.CSSProperties,\n }}\n >\n <span style={{\n display: 'inline-flex', alignItems: 'center', justifyContent: 'center',\n width: 28, height: 28, borderRadius: '50%',\n backgroundColor: '#f3f4f6',\n ...bStyles.backButtonIcon as React.CSSProperties,\n }}>\n <svg width=\"14\" height=\"14\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2.5\" strokeLinecap=\"round\" strokeLinejoin=\"round\">\n <path d=\"M15 18l-6-6 6-6\" />\n </svg>\n </span>\n <BackButtonContentSlot content={cardBackButtonContent} />\n </button>\n {hideTitle ? (\n <div style={{ flex: 1 }} />\n ) : (\n <div style={{\n flex: 1, textAlign: 'center', fontWeight: 600, fontSize: '1.05rem',\n color: '#262833', paddingRight: 80,\n ...bStyles.title as React.CSSProperties,\n }}>\n <TitleContentSlot content={cardTitleContent} />\n </div>\n )}\n </div>\n {/* Skeleton card fields */}\n <div style={{ backgroundColor: inputBg, border: `1px solid ${inputBorder}`, borderTopLeftRadius: 8, borderTopRightRadius: 8, padding: 12, height: 45 }}>\n <div style={{ width: '60%', height: 14, borderRadius: 4, background: '#e5e7eb', animation: 'flopay-interim-pulse 1.5s ease-in-out infinite' }} />\n </div>\n <div style={{ display: 'flex' }}>\n <div style={{ flex: 1, backgroundColor: inputBg, border: `1px solid ${inputBorder}`, borderTop: 'none', borderRight: 'none', borderBottomLeftRadius: 8, padding: 12, height: 45 }}>\n <div style={{ width: '50%', height: 14, borderRadius: 4, background: '#e5e7eb', animation: 'flopay-interim-pulse 1.5s ease-in-out infinite' }} />\n </div>\n <div style={{ flex: 1, backgroundColor: inputBg, border: `1px solid ${inputBorder}`, borderTop: 'none', borderBottomRightRadius: 8, padding: 12, height: 45 }}>\n <div style={{ width: '40%', height: 14, borderRadius: 4, background: '#e5e7eb', animation: 'flopay-interim-pulse 1.5s ease-in-out infinite' }} />\n </div>\n </div>\n <div style={{ backgroundColor: inputBg, border: `1px solid ${inputBorder}`, borderRadius: 8, marginTop: 8, padding: 12, height: 45 }}>\n <div style={{ width: '45%', height: 14, borderRadius: 4, background: '#e5e7eb', animation: 'flopay-interim-pulse 1.5s ease-in-out infinite' }} />\n </div>\n <div style={{\n height: 50, borderRadius: 8, marginTop: 16, background: '#c8c8ff',\n animation: 'flopay-interim-pulse 1.5s ease-in-out infinite',\n ...bStyles.submitButton as React.CSSProperties,\n opacity: 0.5,\n }} />\n <style>{`\n @keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }\n @keyframes flopay-interim-expand {\n 0% { opacity: 0; max-height: 0; transform: translateY(-12px); }\n 40% { opacity: 1; }\n 100% { opacity: 1; max-height: 600px; transform: translateY(0); }\n }\n `}</style>\n </div>\n );\n }\n\n return (\n <div style={{ display: 'flex', flexDirection: 'column', gap: '0.5rem' }}>\n {showPayPal && skeleton(DEFAULT_BUTTONS_LAYOUT_BUTTON_HEIGHT)}\n {(showApplePay || showGooglePay) && skeleton(DEFAULT_BUTTONS_LAYOUT_BUTTON_HEIGHT)}\n <button\n type=\"button\"\n onClick={async () => {\n if (cardLoading) return;\n if (onCardButtonClick) {\n await onCardButtonClick();\n return;\n }\n onButtonClick?.('card');\n setShowCardForm(true);\n }}\n disabled={cardLoading}\n style={{\n width: '100%',\n ...cardButtonSizing,\n backgroundColor: 'white', color: '#262833',\n border: '1px solid #d1d5db', borderRadius: '8px',\n fontSize: bStyles.cardButtonFontSize ?? '0.95rem', fontWeight: 600,\n cursor: cardLoading ? 'not-allowed' : 'pointer', display: 'flex',\n alignItems: 'center', justifyContent: 'center', gap: '0.625rem',\n boxShadow: '0 1px 2px rgba(0,0,0,0.04)',\n transition: 'transform 0.1s',\n position: 'relative',\n opacity: cardLoading ? 0.6 : 1,\n ...bStyles.cardButton as React.CSSProperties,\n }}\n onMouseDown={(e) => { e.currentTarget.style.transform = 'scale(0.985)'; }}\n onMouseUp={(e) => { e.currentTarget.style.transform = 'scale(1)'; }}\n >\n <CardButtonContentSlot content={cardButtonContent} />\n </button>\n {errorMessage && (\n <div style={{\n margin: '0.25rem 0', padding: '0.625rem 0.875rem',\n background: '#FEF2F2', border: '1px solid #FECACA', borderRadius: '8px',\n color: '#991B1B', fontSize: '0.85rem', fontWeight: 600,\n display: 'flex', alignItems: 'center', gap: '0.5rem',\n ...(bStyles.errorBanner as React.CSSProperties | undefined),\n }}>\n <svg width=\"16\" height=\"16\" viewBox=\"0 0 24 24\" fill=\"none\" style={{ flexShrink: 0 }}>\n <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\" />\n </svg>\n {errorMessage}\n </div>\n )}\n <style>{`@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }`}</style>\n </div>\n );\n}\n","import React from 'react';\n\nexport function DefaultCardButtonContent(): React.ReactElement {\n return (\n <>\n <svg\n width=\"20\"\n height=\"20\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"1.5\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n aria-hidden=\"true\"\n >\n <rect width=\"20\" height=\"14\" x=\"2\" y=\"5\" rx=\"2\" />\n <line x1=\"2\" x2=\"22\" y1=\"10\" y2=\"10\" />\n </svg>\n Credit / Debit Card\n <svg\n width=\"16\"\n height=\"16\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"#9ca3af\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n style={{ position: 'absolute', right: '1rem' }}\n aria-hidden=\"true\"\n >\n <path d=\"M9 18l6-6-6-6\" />\n </svg>\n </>\n );\n}\n\nexport function DefaultBackButtonContent(): React.ReactElement {\n return <>Go back</>;\n}\n\nexport function DefaultTitleContent(): React.ReactElement {\n return <>Secure card checkout</>;\n}\n\nexport function isEmptySlotContent(content: React.ReactNode | undefined): boolean {\n return content !== undefined && (content === '' || content === null || content === false);\n}\n\nexport function CardButtonContentSlot({\n content,\n}: {\n content?: React.ReactNode;\n}): React.ReactElement {\n return <>{content === undefined ? <DefaultCardButtonContent /> : content}</>;\n}\n\nexport function BackButtonContentSlot({\n content,\n}: {\n content?: React.ReactNode;\n}): React.ReactElement {\n return <>{content === undefined ? <DefaultBackButtonContent /> : content}</>;\n}\n\nexport function TitleContentSlot({\n content,\n}: {\n content?: React.ReactNode;\n}): React.ReactElement {\n return <>{content === undefined ? <DefaultTitleContent /> : content}</>;\n}\n","import React, { useEffect, useRef, useContext } from 'react';\nimport type { ElementType, ElementChangeEvent, ElementOptions, MountedElement } from '@flopay/shared';\nimport { FloPayContext } from './context.js';\n\n/** Common props shared by all element components. */\nexport interface ElementComponentProps {\n /** Additional CSS class for the wrapper div. */\n className?: string;\n /** Element id attribute for the wrapper div. */\n id?: string;\n /** Inline styles for the wrapper div. */\n style?: React.CSSProperties;\n /** Options forwarded to the underlying element. */\n options?: Partial<ElementOptions>;\n /** Fired when the element's value changes. */\n onChange?: (event: ElementChangeEvent) => void;\n /** Fired when the element is fully rendered and ready. */\n onReady?: () => void;\n /** Fired when the element gains focus. */\n onFocus?: () => void;\n /** Fired when the element loses focus. */\n onBlur?: () => void;\n /** Fired when the Escape key is pressed inside the element. */\n onEscape?: () => void;\n}\n\n/**\n * Generic element component factory.\n *\n * Each element component:\n * 1. Gets the Elements instance from context\n * 2. Creates the appropriate element type\n * 3. Mounts it to a ref'd container div\n * 4. Forwards events as props\n * 5. Cleans up on unmount\n *\n * TODO: In a future phase, each element will render inside an iframe\n * for PCI DSS SAQ-A compliance. For now, they wrap the provider's\n * elements directly.\n */\nfunction createElementComponent(\n elementType: ElementType,\n displayName: string,\n): React.FC<ElementComponentProps> {\n function ElementComponent({\n className,\n id,\n style,\n options,\n onChange,\n onReady,\n onFocus,\n onBlur,\n onEscape,\n }: ElementComponentProps) {\n const containerRef = useRef<HTMLDivElement>(null);\n const elementRef = useRef<MountedElement | null>(null);\n const { elements } = useContext(FloPayContext);\n\n useEffect(() => {\n if (!elements || !containerRef.current) return;\n\n let mounted = true;\n\n (async () => {\n // Reuse existing element if Stripe already created one of this type\n // (handles React Strict Mode double-mount).\n let element = elements.getElement(elementType);\n if (!element) {\n element = await elements.create(elementType, options);\n }\n\n if (!mounted || !containerRef.current) {\n return;\n }\n\n element.mount(containerRef.current);\n elementRef.current = element;\n\n if (onChange) element.on('change', onChange as (...args: unknown[]) => void);\n if (onReady) element.on('ready', onReady as (...args: unknown[]) => void);\n if (onFocus) element.on('focus', onFocus as (...args: unknown[]) => void);\n if (onBlur) element.on('blur', onBlur as (...args: unknown[]) => void);\n if (onEscape) element.on('escape', onEscape as (...args: unknown[]) => void);\n })();\n\n return () => {\n mounted = false;\n // Unmount only — don't destroy. Stripe Elements tracks elements\n // internally; destroying prevents reuse on Strict Mode remount.\n // Guard with try/catch: the element may already be destroyed if\n // the parent provider recreated the Elements group (e.g. on\n // appearance change).\n if (elementRef.current) {\n try {\n elementRef.current.unmount();\n } catch {\n // Element already destroyed — safe to ignore\n }\n elementRef.current = null;\n }\n };\n }, [elements]);\n\n return <div ref={containerRef} className={className} id={id} style={style} />;\n }\n\n ElementComponent.displayName = displayName;\n return ElementComponent;\n}\n\n/**\n * Renders the unified Payment Element — a single component that accepts\n * cards, wallets, and other payment methods.\n *\n * TODO: Will render inside an iframe for PCI compliance in a future phase.\n */\nexport const PaymentElement = createElementComponent('payment', 'PaymentElement');\n\n/**\n * Renders a combined card input (number + expiry + CVC).\n *\n * TODO: Will render inside an iframe for PCI compliance in a future phase.\n */\nexport const CardElement = createElementComponent('card', 'CardElement');\n\n/**\n * Renders a card number input field.\n *\n * TODO: Will render inside an iframe for PCI compliance in a future phase.\n */\nexport const CardNumberElement = createElementComponent('cardNumber', 'CardNumberElement');\n\n/**\n * Renders a card expiry input field.\n *\n * TODO: Will render inside an iframe for PCI compliance in a future phase.\n */\nexport const CardExpiryElement = createElementComponent('cardExpiry', 'CardExpiryElement');\n\n/**\n * Renders a card CVC input field.\n *\n * TODO: Will render inside an iframe for PCI compliance in a future phase.\n */\nexport const CardCvcElement = createElementComponent('cardCvc', 'CardCvcElement');\n\n/**\n * Renders an address input element.\n */\nexport const AddressElement = createElementComponent('address', 'AddressElement');\n","import {\n CardCvcElement,\n CardExpiryElement,\n CardNumberElement,\n} from './elements.js';\nimport {\n ExpressCheckoutElement,\n Elements as StripeElements,\n useElements as useStripeElements,\n useStripe as useStripeRaw,\n} from '@stripe/react-stripe-js';\nimport type {\n BeforeButtonClickEvent,\n CheckoutButtonMethod,\n DeclineEvent,\n InlineSessionPatch,\n PaymentResult,\n TokenizedBody,\n ButtonsLayoutStyles,\n AVSFieldConfig,\n} from '@flopay/shared';\nimport {\n resolveButtonsLayoutTheme,\n getPostalCodeLabel,\n getStateLabel,\n getStateOptions,\n COUNTRY_OPTIONS,\n resolveAVSConfig,\n isAVSFieldVisible,\n getStateFromPostalCode,\n} from '@flopay/shared';\nimport { PaymentAPI } from '@flopay/js';\nimport React, { forwardRef, useCallback, useContext, useEffect, useImperativeHandle, useMemo, useRef, useState } from 'react';\nimport type {\n Stripe,\n StripeExpressCheckoutElementConfirmEvent,\n StripeExpressCheckoutElementReadyEvent,\n} from '@stripe/stripe-js';\nimport { useBillingApiUrl, useElements, useFloPay, usePayPalFloPay } from './hooks.js';\nimport { CheckoutContext } from './context.js';\nimport {\n BackButtonContentSlot,\n CardButtonContentSlot,\n TitleContentSlot,\n isEmptySlotContent,\n} from './card-button-content.js';\nimport {\n PROCESSING_OVERLAY_ERROR_DELAY_MS,\n PROCESSING_OVERLAY_SUCCESS_DELAY_MS,\n ProcessingOverlay,\n type OverlayStatus,\n} from './processing-overlay.js';\nimport {\n buildDeclineEvent,\n buildFloPayApiErrorFromResponse,\n mergeAccountPatch,\n resolvePaymentIntentPaymentMethodId,\n resolveTokenizedPaymentMethodId,\n retrievePaymentIntentFromProvider,\n} from './checkout-utils.js';\nimport { markSessionRecentlyCompleted } from './recent-completion.js';\nimport { isInAppBrowser } from './in-app-browser.js';\n\nimport { FloPayError } from '@flopay/shared';\n\n/** localStorage key for persisting wallet payment state across redirects. */\nconst WALLET_RESUME_KEY = 'flopay_wallet_resume';\n\ntype MaybePromise<T> = T | Promise<T>;\n\n// ─── Global keyframes (always present — not gated behind overlay render) ────\n\nconst FLOPAY_KEYFRAMES = `\n@keyframes flopay-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }\n@keyframes flopay-fade-in { 0% { opacity: 0; } 100% { opacity: 1; } }\n@keyframes flopay-buttons-enter {\n 0% { opacity: 0; transform: translateX(-16px) scale(0.97); }\n 100% { opacity: 1; transform: translateX(0) scale(1); }\n}\n@keyframes flopay-buttons-exit {\n 0% { opacity: 1; transform: translateX(0) scale(1); }\n 100% { opacity: 0; transform: translateX(-16px) scale(0.97); }\n}\n@keyframes flopay-card-enter {\n 0% { opacity: 0; transform: translateX(16px) scale(0.97); }\n 100% { opacity: 1; transform: translateX(0) scale(1); }\n}\n@keyframes flopay-card-exit {\n 0% { opacity: 1; transform: translateX(0) scale(1); }\n 100% { opacity: 0; transform: translateX(16px) scale(0.97); }\n}\n`;\n\nconst DEFAULT_BUTTONS_LAYOUT_BUTTON_HEIGHT = 44;\n\ntype TokenizedBodyOverrides = {\n accountPatch?: InlineSessionPatch['account'];\n completionPaymentMethodId?: string;\n sessionId?: string;\n};\n\ntype InternalTokenizedBodyHandler = (\n body: TokenizedBody,\n overrides?: TokenizedBodyOverrides,\n) => void;\n\ntype BeforeButtonClickPatchResult = {\n error: FloPayError | null;\n sessionId?: string;\n};\n\ntype BeforeButtonClickResult = {\n proceed: boolean;\n accountPatch?: InlineSessionPatch['account'];\n sessionId?: string;\n};\n\ntype RunBeforeButtonClick = (method: CheckoutButtonMethod) => Promise<BeforeButtonClickResult>;\n\nfunction getButtonMethodLabel(method: CheckoutButtonMethod): string {\n switch (method) {\n case 'paypal': return 'PayPal';\n case 'apple_pay': return 'Apple Pay';\n case 'google_pay': return 'Google Pay';\n default: return 'Card';\n }\n}\n\nfunction normalizeBeforeButtonClickError(\n method: CheckoutButtonMethod,\n err: unknown,\n): FloPayError {\n return err instanceof FloPayError\n ? err\n : new FloPayError(\n err instanceof Error ? err.message : `${getButtonMethodLabel(method)} before-click hook failed.`,\n 'validation_error',\n );\n}\n\nfunction FloPayKeyframes() {\n return <style>{FLOPAY_KEYFRAMES}</style>;\n}\n\nfunction toCssSize(value: string | number | undefined): string | undefined {\n if (typeof value === 'number') return `${value}px`;\n return value;\n}\n\nfunction toCssWeight(value: string | number | undefined): string | number | undefined {\n if (typeof value === 'number' || typeof value === 'string') return value;\n return undefined;\n}\n\n/**\n * Express-checkout element load states.\n *\n * - `loading`: initial — waiting for ExpressCheckoutElement's `ready` event.\n * - `ready`: at least one of the requested methods is available on this\n * device. Element renders.\n * - `unavailable`: the element initialized fine but `availablePaymentMethods`\n * reported none of the requested methods. The row collapses so buyers can\n * continue with another payment method.\n * - `load_error`: Stripe's `onLoadError` fired — the element couldn't\n * initialize at all (script blocked, network failure).\n */\ntype ExpressCheckoutLoadState = 'loading' | 'ready' | 'unavailable' | 'load_error';\n\nfunction resolveExpressCheckoutLoadState(\n event: StripeExpressCheckoutElementReadyEvent,\n methods: Array<'paypal' | 'applePay' | 'googlePay'>,\n): ExpressCheckoutLoadState {\n const available = event.availablePaymentMethods;\n if (!available) return 'unavailable';\n\n return methods.some((method) => available[method]) ? 'ready' : 'unavailable';\n}\n\nfunction ExpressCheckoutReadySwap({\n state,\n placeholderTestId,\n children,\n}: {\n state: ExpressCheckoutLoadState;\n placeholderTestId?: string;\n children: React.ReactNode;\n}) {\n if (state === 'unavailable' || state === 'load_error') return null;\n\n return (\n <div style={{ position: 'relative', minHeight: 44 }}>\n <div\n data-testid={placeholderTestId}\n aria-hidden={state === 'ready'}\n style={{\n position: 'absolute',\n inset: 0,\n height: 44,\n borderRadius: 8,\n background: '#e5e7eb',\n animation: state === 'ready' ? undefined : 'flopay-pulse 1.5s ease-in-out infinite',\n opacity: state === 'ready' ? 0 : 1,\n transform: state === 'ready' ? 'scale(0.985)' : 'scale(1)',\n transition: 'opacity 140ms ease-out, transform 140ms ease-out',\n pointerEvents: 'none',\n }}\n />\n <div\n style={{\n minHeight: 44,\n opacity: state === 'ready' ? 1 : 0,\n transform: state === 'ready' ? 'translateY(0)' : 'translateY(2px)',\n transition: 'opacity 140ms ease-out, transform 140ms ease-out',\n pointerEvents: state === 'ready' ? 'auto' : 'none',\n }}\n >\n {children}\n </div>\n </div>\n );\n}\n\nfunction isExpressCheckoutRowVisible(state: ExpressCheckoutLoadState): boolean {\n return state !== 'unavailable' && state !== 'load_error';\n}\n\n/** Methods exposed via ref for external 3DS handling. */\nexport interface SplitCardFormRef {\n handleNextAction: (clientSecret: string) => Promise<void>;\n}\n\n/** Props for the `SplitCardForm` component. */\nexport interface SplitCardFormProps {\n /** The checkout session ID (UUID from billing API). */\n sessionId: string;\n /** Billing API base URL. Optional — defaults to the value from FloPayProvider or the shared constant. */\n billingApiUrl?: string;\n /** User's email (required for creating payment intents). */\n email?: string;\n /** User ID (required for processing payments). */\n userId?: string;\n /** Called when the full payment flow completes successfully. */\n onComplete?: (result: PaymentResult) => void;\n /** Called when a payment error occurs. */\n onError?: (error: FloPayError) => void;\n /** Called when a payment is declined or the authentication step fails. */\n onDecline?: (decline: DeclineEvent) => void;\n /**\n * **Override**: If provided, delegates backend submission to the caller.\n * When omitted, processes internally (calls processPayment + handles 3DS).\n */\n onTokenizedBody?: (tokenizedBody: TokenizedBody) => void;\n /** First name for billing. */\n firstName?: string;\n /** Last name for billing. */\n lastName?: string;\n /** Checkout version for A/B tracking. */\n chv?: string;\n /** Label for the submit button. */\n submitLabel?: string;\n /** Additional CSS class for the form wrapper. */\n className?: string;\n /** Custom children (overrides default submit button). */\n children?: React.ReactNode;\n /** External processing state. */\n isProcessing?: boolean;\n /** External error message. */\n error?: string | null;\n /** Called when internal error state changes. */\n onErrorChange?: (error: string | null) => void;\n /** Callback when the full cardholder name input changes. */\n onFullNameChange?: (value: string) => void;\n /** Callback when first name changes (from the name input). */\n onFirstNameChange?: (value: string) => void;\n /** Callback when last name changes (from the name input). */\n onLastNameChange?: (value: string) => void;\n /**\n * Show PayPal button above card fields. Defaults to `true`.\n * Uses Stripe's ExpressCheckoutElement in a separate Elements instance,\n * matching checkout/StripeCardForm architecture.\n */\n showPayPal?: boolean;\n /** Show Apple Pay button. Defaults to `true`. Only renders on supported devices. */\n showApplePay?: boolean;\n /** Show Google Pay button. Defaults to `true`. Only renders on supported devices. */\n showGooglePay?: boolean;\n /**\n * Layout mode for the payment form.\n * - `'default'` — all payment methods + card form shown together (current behavior)\n * - `'buttons'` — PayPal, wallets, and a \"Credit / Debit Card\" button; clicking the card\n * button expands the card form with a back button to return to the button view\n */\n layout?: 'default' | 'buttons';\n /**\n * Theme preset for the `buttons` layout. Ignored when `layout` is `'default'`.\n * - `'default'` — white card button, neutral borders\n * - `'minimal'` — borderless, subtle backgrounds\n * - `'rounded'` — large border radius, soft shadows\n * - `'dark'` — dark backgrounds, light text\n */\n buttonsTheme?: import('@flopay/shared').ButtonsLayoutTheme;\n /** Custom style overrides for the `buttons` layout. Merged on top of the theme preset. */\n buttonsStyles?: import('@flopay/shared').ButtonsLayoutStyles;\n /** Custom React content rendered inside the card button when `layout=\"buttons\"`. */\n cardButtonContent?: React.ReactNode;\n /** Custom React content rendered for the buttons-layout card back button label. */\n cardBackButtonContent?: React.ReactNode;\n /** Custom React content rendered for the card-form title. */\n cardTitleContent?: React.ReactNode;\n /** Whether to show the default security footer in `layout=\"default\"`. Defaults to `true`. */\n showSecurityFooter?: boolean;\n /**\n * Called when a payment method button is clicked.\n * `method`: `'card'` | `'paypal'` | `'apple_pay'` | `'google_pay'`\n */\n onButtonClick?: (method: CheckoutButtonMethod) => void;\n /**\n * Called before a payment button continues in `layout=\"buttons\"`.\n * Runs for card, PayPal, Apple Pay, and Google Pay.\n */\n onBeforeButtonClick?: (\n event: BeforeButtonClickEvent,\n ) => MaybePromise<void | false | InlineSessionPatch>;\n /**\n * Enable AVS (Address Verification).\n * - `true` — show country + postal code (backward compatible default)\n * - `AVSFieldConfig` — granular per-field control, optionally scoped to country codes\n * - `false` / omitted — AVS disabled\n */\n enableAVS?: boolean | AVSFieldConfig;\n /** Layout for AVS fields: 'row' (side-by-side, default) or 'column' (stacked). */\n avsLayout?: 'row' | 'column';\n /** Pre-filled country code (ISO 3166-1 alpha-2) for AVS. */\n country?: string;\n /** Pre-filled ZIP/postal code for AVS. */\n zip?: string;\n /** Pre-filled street address (line 1) for AVS. Typically from a partner GeoIP / profile lookup. */\n addressLine1?: string;\n /** Pre-filled apt/suite/unit (line 2) for AVS. */\n addressLine2?: string;\n /** Pre-filled city for AVS. Typically from a partner GeoIP / profile lookup. */\n city?: string;\n /** Pre-filled state/province for AVS. Typically from a partner GeoIP / profile lookup. */\n state?: string;\n /** Callback when AVS country changes. */\n onCountryChange?: (country: string) => void;\n /** Callback when AVS ZIP/postal code changes. */\n onZipChange?: (zip: string) => void;\n // ── Checkout analytics metadata ──\n /** Whether AVS was enabled (sent to backend for analytics). */\n avsCheck?: boolean;\n /** Checkout type: 'standard_checkout' or 'embedded_checkout'. */\n checkoutType?: string;\n /** Checkout layout: 'default_layout', 'buttons_layout', or 'custom_layout'. */\n checkoutLayout?: string;\n /** Total amount in cents (smallest currency unit). Used for wallet/PayPal Elements config. */\n totalAmount?: number;\n /** Currency code (used for PayPal Elements config). */\n currency?: string;\n /** Render the card form expanded on first paint when `layout=\"buttons\"`. */\n initialCardOpen?: boolean;\n}\n\n/**\n * Split card checkout form matching `checkout/StripeCardForm`:\n * PayPal button → divider → CardNumber → CardExpiry + CardCVC → Full Name → Submit.\n *\n * PayPal uses its own Stripe Elements instance (no `paymentMethodCreation`)\n * exactly like checkout does with two separate `<Elements>` wrappers.\n */\nexport const SplitCardForm = forwardRef<SplitCardFormRef, SplitCardFormProps>(\n function SplitCardForm(props, ref) {\n return <SplitCardFormInner {...props} innerRef={ref} />;\n },\n);\n\n// ─── PayPal button (own Elements instance) ──────────────────────────────────\n// Mirrors checkout/StripeCardForm's StripePayPalButtonInner exactly.\n\nfunction PayPalButtonInner({\n sessionId,\n email,\n billingApiUrl,\n onTokenizedBody,\n onErrorChange,\n isProcessing = false,\n onButtonClick,\n onDecline,\n runBeforeButtonClick,\n onLoadStateChange,\n}: {\n sessionId: string;\n email?: string;\n billingApiUrl: string;\n onTokenizedBody: InternalTokenizedBodyHandler;\n onErrorChange?: (error: string | null) => void;\n isProcessing?: boolean;\n onButtonClick?: (method: CheckoutButtonMethod) => void;\n onDecline?: (decline: DeclineEvent) => void;\n runBeforeButtonClick?: RunBeforeButtonClick;\n onLoadStateChange?: (state: ExpressCheckoutLoadState) => void;\n}) {\n const stripe = useStripeRaw();\n const elements = useStripeElements();\n const [loadState, setLoadState] = useState<ExpressCheckoutLoadState>('loading');\n useEffect(() => {\n onLoadStateChange?.(loadState);\n }, [loadState, onLoadStateChange]);\n const [submitting, setSubmitting] = useState(false);\n const paypalResumeAttempted = useRef(false);\n const beforeClickRef = useRef<{\n accountPatch?: InlineSessionPatch['account'];\n sessionId?: string;\n } | null>(null);\n const baseUrl = billingApiUrl.replace(/\\/+$/, '');\n\n // Resume PayPal redirect return — detect payment_intent in URL\n useEffect(() => {\n if (!stripe || paypalResumeAttempted.current) return;\n\n const params = new URLSearchParams(window.location.search);\n const paymentIntentId = params.get('payment_intent');\n const clientSecret = params.get('payment_intent_client_secret');\n const redirectStatus = params.get('redirect_status');\n\n if (!paymentIntentId || !clientSecret) return;\n paypalResumeAttempted.current = true;\n\n // Strip Stripe's PayPal-redirect params from the URL up front, before any\n // async work. The resume `useRef` guard above is reset on remount — if a\n // remount races our async resume, the only way to stop it from re-firing\n // for the same PI is to make sure the URL no longer signals \"we're inside\n // a resume.\" Doing this synchronously (rather than only after a successful\n // /process) closes that re-entry window for every branch below.\n const cleanedUrl = new URL(window.location.href);\n cleanedUrl.searchParams.delete('payment_intent');\n cleanedUrl.searchParams.delete('payment_intent_client_secret');\n cleanedUrl.searchParams.delete('redirect_status');\n window.history.replaceState({}, '', cleanedUrl.toString());\n\n (async () => {\n try {\n setSubmitting(true);\n\n if (redirectStatus === 'failed') {\n const message = 'PayPal payment was declined. Please try again.';\n onErrorChange?.(message);\n onDecline?.(buildDeclineEvent('paypal', message));\n return;\n }\n\n const { paymentIntent, error } = await stripe.retrievePaymentIntent(clientSecret);\n if (error) {\n onErrorChange?.(error.message ?? 'Failed to retrieve PayPal payment status.');\n return;\n }\n\n if (paymentIntent && (paymentIntent.status === 'requires_capture' || paymentIntent.status === 'succeeded')) {\n const paymentMethodId = typeof paymentIntent.payment_method === 'string'\n ? paymentIntent.payment_method\n : paymentIntent.payment_method?.id;\n\n onTokenizedBody({\n id: paymentMethodId ?? paymentIntent.id,\n type: 'card',\n threeDSecureActionResultTokenId: paymentIntent.id,\n isPaypal: true,\n });\n } else {\n const message = 'PayPal payment was not completed. Please try again.';\n onErrorChange?.(message);\n onDecline?.(buildDeclineEvent('paypal', message));\n }\n } catch (err) {\n onErrorChange?.(err instanceof Error ? err.message : 'Failed to complete PayPal payment.');\n } finally {\n setSubmitting(false);\n }\n })();\n }, [stripe, onTokenizedBody, onErrorChange, onDecline]);\n\n const handlePayPalClick = useCallback(async (\n event: { resolve: () => void; reject: () => void },\n ) => {\n if (isProcessing || submitting) {\n event.reject();\n return;\n }\n\n const beforeClick = runBeforeButtonClick\n ? await runBeforeButtonClick('paypal')\n : { proceed: true } as BeforeButtonClickResult;\n\n if (!beforeClick.proceed) {\n beforeClickRef.current = null;\n event.reject();\n return;\n }\n\n beforeClickRef.current = {\n accountPatch: beforeClick.accountPatch,\n sessionId: beforeClick.sessionId,\n };\n onButtonClick?.('paypal');\n event.resolve();\n }, [isProcessing, onButtonClick, runBeforeButtonClick, submitting]);\n\n // PayPal confirm handler — called by ExpressCheckoutElement onConfirm\n const handlePayPalConfirm = useCallback(async (event: StripeExpressCheckoutElementConfirmEvent) => {\n if (!stripe || !elements) return;\n\n let prepared = beforeClickRef.current;\n beforeClickRef.current = null;\n\n if (!prepared && runBeforeButtonClick) {\n const beforeClick = await runBeforeButtonClick('paypal');\n if (!beforeClick.proceed) {\n event.paymentFailed({ reason: 'fail', message: 'PayPal checkout was cancelled.' });\n return;\n }\n prepared = {\n accountPatch: beforeClick.accountPatch,\n sessionId: beforeClick.sessionId,\n };\n }\n\n const effectiveSessionId = prepared?.sessionId ?? sessionId;\n const effectiveEmail = prepared?.accountPatch?.email ?? email;\n\n try {\n setSubmitting(true);\n onErrorChange?.(null);\n\n if (!effectiveSessionId || !effectiveEmail) {\n throw new Error('Missing sessionId or email for PayPal payment');\n }\n\n const createPM = stripe.createPaymentMethod as unknown as (\n params: { type: string },\n ) => Promise<{ error?: { message?: string }; paymentMethod?: { id: string } }>;\n\n const { error: pmError, paymentMethod } = await createPM({ type: 'paypal' });\n if (pmError) {\n const message = pmError.message ?? 'PayPal payment failed.';\n onErrorChange?.(message);\n event.paymentFailed({ reason: 'fail', message });\n return;\n }\n\n // 1. Create PaymentIntent via backend with the PayPal payment method.\n // isPaypal must be string 'true' — backend checks === 'true'.\n\n const intentResponse = await fetch(`${baseUrl}/v1/checkouts/payments/intents`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n sessionId: effectiveSessionId,\n email: effectiveEmail,\n paymentMethodType: paymentMethod?.id ?? 'paypal',\n isPaypal: 'true',\n setupFutureUsage: 'off_session',\n setup_future_usage: 'off_session',\n }),\n });\n\n if (!intentResponse.ok) {\n const intentError = await buildFloPayApiErrorFromResponse(\n intentResponse,\n 'Failed to create payment intent',\n );\n onErrorChange?.(intentError.message);\n onDecline?.(buildDeclineEvent('paypal', intentError));\n event.paymentFailed({ reason: 'fail', message: intentError.message });\n return;\n }\n const intentJson = await intentResponse.json() as { data?: { id?: string } };\n const intentClientSecret = intentJson.data?.id;\n if (!intentClientSecret) throw new Error('No client_secret in payment intent response');\n\n // 2. Confirm payment — PayPal will redirect or complete inline.\n const confirmParams: Record<string, unknown> = {\n return_url: window.location.href,\n };\n if (paymentMethod?.id) {\n confirmParams['payment_method'] = paymentMethod.id;\n }\n\n const { error: confirmError, paymentIntent } = await stripe.confirmPayment({\n clientSecret: intentClientSecret,\n confirmParams: confirmParams as { return_url: string },\n redirect: 'if_required',\n });\n\n if (confirmError) {\n const message = confirmError.message ?? 'PayPal payment failed.';\n onErrorChange?.(message);\n onDecline?.(buildDeclineEvent('paypal', message, {\n code: confirmError.code,\n }));\n return;\n }\n\n const confirmedPmId = typeof paymentIntent?.payment_method === 'string'\n ? paymentIntent.payment_method\n : paymentIntent?.payment_method?.id;\n\n onTokenizedBody({\n id: confirmedPmId ?? paymentIntent?.id,\n type: 'card',\n threeDSecureActionResultTokenId: paymentIntent?.id,\n isPaypal: true,\n }, {\n accountPatch: prepared?.accountPatch,\n sessionId: effectiveSessionId,\n });\n return;\n } catch (err) {\n onErrorChange?.(err instanceof Error ? err.message : 'PayPal payment failed. Please try again.');\n } finally {\n setSubmitting(false);\n }\n }, [stripe, elements, sessionId, email, baseUrl, onTokenizedBody, onErrorChange, onDecline, runBeforeButtonClick]);\n\n return (\n <>\n <ExpressCheckoutReadySwap state={loadState} placeholderTestId=\"flopay-paypal-placeholder\">\n <ExpressCheckoutElement\n onReady={(event) => setLoadState(resolveExpressCheckoutLoadState(event, ['paypal']))}\n onLoadError={() => setLoadState('load_error')}\n onClick={handlePayPalClick}\n onConfirm={handlePayPalConfirm}\n onCancel={() => {\n beforeClickRef.current = null;\n onDecline?.(buildDeclineEvent('paypal', 'PayPal checkout was cancelled.'));\n }}\n options={{\n buttonType: { paypal: 'paypal' } as Record<string, string>,\n billingAddressRequired: false,\n phoneNumberRequired: false,\n shippingAddressRequired: false,\n paymentMethods: {\n applePay: 'never',\n googlePay: 'never',\n paypal: 'auto',\n link: 'never',\n },\n } as Parameters<typeof ExpressCheckoutElement>[0]['options']}\n />\n </ExpressCheckoutReadySwap>\n {submitting && <ProcessingOverlay status=\"processing\" />}\n </>\n );\n}\n\n// ─── Wallet buttons (Apple Pay / Google Pay — own Elements instance) ────────\n// Uses raw stripe + elements from its own StripeElements context,\n// matching checkout/StripeCardForm's handleExpressCheckoutConfirm exactly.\n\nfunction WalletButtonInner({\n sessionId,\n email,\n billingApiUrl,\n showApplePay = true,\n showGooglePay = true,\n onTokenizedBody,\n onErrorChange,\n onButtonClick,\n onDecline,\n runBeforeButtonClick,\n onLoadStateChange,\n}: {\n sessionId: string;\n email?: string;\n billingApiUrl: string;\n showApplePay?: boolean;\n showGooglePay?: boolean;\n onTokenizedBody: InternalTokenizedBodyHandler;\n onErrorChange?: (error: string | null) => void;\n onButtonClick?: (method: CheckoutButtonMethod) => void;\n onDecline?: (decline: DeclineEvent) => void;\n runBeforeButtonClick?: RunBeforeButtonClick;\n onLoadStateChange?: (state: ExpressCheckoutLoadState) => void;\n}) {\n const stripe = useStripeRaw();\n const elements = useStripeElements();\n const [loadState, setLoadState] = useState<ExpressCheckoutLoadState>('loading');\n useEffect(() => {\n onLoadStateChange?.(loadState);\n }, [loadState, onLoadStateChange]);\n const [submitting, setSubmitting] = useState(false);\n const baseUrl = billingApiUrl.replace(/\\/+$/, '');\n const lastWalletMethodRef = useRef<CheckoutButtonMethod>('card');\n const beforeClickRef = useRef<{\n accountPatch?: InlineSessionPatch['account'];\n sessionId?: string;\n } | null>(null);\n\n const handleWalletConfirm = useCallback(\n async (event: StripeExpressCheckoutElementConfirmEvent) => {\n if (!stripe || !elements) return;\n\n // Detect wallet type from the express checkout event\n const walletType = (event as unknown as { expressPaymentType?: string }).expressPaymentType;\n let prepared = beforeClickRef.current;\n beforeClickRef.current = null;\n\n if (!prepared && runBeforeButtonClick) {\n const beforeClick = await runBeforeButtonClick(\n walletType === 'apple_pay' ? 'apple_pay' : 'google_pay',\n );\n if (!beforeClick.proceed) {\n event.paymentFailed({ reason: 'fail', message: 'Wallet checkout was cancelled.' });\n return;\n }\n prepared = {\n accountPatch: beforeClick.accountPatch,\n sessionId: beforeClick.sessionId,\n };\n }\n\n const method = walletType === 'apple_pay' ? 'apple_pay' : 'google_pay';\n const effectiveSessionId = prepared?.sessionId ?? sessionId;\n const effectiveEmail = prepared?.accountPatch?.email ?? email;\n\n try {\n setSubmitting(true);\n onErrorChange?.(null);\n\n // 1. Submit elements (validates wallet payment sheet)\n const { error: submitError } = await elements.submit();\n if (submitError) {\n onErrorChange?.(submitError.message ?? 'Wallet payment failed.');\n return;\n }\n\n // 2. Create PaymentMethod from wallet token via the wallet's own Elements\n const { error: pmError, paymentMethod } = await stripe.createPaymentMethod({ elements });\n if (pmError || !paymentMethod) {\n onErrorChange?.(pmError?.message ?? 'Failed to create payment method.');\n return;\n }\n\n if (!effectiveSessionId || !effectiveEmail) {\n throw new Error('Missing sessionId or email for wallet payment');\n }\n\n // 3. Create PaymentIntent via backend\n const intentResponse = await fetch(`${baseUrl}/v1/checkouts/payments/intents`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n sessionId: effectiveSessionId,\n email: effectiveEmail,\n paymentMethodType: paymentMethod.id,\n isPaypal: false,\n }),\n });\n\n if (!intentResponse.ok) {\n const intentError = await buildFloPayApiErrorFromResponse(\n intentResponse,\n 'Failed to create payment intent',\n );\n onErrorChange?.(intentError.message);\n onDecline?.(buildDeclineEvent(method, intentError));\n event.paymentFailed({ reason: 'fail', message: intentError.message });\n return;\n }\n const intentJson = await intentResponse.json() as { data?: { id?: string } };\n const intentClientSecret = intentJson.data?.id;\n if (!intentClientSecret) throw new Error('No client_secret in payment intent response');\n\n // 4. Confirm card payment (handles 3DS automatically)\n const { error: confirmError, paymentIntent } = await stripe.confirmCardPayment(\n intentClientSecret,\n { payment_method: paymentMethod.id },\n );\n\n if (confirmError) {\n const message = confirmError.message ?? 'Wallet payment failed.';\n onErrorChange?.(message);\n onDecline?.(buildDeclineEvent(method, message, {\n code: confirmError.code,\n }));\n return;\n }\n\n // 5. Send PM + PI to process endpoint\n onTokenizedBody({\n id: paymentMethod.id,\n type: 'card',\n threeDSecureActionResultTokenId: paymentIntent?.id,\n }, {\n accountPatch: prepared?.accountPatch,\n sessionId: effectiveSessionId,\n });\n } catch (err) {\n onErrorChange?.(err instanceof Error ? err.message : 'Wallet payment failed. Please try again.');\n } finally {\n setSubmitting(false);\n }\n },\n [stripe, elements, sessionId, email, baseUrl, onTokenizedBody, onErrorChange, onDecline, runBeforeButtonClick],\n );\n\n return (\n <>\n <ExpressCheckoutReadySwap state={loadState} placeholderTestId=\"flopay-wallet-placeholder\">\n <ExpressCheckoutElement\n onReady={(event) => setLoadState(resolveExpressCheckoutLoadState(event, ['applePay', 'googlePay']))}\n onLoadError={() => setLoadState('load_error')}\n onClick={async (event) => {\n lastWalletMethodRef.current = event.expressPaymentType === 'apple_pay' ? 'apple_pay' : 'google_pay';\n\n const beforeClick = runBeforeButtonClick\n ? await runBeforeButtonClick(lastWalletMethodRef.current)\n : { proceed: true } as BeforeButtonClickResult;\n\n if (!beforeClick.proceed) {\n beforeClickRef.current = null;\n event.reject();\n return;\n }\n\n beforeClickRef.current = {\n accountPatch: beforeClick.accountPatch,\n sessionId: beforeClick.sessionId,\n };\n onButtonClick?.(lastWalletMethodRef.current);\n event.resolve();\n }}\n onConfirm={handleWalletConfirm}\n onCancel={() => {\n beforeClickRef.current = null;\n onDecline?.(buildDeclineEvent(lastWalletMethodRef.current, 'Wallet checkout was cancelled.'));\n }}\n options={{\n buttonType: { applePay: 'plain', googlePay: 'plain' } as Record<string, string>,\n paymentMethods: {\n applePay: showApplePay ? 'always' : 'never',\n googlePay: showGooglePay ? 'always' : 'never',\n paypal: 'never',\n link: 'never',\n amazonPay: 'never',\n klarna: 'never',\n },\n layout: { maxColumns: 1, overflow: 'never' },\n } as Parameters<typeof ExpressCheckoutElement>[0]['options']}\n />\n </ExpressCheckoutReadySwap>\n {submitting && <ProcessingOverlay status=\"processing\" />}\n </>\n );\n}\n\n// ─── Main form ──────────────────────────────────────────────────────────────\n\nfunction SplitCardFormInner({\n sessionId,\n billingApiUrl,\n email,\n userId,\n onComplete,\n onError,\n onDecline,\n onTokenizedBody,\n firstName,\n lastName,\n chv,\n submitLabel = 'CONFIRM PAYMENT',\n className,\n children,\n isProcessing: externalProcessing,\n error: externalError,\n onErrorChange,\n onFullNameChange,\n onFirstNameChange,\n onLastNameChange,\n showPayPal = true,\n showApplePay = true,\n showGooglePay = true,\n layout = 'default',\n buttonsTheme,\n buttonsStyles: buttonsStylesOverride,\n cardButtonContent,\n cardBackButtonContent,\n cardTitleContent,\n showSecurityFooter = true,\n onButtonClick,\n onBeforeButtonClick,\n enableAVS: enableAVSProp,\n avsLayout: avsLayoutProp = 'row',\n country: countryProp,\n zip: zipProp,\n addressLine1: addressLine1Prop,\n addressLine2: addressLine2Prop,\n city: cityProp,\n state: stateProp,\n onCountryChange,\n onZipChange,\n avsCheck: avsCheckProp,\n checkoutType: checkoutTypeProp,\n checkoutLayout: checkoutLayoutProp,\n totalAmount = 0,\n currency = 'usd',\n initialCardOpen = false,\n innerRef,\n}: SplitCardFormProps & { innerRef: React.Ref<SplitCardFormRef> }) {\n const flopay = useFloPay();\n const paypalFlopay = usePayPalFloPay();\n const elements = useElements();\n const checkout = useContext(CheckoutContext);\n const contextBillingUrl = useBillingApiUrl();\n const [processing, setProcessing] = useState(false);\n const [error, setError] = useState<string | null>(null);\n const [is3DSActive, setIs3DSActive] = useState(false);\n const [selectedCountry, setSelectedCountry] = useState(countryProp ?? 'US');\n const [zipCode, setZipCode] = useState(zipProp ?? '');\n const [addressLine1, setAddressLine1] = useState(addressLine1Prop ?? '');\n const [addressLine2, setAddressLine2] = useState(addressLine2Prop ?? '');\n const [city, setCity] = useState(cityProp ?? '');\n const [stateValue, setStateValue] = useState(stateProp ?? '');\n const [accountPatch, setAccountPatch] = useState<InlineSessionPatch['account']>({});\n const zipCodeRef = useRef(zipProp ?? '');\n const selectedCountryRef = useRef(countryProp ?? 'US');\n const addressLine1Ref = useRef(addressLine1Prop ?? '');\n const addressLine2Ref = useRef(addressLine2Prop ?? '');\n const cityRef = useRef(cityProp ?? '');\n const stateRef = useRef(stateProp ?? '');\n\n // Resolve AVS config: boolean → default config, object → as-is, falsy → null\n const avsConfig = useMemo(() => resolveAVSConfig(enableAVSProp), [enableAVSProp]);\n const enableAVS = avsConfig !== null;\n\n // Buttons ↔ Card transition state machine\n type ViewState = 'buttons' | 'expanding' | 'card' | 'collapsing';\n const [viewState, setViewState] = useState<ViewState>(initialCardOpen ? 'card' : 'buttons');\n const showCardForm = viewState === 'expanding' || viewState === 'card';\n const TRANSITION_MS = 280;\n\n const expandToCard = useCallback(() => {\n setViewState('expanding');\n setTimeout(() => setViewState('card'), TRANSITION_MS);\n }, []);\n\n const collapseToButtons = useCallback(() => {\n setViewState('collapsing');\n setTimeout(() => setViewState('buttons'), TRANSITION_MS);\n }, []);\n\n useEffect(() => {\n if (layout === 'buttons' && initialCardOpen) {\n setViewState('card');\n }\n }, [layout, initialCardOpen]);\n const [fullName, setFullName] = useState('');\n const [formReady, setFormReady] = useState(false);\n const [overlayStatus, setOverlayStatus] = useState<OverlayStatus | null>(null);\n const processingRef = useRef(false);\n\n const resolvedBillingApiUrl = billingApiUrl || contextBillingUrl;\n const displayError = externalError ?? error;\n\n // Resolve buttons layout styles: theme preset merged with custom overrides\n const bStyles = useMemo<ButtonsLayoutStyles>(() => {\n const base = resolveButtonsLayoutTheme(buttonsTheme);\n if (!buttonsStylesOverride) return base;\n return {\n ...base,\n ...buttonsStylesOverride,\n cardButton: { ...base.cardButton, ...buttonsStylesOverride.cardButton },\n cardFormContainer: { ...base.cardFormContainer, ...buttonsStylesOverride.cardFormContainer },\n backButton: { ...base.backButton, ...buttonsStylesOverride.backButton },\n backButtonIcon: { ...base.backButtonIcon, ...buttonsStylesOverride.backButtonIcon },\n submitButton: { ...base.submitButton, ...buttonsStylesOverride.submitButton },\n title: { ...base.title, ...buttonsStylesOverride.title },\n };\n }, [buttonsTheme, buttonsStylesOverride]);\n const isInlineSessionPatchProcessing = checkout.inlineSessionPatchProcessing ?? false;\n const isSubmitting = (externalProcessing ?? processing) || isInlineSessionPatchProcessing;\n const isSelfContained = !onTokenizedBody;\n const baseUrl = resolvedBillingApiUrl.replace(/\\/+$/, '');\n const resolvedAccount = useMemo(() => mergeAccountPatch({\n userId,\n email,\n firstName,\n lastName,\n country: countryProp,\n zip: zipProp,\n }, accountPatch), [userId, email, firstName, lastName, countryProp, zipProp, accountPatch]);\n\n // Get raw Stripe instance for wallet Elements provider (primary Stripe account).\n const stripeInstance = useMemo(() => {\n if (!flopay) return null;\n return flopay.getRawProvider() as Stripe | null;\n }, [flopay]);\n\n // Get raw Stripe instance for the PayPal Elements provider. PayPal lives on\n // the dedicated PayPal Stripe account (gatewayData.paypalPublishableKey).\n // When no PayPal FloPay is configured, PayPal is disabled entirely.\n const paypalStripeInstance = useMemo(() => {\n if (!paypalFlopay) return null;\n return paypalFlopay.getRawProvider() as Stripe | null;\n }, [paypalFlopay]);\n\n // totalAmount is in cents (smallest currency unit) when passed from FloPayCheckout.\n // Stripe Elements `amount` expects cents.\n const amountInCents = totalAmount || 100; // minimum 1 cent\n\n // Wallet (Apple/Google Pay) Elements options — uses paymentMethodCreation: 'manual'\n // to match the main card Elements, allowing explicit createPaymentMethod() calls.\n const walletOptions = useMemo(() => ({\n mode: 'payment' as const,\n amount: amountInCents,\n currency: currency.toLowerCase(),\n paymentMethodCreation: 'manual' as const,\n captureMethod: 'manual' as const,\n }), [amountInCents, currency]);\n\n // PayPal Elements options — no paymentMethodCreation (matches checkout)\n const paypalOptions = useMemo(() => ({\n mode: 'payment' as const,\n amount: amountInCents,\n currency: currency.toLowerCase(),\n captureMethod: 'manual' as const,\n setupFutureUsage: 'off_session' as const,\n }), [amountInCents, currency]);\n\n const updateError = useCallback(\n (err: string | null) => {\n setError(err);\n onErrorChange?.(err);\n },\n [onErrorChange],\n );\n\n const emitDecline = useCallback(\n (\n method: CheckoutButtonMethod,\n input: string | FloPayError,\n overrides?: { code?: string; declineCode?: string },\n ) => {\n onDecline?.(buildDeclineEvent(method, input, overrides));\n },\n [onDecline],\n );\n\n const showWallets = showApplePay || showGooglePay;\n\n // Known in-app browser WebViews do not reliably support PayPal/wallet\n // express checkout. Suppress those rows proactively and let card checkout\n // remain available. Outside known WebViews, Stripe availability events still\n // collapse unavailable/load-error rows via ExpressCheckoutReadySwap.\n const [paypalLoadState, setPaypalLoadState] = useState<ExpressCheckoutLoadState>('loading');\n const [walletLoadState, setWalletLoadState] = useState<ExpressCheckoutLoadState>('loading');\n const [inAppBrowserDetected, setInAppBrowserDetected] = useState<boolean>();\n useEffect(() => {\n setInAppBrowserDetected(isInAppBrowser());\n }, []);\n const shouldShowPayPal = showPayPal && inAppBrowserDetected === false;\n const shouldShowWallets = showWallets && inAppBrowserDetected === false;\n const shouldRenderPayPal = shouldShowPayPal && !!paypalStripeInstance;\n const shouldRenderWallets = shouldShowWallets && !!stripeInstance;\n const shouldDisplayPayPalRow = shouldRenderPayPal && isExpressCheckoutRowVisible(paypalLoadState);\n const shouldDisplayWalletRow = shouldRenderWallets && isExpressCheckoutRowVisible(walletLoadState);\n\n const handleNameChange = useCallback((value: string) => {\n setFullName(value);\n onFullNameChange?.(value);\n const parts = value.trim().split(/\\s+/);\n onFirstNameChange?.(parts[0] ?? '');\n onLastNameChange?.(parts.length > 1 ? parts.slice(1).join(' ') : '');\n }, [onFullNameChange, onFirstNameChange, onLastNameChange]);\n\n const applyInlineSessionPatch = useCallback(\n (patch: InlineSessionPatch, method: CheckoutButtonMethod): Promise<BeforeButtonClickPatchResult> => {\n if (!checkout.applyInlineSessionPatch) {\n return Promise.resolve({ error: null, sessionId });\n }\n\n return checkout.applyInlineSessionPatch(patch)\n .then((result) => ({\n error: null,\n sessionId: result.sessionId || sessionId,\n }))\n .catch((err) => {\n const floPayErr = normalizeBeforeButtonClickError(method, err);\n updateError(floPayErr.message);\n onError?.(floPayErr);\n return { error: floPayErr, sessionId };\n });\n },\n [checkout.applyInlineSessionPatch, onError, sessionId, updateError],\n );\n\n const runBeforeButtonClick = useCallback(async (\n method: CheckoutButtonMethod,\n ): Promise<BeforeButtonClickResult> => {\n if (!onBeforeButtonClick) return { proceed: true };\n\n try {\n const result = await onBeforeButtonClick({\n method,\n sessionId: sessionId || undefined,\n createSession: checkout.inlineSessionDraft,\n });\n\n if (result === false) {\n return { proceed: false };\n }\n\n if (result && typeof result === 'object') {\n if (result.account) {\n setAccountPatch((prev) => ({ ...(prev ?? {}), ...result.account }));\n }\n\n const patchResult = await applyInlineSessionPatch(result, method);\n if (patchResult.error) {\n return {\n proceed: false,\n accountPatch: result.account,\n };\n }\n\n return {\n proceed: true,\n accountPatch: result.account,\n sessionId: patchResult.sessionId,\n };\n }\n\n return { proceed: true };\n } catch (err) {\n const floPayErr = normalizeBeforeButtonClickError(method, err);\n updateError(floPayErr.message);\n onError?.(floPayErr);\n return { proceed: false };\n }\n }, [applyInlineSessionPatch, checkout.inlineSessionDraft, onBeforeButtonClick, onError, sessionId, updateError]);\n\n // ── Internal processPayment + 3DS retry ──\n\n const processPaymentInternal = useCallback(\n async (tokenizedBody: TokenizedBody, overrides?: TokenizedBodyOverrides) => {\n // Prevent double-processing\n if (processingRef.current) return;\n processingRef.current = true;\n\n setProcessing(true);\n setOverlayStatus('processing');\n updateError(null);\n\n const effectiveSessionId = overrides?.sessionId ?? sessionId;\n const effectiveAccount = mergeAccountPatch(resolvedAccount, overrides?.accountPatch);\n const resolvedCompletionPaymentMethodId =\n overrides?.completionPaymentMethodId ?? resolveTokenizedPaymentMethodId(tokenizedBody);\n const requestTokenizedBody = tokenizedBody.originalPaymentMethodId\n ? { ...tokenizedBody, originalPaymentMethodId: undefined }\n : tokenizedBody;\n\n try {\n const api = new PaymentAPI(baseUrl);\n const response = await api.processPayment(effectiveAccount.userId ?? '', {\n sessionId: effectiveSessionId,\n tokenizedData: requestTokenizedBody,\n accountData: {\n userId: effectiveAccount.userId ?? '',\n email: effectiveAccount.email ?? '',\n firstName: effectiveAccount.firstName ?? fullName.trim().split(/\\s+/)[0] ?? '',\n lastName: effectiveAccount.lastName ?? fullName.trim().split(/\\s+/).slice(1).join(' ') ?? '',\n ...(avsConfig ? (() => {\n const c = selectedCountryRef.current;\n const stateVisible = isAVSFieldVisible(avsConfig.state, c);\n const line1Visible = isAVSFieldVisible(avsConfig.address_line_1, c);\n const zipVisible = isAVSFieldVisible(avsConfig.postal_code, c);\n // When line1 is collected but state is hidden, derive state\n // from the ZIP for US/CA so Stripe AVS still gets a state signal.\n const derivedState = (line1Visible && !stateVisible && zipVisible)\n ? getStateFromPostalCode(c, zipCodeRef.current ?? '')\n : null;\n const stateValue = stateVisible ? stateRef.current : derivedState;\n return {\n country: c,\n ...(zipVisible && zipCodeRef.current ? { zip: zipCodeRef.current } : {}),\n ...(isAVSFieldVisible(avsConfig.city, c) && cityRef.current ? { city: cityRef.current } : {}),\n ...(stateValue ? { state: stateValue } : {}),\n ...(line1Visible && addressLine1Ref.current ? { addressLine1: addressLine1Ref.current } : {}),\n ...(isAVSFieldVisible(avsConfig.address_line_2, c) && addressLine2Ref.current ? { addressLine2: addressLine2Ref.current } : {}),\n };\n })() : {}),\n },\n chv,\n // Checkout analytics metadata\n avsCheck: avsCheckProp ?? false,\n checkoutType: checkoutTypeProp,\n checkoutLayout: checkoutLayoutProp,\n // Resolved exposure: which fields were actually shown for the active country.\n // Country-scoped rules (e.g. ['US', 'CA']) are flattened to booleans here.\n avsConfig: avsConfig ? {\n country: isAVSFieldVisible(avsConfig.country, selectedCountryRef.current),\n postal_code: isAVSFieldVisible(avsConfig.postal_code, selectedCountryRef.current),\n address_line_1: isAVSFieldVisible(avsConfig.address_line_1, selectedCountryRef.current),\n address_line_2: isAVSFieldVisible(avsConfig.address_line_2, selectedCountryRef.current),\n city: isAVSFieldVisible(avsConfig.city, selectedCountryRef.current),\n state: isAVSFieldVisible(avsConfig.state, selectedCountryRef.current),\n } : undefined,\n });\n\n if (response.ok) {\n // Mark the session as completed *now*, before the 1.2s success\n // overlay delay below. A bootstrap that re-runs during that delay\n // (real remount, navigation flicker, etc.) would otherwise see the\n // backend status flipped to 'complete', clear the cache, and POST\n // a duplicate session that would then be /process'd with the\n // original PaymentIntent — double-charging the buyer.\n markSessionRecentlyCompleted(effectiveSessionId);\n setOverlayStatus('success');\n await new Promise((r) => setTimeout(r, PROCESSING_OVERLAY_SUCCESS_DELAY_MS));\n onComplete?.({\n status: 'succeeded',\n paymentIntentId: tokenizedBody.threeDSecureActionResultTokenId,\n paymentMethodId: resolvedCompletionPaymentMethodId,\n checkoutMethod: tokenizedBody.isPaypal ? 'paypal' : 'card',\n });\n return;\n }\n\n const json = await response.json().catch(() => null) as Record<string, unknown> | null;\n\n if (json?.type === '3ds_required') {\n const secret = json['threeDSecureToken'] as string;\n if (!flopay || !secret) {\n setOverlayStatus('error');\n updateError('3DS authentication required but no token provided.');\n return;\n }\n\n setIs3DSActive(true);\n try {\n // Only include AVS fields that are currently visible for the selected country.\n const retryBillingAddress: Record<string, string> = {};\n const retryCC = selectedCountryRef.current;\n const retryCountry = enableAVS ? retryCC : effectiveAccount.country;\n if (retryCountry) retryBillingAddress['country'] = retryCountry;\n if (avsConfig && isAVSFieldVisible(avsConfig.postal_code, retryCC) && zipCodeRef.current.trim()) {\n retryBillingAddress['postal_code'] = zipCodeRef.current.trim();\n } else if (!avsConfig && effectiveAccount.zip) {\n retryBillingAddress['postal_code'] = effectiveAccount.zip;\n }\n if (avsConfig && isAVSFieldVisible(avsConfig.address_line_1, retryCC) && addressLine1Ref.current.trim()) retryBillingAddress['line1'] = addressLine1Ref.current.trim();\n if (avsConfig && isAVSFieldVisible(avsConfig.address_line_2, retryCC) && addressLine2Ref.current.trim()) retryBillingAddress['line2'] = addressLine2Ref.current.trim();\n if (avsConfig && isAVSFieldVisible(avsConfig.city, retryCC) && cityRef.current.trim()) retryBillingAddress['city'] = cityRef.current.trim();\n if (avsConfig && isAVSFieldVisible(avsConfig.state, retryCC) && stateRef.current.trim()) {\n retryBillingAddress['state'] = stateRef.current.trim();\n } else if (\n avsConfig\n && isAVSFieldVisible(avsConfig.address_line_1, retryCC)\n && !isAVSFieldVisible(avsConfig.state, retryCC)\n && isAVSFieldVisible(avsConfig.postal_code, retryCC)\n ) {\n const derivedRetryState = getStateFromPostalCode(retryCC, zipCodeRef.current.trim());\n if (derivedRetryState) retryBillingAddress['state'] = derivedRetryState;\n }\n const result = await flopay.confirmPayment({\n clientSecret: secret,\n returnUrl: window.location.href,\n billingDetails: {\n ...(effectiveAccount.email ? { email: effectiveAccount.email } : {}),\n ...(fullName.trim() ? { name: fullName.trim() } : {}),\n ...(Object.keys(retryBillingAddress).length > 0 ? { address: retryBillingAddress } : {}),\n },\n });\n\n if (result.error) {\n setOverlayStatus('error');\n updateError(result.error.message);\n onError?.(result.error);\n emitDecline('card', result.error);\n return;\n }\n\n if (result.status === 'succeeded' || result.status === 'processing') {\n // Allow re-entry for 3DS retry\n processingRef.current = false;\n await processPaymentInternal({\n id: result.paymentIntentId,\n type: 'card',\n threeDSecureActionResultTokenId: result.paymentIntentId,\n }, {\n completionPaymentMethodId: resolvedCompletionPaymentMethodId,\n });\n }\n } finally {\n setIs3DSActive(false);\n }\n return;\n }\n\n // PayPal redirect required — backend created a PI that needs PayPal authorization.\n // Confirm the payment which triggers redirect to PayPal. On return, the\n // PayPalButtonInner's resume handler picks up the payment_intent URL params.\n if (json?.type === 'paypal_redirect_required') {\n const secret = json['threeDSecureToken'] as string;\n const savedPmId = (json['paymentMethodId'] as string) || tokenizedBody.id || '';\n if (!flopay || !secret) {\n setOverlayStatus('error');\n updateError('PayPal authorization required but no token provided.');\n return;\n }\n\n try {\n // PayPal PaymentIntents live on the PayPal Stripe account — route\n // the confirmation through the PayPal Stripe instance.\n const paypalStripe = paypalFlopay?.getRawProvider() as Stripe | null;\n if (!paypalStripe) {\n updateError('PayPal is not available.');\n return;\n }\n\n const confirmParams: Record<string, unknown> = {\n return_url: window.location.href,\n };\n if (savedPmId) {\n confirmParams['payment_method'] = savedPmId;\n }\n\n const { error: confirmError } = await paypalStripe.confirmPayment({\n clientSecret: secret,\n confirmParams: confirmParams as { return_url: string },\n redirect: 'if_required',\n });\n\n if (confirmError) {\n setOverlayStatus('error');\n const message = confirmError.message ?? 'PayPal payment failed.';\n updateError(message);\n emitDecline('paypal', message, {\n code: confirmError.code,\n });\n }\n } catch (err) {\n setOverlayStatus('error');\n updateError(err instanceof Error ? err.message : 'PayPal authorization failed.');\n }\n return;\n }\n\n setOverlayStatus('error');\n const message = (json?.message as string) ?? 'Payment failed. Please try again.';\n updateError(message);\n emitDecline(tokenizedBody.isPaypal ? 'paypal' : 'card', message, {\n code: (json?.code ?? json?.gatewayErrorCode) as string | undefined,\n declineCode: (json?.declineCode ?? json?.gatewayDeclineReason) as string | undefined,\n });\n await new Promise((r) => setTimeout(r, PROCESSING_OVERLAY_ERROR_DELAY_MS));\n } catch (err) {\n setOverlayStatus('error');\n updateError(err instanceof Error ? err.message : 'An unexpected error occurred');\n await new Promise((r) => setTimeout(r, PROCESSING_OVERLAY_ERROR_DELAY_MS));\n } finally {\n setProcessing(false);\n setOverlayStatus(null);\n processingRef.current = false;\n }\n },\n [baseUrl, sessionId, resolvedAccount, fullName, chv, flopay, paypalFlopay, onComplete, onError, updateError, emitDecline],\n );\n\n const dispatchTokenizedBody = useCallback(\n (tokenizedBody: TokenizedBody, overrides?: TokenizedBodyOverrides) => {\n if (onTokenizedBody) {\n onTokenizedBody(tokenizedBody);\n } else {\n processPaymentInternal(tokenizedBody, overrides);\n }\n },\n [onTokenizedBody, processPaymentInternal],\n );\n\n // ── Imperative 3DS handler ──\n\n useImperativeHandle(innerRef, () => ({\n async handleNextAction(secret: string) {\n if (!flopay) return;\n\n setIs3DSActive(true);\n try {\n const result = await flopay.confirmPayment({\n clientSecret: secret,\n returnUrl: window.location.href,\n });\n\n if (result.error) {\n updateError(result.error.message);\n onError?.(result.error);\n emitDecline('card', result.error);\n } else if (result.status === 'succeeded' || result.status === 'processing') {\n dispatchTokenizedBody({\n id: result.paymentIntentId,\n type: 'card',\n threeDSecureActionResultTokenId: result.paymentIntentId,\n });\n }\n } catch (err) {\n updateError(err instanceof Error ? err.message : 'Payment authentication failed.');\n } finally {\n setIs3DSActive(false);\n }\n },\n }), [flopay, dispatchTokenizedBody, onError, updateError, emitDecline]);\n\n // ── Wallet resume ──\n\n useEffect(() => {\n if (typeof window === 'undefined') return;\n\n const stored = localStorage.getItem(WALLET_RESUME_KEY);\n if (!stored) return;\n\n try {\n const payload = JSON.parse(stored) as {\n sessionId: string;\n paymentIntentId: string;\n tokenType: string;\n tokenId: string;\n status: string;\n };\n\n if (payload.sessionId === sessionId) {\n localStorage.removeItem(WALLET_RESUME_KEY);\n dispatchTokenizedBody({\n id: payload.tokenId,\n type: payload.tokenType,\n threeDSecureActionResultTokenId: payload.paymentIntentId,\n });\n }\n } catch {\n localStorage.removeItem(WALLET_RESUME_KEY);\n }\n }, [sessionId, dispatchTokenizedBody]);\n\n // ── Card submit ──\n\n const handleSubmit = useCallback(\n async (e: React.FormEvent) => {\n e.preventDefault();\n if (!flopay || !elements || isSubmitting || processingRef.current) return;\n\n if (layout !== 'buttons') {\n onButtonClick?.('card');\n }\n setProcessing(true);\n setOverlayStatus('processing');\n updateError(null);\n\n // Track whether we handed off to processPaymentInternal (which manages its own overlay)\n let handedOff = false;\n\n try {\n // Matches checkout/StripeCardForm exactly:\n // 1. createPaymentMethod → 2. createPaymentIntent → 3. confirmCardPayment → 4. onTokenizedBody\n\n // 0. Validate AVS fields — all visible fields are required (except address_line_2).\n // Read from refs for the latest value — state may not have flushed\n // if the user typed and clicked submit in quick succession.\n if (avsConfig) {\n const country = selectedCountryRef.current;\n if (isAVSFieldVisible(avsConfig.postal_code, country) && !zipCodeRef.current.trim()) {\n updateError(getPostalCodeLabel(country) + ' is required');\n return;\n }\n if (isAVSFieldVisible(avsConfig.address_line_1, country) && !addressLine1Ref.current.trim()) {\n updateError('Street address is required');\n return;\n }\n if (isAVSFieldVisible(avsConfig.city, country) && !cityRef.current.trim()) {\n updateError('City is required');\n return;\n }\n if (isAVSFieldVisible(avsConfig.state, country) && !stateRef.current.trim()) {\n updateError(getStateLabel(country) + ' is required');\n return;\n }\n }\n\n // 1. Validate elements\n const submitResult = await flopay.submitElements();\n if (submitResult.error) {\n updateError(submitResult.error.message);\n onError?.(submitResult.error);\n return;\n }\n\n // 2. Create PaymentMethod (tokenize card + AVS billing_details)\n // Only include fields that are currently visible for the selected country.\n const billingAddress: Record<string, string> = {};\n const cc = selectedCountryRef.current;\n const avsCountry = enableAVS ? cc : resolvedAccount.country;\n if (avsCountry) billingAddress['country'] = avsCountry;\n if (avsConfig && isAVSFieldVisible(avsConfig.postal_code, cc) && zipCodeRef.current.trim()) {\n billingAddress['postal_code'] = zipCodeRef.current.trim();\n } else if (!avsConfig && resolvedAccount.zip) {\n billingAddress['postal_code'] = resolvedAccount.zip;\n }\n if (avsConfig && isAVSFieldVisible(avsConfig.address_line_1, cc) && addressLine1Ref.current.trim()) billingAddress['line1'] = addressLine1Ref.current.trim();\n if (avsConfig && isAVSFieldVisible(avsConfig.address_line_2, cc) && addressLine2Ref.current.trim()) billingAddress['line2'] = addressLine2Ref.current.trim();\n if (avsConfig && isAVSFieldVisible(avsConfig.city, cc) && cityRef.current.trim()) billingAddress['city'] = cityRef.current.trim();\n if (avsConfig && isAVSFieldVisible(avsConfig.state, cc) && stateRef.current.trim()) {\n billingAddress['state'] = stateRef.current.trim();\n } else if (\n avsConfig\n && isAVSFieldVisible(avsConfig.address_line_1, cc)\n && !isAVSFieldVisible(avsConfig.state, cc)\n && isAVSFieldVisible(avsConfig.postal_code, cc)\n ) {\n const derivedSubmitState = getStateFromPostalCode(cc, zipCodeRef.current.trim());\n if (derivedSubmitState) billingAddress['state'] = derivedSubmitState;\n }\n\n const billingDetails = {\n ...(resolvedAccount.email ? { email: resolvedAccount.email } : {}),\n ...(fullName.trim() ? { name: fullName.trim() } : {}),\n ...(Object.keys(billingAddress).length > 0 ? { address: billingAddress } : {}),\n };\n const pmResult = await flopay.createPaymentMethod(billingDetails);\n if (pmResult.error || !pmResult.paymentMethodId) {\n updateError(pmResult.error?.message ?? 'Failed to create payment method.');\n return;\n }\n\n if (!sessionId || !resolvedAccount.email) {\n throw new FloPayError('Missing sessionId or email', 'validation_error');\n }\n\n // 3. Create PaymentIntent via billing API (backend uses capture_method: 'manual')\n const intentResponse = await fetch(`${baseUrl}/v1/checkouts/payments/intents`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n sessionId,\n email: resolvedAccount.email,\n paymentMethodType: pmResult.paymentMethodId,\n isPaypal: false,\n }),\n });\n\n if (!intentResponse.ok) {\n const intentError = await buildFloPayApiErrorFromResponse(\n intentResponse,\n 'Failed to create payment intent',\n );\n setOverlayStatus('error');\n updateError(intentError.message);\n onError?.(intentError);\n emitDecline('card', intentError);\n await new Promise((r) => setTimeout(r, PROCESSING_OVERLAY_ERROR_DELAY_MS));\n return;\n }\n\n const intentJson = await intentResponse.json() as { data?: { id?: string } };\n const intentClientSecret = intentJson.data?.id;\n if (!intentClientSecret) throw new FloPayError('No client_secret in payment intent response', 'api_error');\n\n // 4. Confirm card payment (handles 3DS automatically via Stripe)\n const confirmResult = await flopay.confirmCardPayment({\n clientSecret: intentClientSecret,\n paymentMethodId: pmResult.paymentMethodId,\n });\n\n if (confirmResult.error) {\n setOverlayStatus('error');\n updateError(confirmResult.error.message);\n onError?.(confirmResult.error);\n emitDecline('card', confirmResult.error);\n await new Promise((r) => setTimeout(r, PROCESSING_OVERLAY_ERROR_DELAY_MS));\n return;\n }\n\n const rawProvider = typeof flopay.getRawProvider === 'function' ? flopay.getRawProvider() : null;\n const confirmedPaymentIntent = await retrievePaymentIntentFromProvider(\n rawProvider,\n intentClientSecret,\n );\n const paymentIntentId = confirmResult.paymentIntentId ?? confirmedPaymentIntent?.id;\n const paymentMethodId =\n confirmResult.paymentMethodId\n ?? resolvePaymentIntentPaymentMethodId(confirmedPaymentIntent)\n ?? pmResult.paymentMethodId;\n\n if (!paymentIntentId) {\n const error = new FloPayError('No payment intent returned after confirmation.', 'api_error');\n setOverlayStatus('error');\n updateError(error.message);\n onError?.(error);\n await new Promise((r) => setTimeout(r, PROCESSING_OVERLAY_ERROR_DELAY_MS));\n return;\n }\n\n // 5. Send PM + PI to processPaymentInternal (or parent via onTokenizedBody)\n // In self-contained mode, processPaymentInternal manages overlay lifecycle.\n handedOff = isSelfContained;\n dispatchTokenizedBody({\n id: paymentMethodId,\n type: 'card',\n threeDSecureActionResultTokenId: paymentIntentId,\n originalPaymentMethodId: pmResult.paymentMethodId,\n });\n } catch (err) {\n setOverlayStatus('error');\n updateError(err instanceof Error ? err.message : 'An unexpected error occurred');\n await new Promise((r) => setTimeout(r, PROCESSING_OVERLAY_ERROR_DELAY_MS));\n } finally {\n if (!handedOff) {\n setProcessing(false);\n setOverlayStatus(null);\n }\n }\n },\n [flopay, elements, isSubmitting, sessionId, resolvedAccount.email, baseUrl, isSelfContained, dispatchTokenizedBody, onButtonClick, onError, updateError, emitDecline, layout],\n );\n\n const isReady = flopay !== null && elements !== null;\n\n if (!isReady) {\n return <div data-testid=\"flopay-loading\" aria-busy=\"true\">Loading payment form...</div>;\n }\n\n const isButtons = layout === 'buttons';\n const resolvedBorder = isButtons ? (bStyles.cardInputBorder ?? '#e5e7eb') : '#A4A4FF';\n const cardBg = isButtons ? ((bStyles.cardFormContainer?.backgroundColor as string) ?? 'white') : '#EDEDFF';\n const cardInputBg = isButtons ? (bStyles.cardInputBackground ?? 'white') : 'white';\n const hideBackButtonLabel = isEmptySlotContent(cardBackButtonContent);\n const hideTitle = isEmptySlotContent(cardTitleContent);\n const nameInputOverrides = isButtons ? bStyles.nameInput : undefined;\n const resolvedInputFontSize = bStyles.cardInputFontSize\n ?? toCssSize(nameInputOverrides?.fontSize)\n ?? '16px';\n const resolvedInputFontFamily = typeof nameInputOverrides?.fontFamily === 'string'\n ? nameInputOverrides.fontFamily\n : 'Poppins, sans-serif';\n const resolvedInputFontWeight = toCssWeight(nameInputOverrides?.fontWeight) ?? 400;\n const resolvedInputColor = bStyles.cardInputColor\n ?? (typeof nameInputOverrides?.color === 'string' ? nameInputOverrides.color : undefined)\n ?? '#262833';\n const resolvedPlaceholderColor = bStyles.cardInputPlaceholderColor ?? '#9ca3af';\n const sharedInputTypography: React.CSSProperties = {\n fontSize: resolvedInputFontSize,\n fontFamily: resolvedInputFontFamily,\n fontWeight: resolvedInputFontWeight,\n color: resolvedInputColor,\n WebkitFontSmoothing: 'antialiased',\n MozOsxFontSmoothing: 'grayscale',\n };\n const sharedInputPlaceholderVars = {\n '--flopay-input-placeholder-color': resolvedPlaceholderColor,\n '--flopay-input-font-size': resolvedInputFontSize,\n '--flopay-input-font-family': resolvedInputFontFamily,\n '--flopay-input-font-weight': String(resolvedInputFontWeight),\n } as React.CSSProperties;\n\n // Stripe Element style — keeps the iframe typography aligned with the plain text inputs.\n const stripeElementStyle = {\n style: {\n base: {\n ...sharedInputTypography,\n fontSmoothing: 'antialiased',\n '::placeholder': {\n color: resolvedPlaceholderColor,\n fontSize: resolvedInputFontSize,\n fontFamily: resolvedInputFontFamily,\n fontWeight: resolvedInputFontWeight,\n },\n },\n invalid: { color: '#ef4444' },\n },\n };\n\n // ── Card fields block (shared between both layouts) ──\n const cardFormBlock = (\n <div style={{\n backgroundColor: cardBg, borderRadius: '8px',\n padding: isButtons ? '0' : '1rem',\n ...(isButtons ? bStyles.cardFormContainer as React.CSSProperties : {}),\n ...(isButtons ? { padding: bStyles.cardFormContainer?.padding ?? '0' } : {}),\n ...sharedInputPlaceholderVars,\n }}>\n <style>{`\n .flopay-shared-input::placeholder {\n color: var(--flopay-input-placeholder-color);\n opacity: 1;\n font-size: var(--flopay-input-font-size);\n font-family: var(--flopay-input-font-family);\n font-weight: var(--flopay-input-font-weight);\n }\n `}</style>\n {/* Header: back button + title on same row (buttons layout) */}\n {isButtons && showCardForm && (\n <div style={{\n display: 'flex', alignItems: 'center', padding: '0.75rem 0 0.625rem',\n }}>\n <button\n type=\"button\"\n onClick={collapseToButtons}\n style={{\n display: 'inline-flex', alignItems: 'center', gap: hideBackButtonLabel ? 0 : '0.5rem',\n background: 'none', border: 'none', cursor: 'pointer',\n color: '#4b5563', fontSize: bStyles.backButtonFontSize ?? '0.85rem', fontWeight: 500,\n padding: 0, transition: 'color 0.15s', flexShrink: 0,\n ...bStyles.backButton as React.CSSProperties,\n }}\n aria-label=\"Back to payment methods\"\n >\n <span style={{\n display: 'inline-flex', alignItems: 'center', justifyContent: 'center',\n width: 28, height: 28, borderRadius: '50%',\n backgroundColor: '#f3f4f6', transition: 'background-color 0.15s',\n ...bStyles.backButtonIcon as React.CSSProperties,\n }}>\n <svg width=\"14\" height=\"14\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2.5\" strokeLinecap=\"round\" strokeLinejoin=\"round\">\n <path d=\"M15 18l-6-6 6-6\" />\n </svg>\n </span>\n <BackButtonContentSlot content={cardBackButtonContent} />\n </button>\n {hideTitle ? (\n <div style={{ flex: 1 }} />\n ) : (\n <div style={{\n flex: 1, textAlign: 'center', fontWeight: 600,\n fontSize: bStyles.titleFontSize ?? '1.05rem',\n color: '#262833', paddingRight: 80,\n ...bStyles.title as React.CSSProperties,\n }}>\n <TitleContentSlot content={cardTitleContent} />\n </div>\n )}\n </div>\n )}\n\n {/* Title (default layout only) */}\n {!isButtons && !hideTitle && (\n <div style={{ textAlign: 'center', fontWeight: 600, fontSize: '1.1rem', padding: '0.5rem 0', color: '#262833' }}>\n <TitleContentSlot content={cardTitleContent} />\n </div>\n )}\n\n {/* Card Number */}\n <div style={{\n backgroundColor: cardInputBg, border: `1px solid ${resolvedBorder}`,\n borderTopLeftRadius: '8px', borderTopRightRadius: '8px', padding: '10px',\n }}>\n <CardNumberElement onReady={() => setFormReady(true)} options={stripeElementStyle} />\n </div>\n\n {/* Expiry + CVC */}\n <div style={{ display: 'flex' }}>\n <div style={{\n flex: 1, backgroundColor: cardInputBg, border: `1px solid ${resolvedBorder}`,\n borderTop: 'none', borderRight: 'none',\n borderBottomLeftRadius: '8px', padding: '10px',\n }}>\n <CardExpiryElement options={stripeElementStyle} />\n </div>\n <div style={{\n flex: 1, backgroundColor: cardInputBg, border: `1px solid ${resolvedBorder}`,\n borderTop: 'none', borderBottomRightRadius: '8px', padding: '10px',\n }}>\n <CardCvcElement options={stripeElementStyle} />\n </div>\n </div>\n\n {/* Full Name */}\n <div style={{\n backgroundColor: cardInputBg, border: `1px solid ${resolvedBorder}`,\n borderRadius: '8px', marginTop: '0.5rem', padding: '10px',\n }}>\n <input\n className=\"flopay-shared-input\"\n placeholder=\"Full Name on Card\"\n autoComplete=\"cc-name\"\n value={fullName}\n onChange={(e) => handleNameChange(e.target.value)}\n disabled={isSubmitting}\n required\n style={{\n width: '100%', border: 'none', outline: 'none', background: 'transparent',\n ...sharedInputTypography,\n ...(isButtons && bStyles.nameInput ? bStyles.nameInput as React.CSSProperties : {}),\n }}\n />\n </div>\n\n {/* AVS Address Fields */}\n {avsConfig && (() => {\n const cc = selectedCountry;\n const inputWrapStyle = (extraStyle?: Record<string, string | number>): React.CSSProperties => ({\n backgroundColor: cardInputBg, border: `1px solid ${resolvedBorder}`,\n borderRadius: '8px', marginTop: '0.5rem', padding: '10px',\n ...(isButtons && extraStyle ? extraStyle as React.CSSProperties : {}),\n });\n const inputFieldStyle = (): React.CSSProperties => ({\n width: '100%', border: 'none', outline: 'none', background: 'transparent',\n ...sharedInputTypography,\n ...(isButtons && bStyles.nameInput ? bStyles.nameInput as React.CSSProperties : {}),\n });\n const stateOpts = getStateOptions(cc);\n\n return (\n <>\n {/* Street Address (line 1) */}\n {isAVSFieldVisible(avsConfig.address_line_1, cc) && (\n <div style={inputWrapStyle(bStyles.addressLine1Input)}>\n <input\n className=\"flopay-shared-input\"\n placeholder=\"Street Address (e.g. 123 Main St)\"\n autoComplete=\"address-line1\"\n value={addressLine1}\n onChange={(e) => { addressLine1Ref.current = e.target.value; setAddressLine1(e.target.value); }}\n disabled={isSubmitting}\n required\n data-testid=\"flopay-address-line1\"\n style={inputFieldStyle()}\n />\n </div>\n )}\n\n {/* Apt, Suite, etc. (line 2) */}\n {isAVSFieldVisible(avsConfig.address_line_2, cc) && (\n <div style={inputWrapStyle(bStyles.addressLine2Input)}>\n <input\n className=\"flopay-shared-input\"\n placeholder=\"Apt, Suite, Unit (optional)\"\n autoComplete=\"address-line2\"\n value={addressLine2}\n onChange={(e) => { addressLine2Ref.current = e.target.value; setAddressLine2(e.target.value); }}\n disabled={isSubmitting}\n data-testid=\"flopay-address-line2\"\n style={inputFieldStyle()}\n />\n </div>\n )}\n\n {/* City + State row */}\n {(isAVSFieldVisible(avsConfig.city, cc) || isAVSFieldVisible(avsConfig.state, cc)) && (\n <div style={{\n display: 'flex', gap: '0', marginTop: '0.5rem',\n }}>\n {isAVSFieldVisible(avsConfig.city, cc) && (\n <div style={{\n flex: 1, backgroundColor: cardInputBg, border: `1px solid ${resolvedBorder}`,\n padding: '10px',\n borderTopLeftRadius: '8px', borderBottomLeftRadius: '8px',\n ...(isAVSFieldVisible(avsConfig.state, cc) ? { borderRight: 'none', borderTopRightRadius: 0, borderBottomRightRadius: 0 } : { borderRadius: '8px' }),\n ...(isButtons && bStyles.cityInput ? bStyles.cityInput as React.CSSProperties : {}),\n }}>\n <input\n className=\"flopay-shared-input\"\n placeholder=\"City\"\n autoComplete=\"address-level2\"\n value={city}\n onChange={(e) => { cityRef.current = e.target.value; setCity(e.target.value); }}\n disabled={isSubmitting}\n required\n data-testid=\"flopay-city\"\n style={inputFieldStyle()}\n />\n </div>\n )}\n {isAVSFieldVisible(avsConfig.state, cc) && (\n <div style={{\n flex: 1, backgroundColor: cardInputBg, border: `1px solid ${resolvedBorder}`,\n padding: '10px',\n borderTopRightRadius: '8px', borderBottomRightRadius: '8px',\n ...(isAVSFieldVisible(avsConfig.city, cc) ? { borderTopLeftRadius: 0, borderBottomLeftRadius: 0 } : { borderRadius: '8px' }),\n ...(isButtons && bStyles.stateInput ? bStyles.stateInput as React.CSSProperties : {}),\n }}>\n {stateOpts ? (\n <select\n value={stateValue}\n onChange={(e) => { stateRef.current = e.target.value; setStateValue(e.target.value); }}\n disabled={isSubmitting}\n autoComplete=\"address-level1\"\n required\n data-testid=\"flopay-state\"\n style={{ ...inputFieldStyle(), cursor: 'pointer' }}\n >\n <option value=\"\">{getStateLabel(cc)}</option>\n {stateOpts.map((s) => (\n <option key={s.code} value={s.code}>{s.name}</option>\n ))}\n </select>\n ) : (\n <input\n className=\"flopay-shared-input\"\n placeholder={getStateLabel(cc)}\n autoComplete=\"address-level1\"\n value={stateValue}\n onChange={(e) => { stateRef.current = e.target.value; setStateValue(e.target.value); }}\n disabled={isSubmitting}\n required\n data-testid=\"flopay-state\"\n style={inputFieldStyle()}\n />\n )}\n </div>\n )}\n </div>\n )}\n\n {/* Country + ZIP/Postcode row */}\n {(isAVSFieldVisible(avsConfig.country, cc) || isAVSFieldVisible(avsConfig.postal_code, cc)) && (\n <div style={{\n display: 'flex',\n flexDirection: avsLayoutProp === 'column' ? 'column' : 'row',\n gap: avsLayoutProp === 'column' ? '0.5rem' : '0',\n marginTop: '0.5rem',\n }}>\n {isAVSFieldVisible(avsConfig.country, cc) && (\n <div style={{\n flex: avsLayoutProp === 'row' ? 1 : undefined,\n backgroundColor: cardInputBg, border: `1px solid ${resolvedBorder}`,\n padding: '10px',\n ...(avsLayoutProp === 'row' && isAVSFieldVisible(avsConfig.postal_code, cc)\n ? { borderRadius: '0', borderTopLeftRadius: '8px', borderBottomLeftRadius: '8px', borderRight: 'none' }\n : { borderRadius: '8px' }),\n ...(isButtons && bStyles.countrySelect ? bStyles.countrySelect as React.CSSProperties : {}),\n }}>\n <select\n value={selectedCountry}\n onChange={(e) => {\n selectedCountryRef.current = e.target.value;\n setSelectedCountry(e.target.value);\n onCountryChange?.(e.target.value);\n // Reset state when country changes (different state lists)\n stateRef.current = '';\n setStateValue('');\n }}\n disabled={isSubmitting}\n autoComplete=\"country\"\n data-testid=\"flopay-country\"\n style={{ ...inputFieldStyle(), cursor: 'pointer' }}\n >\n {COUNTRY_OPTIONS.map((c) => (\n <option key={c.code} value={c.code}>{c.flag} {c.name}</option>\n ))}\n </select>\n </div>\n )}\n {isAVSFieldVisible(avsConfig.postal_code, cc) && (\n <div style={{\n flex: avsLayoutProp === 'row' ? 1 : undefined,\n backgroundColor: cardInputBg, border: `1px solid ${resolvedBorder}`,\n padding: '10px',\n ...(avsLayoutProp === 'row' && isAVSFieldVisible(avsConfig.country, cc)\n ? { borderRadius: '0', borderTopRightRadius: '8px', borderBottomRightRadius: '8px' }\n : { borderRadius: '8px' }),\n ...(isButtons && bStyles.zipInput ? bStyles.zipInput as React.CSSProperties : {}),\n }}>\n <input\n className=\"flopay-shared-input\"\n placeholder={getPostalCodeLabel(selectedCountry)}\n autoComplete=\"postal-code\"\n value={zipCode}\n onChange={(e) => {\n zipCodeRef.current = e.target.value;\n setZipCode(e.target.value);\n onZipChange?.(e.target.value);\n }}\n disabled={isSubmitting}\n required\n data-testid=\"flopay-zip\"\n style={inputFieldStyle()}\n />\n </div>\n )}\n </div>\n )}\n </>\n );\n })()}\n\n {displayError && (\n <div role=\"alert\" data-testid=\"flopay-error\" style={{\n margin: '0.75rem 0', padding: '0.625rem 0.875rem',\n background: '#FEF2F2', border: '1px solid #FECACA', borderRadius: '8px',\n color: '#991B1B', fontSize: '0.85rem', fontWeight: 600,\n display: 'flex', alignItems: 'center', gap: '0.5rem',\n ...(isButtons && bStyles.errorBanner ? bStyles.errorBanner as React.CSSProperties : {}),\n }}>\n <svg width=\"16\" height=\"16\" viewBox=\"0 0 24 24\" fill=\"none\" style={{ flexShrink: 0 }}>\n <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\" />\n </svg>\n {displayError}\n </div>\n )}\n\n {children ?? (\n <button\n type=\"submit\"\n disabled={!formReady || isSubmitting}\n data-testid=\"flopay-submit\"\n style={{\n width: '100%', padding: '0.875rem', marginTop: '1rem',\n backgroundColor: '#4A49FF', color: 'white', border: 'none',\n borderRadius: '8px',\n fontSize: (isButtons && bStyles.submitButtonFontSize) ? bStyles.submitButtonFontSize : '1rem',\n fontWeight: 600,\n cursor: !formReady || isSubmitting ? 'not-allowed' : 'pointer',\n opacity: !formReady || isSubmitting ? 0.5 : 1,\n ...((isButtons ? bStyles.submitButton : {}) as React.CSSProperties),\n }}\n >\n {isSubmitting ? 'PROCESSING...' : submitLabel}\n </button>\n )}\n\n {/* Security footer — only in default layout */}\n {!isButtons && showSecurityFooter && (\n <div style={{\n backgroundColor: '#EFF9F0', borderRadius: '8px', padding: '0.75rem',\n marginTop: '0.75rem', textAlign: 'center', fontSize: '0.85rem',\n fontWeight: 600, color: '#7DAD3A',\n }}>\n Secure Card Checkout\n </div>\n )}\n </div>\n );\n\n // ── Buttons layout ──\n if (layout === 'buttons') {\n const isButtonsView = viewState === 'buttons' || viewState === 'expanding';\n const isCardView = viewState === 'expanding' || viewState === 'card' || viewState === 'collapsing';\n const cardButtonSizing = cardButtonContent === undefined\n ? { boxSizing: 'border-box' as const, height: DEFAULT_BUTTONS_LAYOUT_BUTTON_HEIGHT, padding: '0 1rem' }\n : { padding: '0.9rem 1rem' };\n\n const buttonsAnim = viewState === 'expanding'\n ? `flopay-buttons-exit ${TRANSITION_MS}ms cubic-bezier(0.4, 0, 0.2, 1) both`\n : viewState === 'collapsing'\n ? `flopay-buttons-enter ${TRANSITION_MS}ms cubic-bezier(0, 0, 0.2, 1) both`\n : undefined;\n\n const cardAnim = viewState === 'expanding'\n ? `flopay-card-enter ${TRANSITION_MS}ms cubic-bezier(0, 0, 0.2, 1) both`\n : viewState === 'collapsing'\n ? `flopay-card-exit ${TRANSITION_MS}ms cubic-bezier(0.4, 0, 0.2, 1) both`\n : undefined;\n\n return (\n <form onSubmit={handleSubmit} className={className} style={{ position: 'relative' }}>\n <FloPayKeyframes />\n {overlayStatus && <ProcessingOverlay status={overlayStatus} errorMessage={displayError} />}\n\n {/* Container — uses grid overlap so both views can coexist during transition */}\n <div style={{ display: 'grid' }}>\n\n {/* Payment method buttons — always mounted to preserve PayPal/wallet Elements */}\n <div style={{\n gridArea: '1 / 1',\n display: 'flex', flexDirection: 'column', gap: '0.5rem',\n // When card form is showing (and not transitioning), hide but keep mounted\n ...(!isButtonsView && !buttonsAnim ? { visibility: 'hidden' as const, position: 'absolute' as const, pointerEvents: 'none' as const, width: '100%' } : {}),\n ...(buttonsAnim ? { animation: buttonsAnim, pointerEvents: 'none' as const } : {}),\n }}>\n {/* PayPal — hidden when unsupported or no paypalPublishableKey is configured */}\n {shouldRenderPayPal && (\n <StripeElements stripe={paypalStripeInstance} options={paypalOptions}>\n <PayPalButtonInner\n sessionId={sessionId}\n email={resolvedAccount.email}\n billingApiUrl={resolvedBillingApiUrl}\n onTokenizedBody={dispatchTokenizedBody}\n onErrorChange={updateError}\n isProcessing={isSubmitting}\n onButtonClick={onButtonClick}\n onDecline={onDecline}\n runBeforeButtonClick={runBeforeButtonClick}\n onLoadStateChange={setPaypalLoadState}\n />\n </StripeElements>\n )}\n\n {/* Wallets (Apple Pay / Google Pay) */}\n {shouldRenderWallets ? (\n <StripeElements stripe={stripeInstance} options={walletOptions}>\n <WalletButtonInner\n sessionId={sessionId}\n email={resolvedAccount.email}\n billingApiUrl={resolvedBillingApiUrl}\n showApplePay={showApplePay}\n showGooglePay={showGooglePay}\n onTokenizedBody={dispatchTokenizedBody}\n onErrorChange={updateError}\n onButtonClick={onButtonClick}\n onDecline={onDecline}\n runBeforeButtonClick={runBeforeButtonClick}\n onLoadStateChange={setWalletLoadState}\n />\n </StripeElements>\n ) : shouldShowWallets ? (\n <div style={{ height: DEFAULT_BUTTONS_LAYOUT_BUTTON_HEIGHT, borderRadius: 8, background: '#e5e7eb', animation: 'flopay-pulse 1.5s ease-in-out infinite' }} />\n ) : null}\n\n {/* Credit / Debit Card button */}\n <button\n type=\"button\"\n onClick={async () => {\n if (isSubmitting) return;\n const beforeClick = await runBeforeButtonClick('card');\n if (!beforeClick.proceed) return;\n onButtonClick?.('card');\n expandToCard();\n }}\n disabled={isSubmitting}\n style={{\n width: '100%',\n ...cardButtonSizing,\n backgroundColor: 'white', color: '#262833',\n border: '1px solid #d1d5db', borderRadius: '8px',\n fontSize: bStyles.cardButtonFontSize ?? '0.95rem', fontWeight: 600,\n cursor: isSubmitting ? 'not-allowed' : 'pointer', display: 'flex',\n alignItems: 'center', justifyContent: 'center', gap: '0.625rem',\n transition: 'border-color 0.2s, box-shadow 0.2s, transform 0.1s',\n boxShadow: '0 1px 2px rgba(0,0,0,0.04)',\n position: 'relative',\n opacity: isSubmitting ? 0.6 : 1,\n ...bStyles.cardButton as React.CSSProperties,\n }}\n onMouseDown={(e) => { e.currentTarget.style.transform = 'scale(0.985)'; }}\n onMouseUp={(e) => { e.currentTarget.style.transform = 'scale(1)'; }}\n >\n <CardButtonContentSlot content={cardButtonContent} />\n </button>\n\n {displayError && viewState === 'buttons' && (\n <div role=\"alert\" data-testid=\"flopay-error\" style={{\n margin: '0.25rem 0', padding: '0.625rem 0.875rem',\n background: '#FEF2F2', border: '1px solid #FECACA', borderRadius: '8px',\n color: '#991B1B', fontSize: '0.85rem', fontWeight: 600,\n display: 'flex', alignItems: 'center', gap: '0.5rem',\n ...(bStyles.errorBanner ? bStyles.errorBanner as React.CSSProperties : {}),\n }}>\n <svg width=\"16\" height=\"16\" viewBox=\"0 0 24 24\" fill=\"none\" style={{ flexShrink: 0 }}>\n <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\" />\n </svg>\n {displayError}\n </div>\n )}\n </div>\n\n {/* Card form */}\n {isCardView && (\n <div style={{\n gridArea: '1 / 1',\n ...(cardAnim ? { animation: cardAnim } : {}),\n ...(viewState === 'collapsing' ? { pointerEvents: 'none' as const } : {}),\n }}>\n {cardFormBlock}\n </div>\n )}\n </div>\n </form>\n );\n }\n\n // ── Default layout ──\n return (\n <form onSubmit={handleSubmit} className={className} style={{ position: 'relative' }}>\n <FloPayKeyframes />\n {overlayStatus && <ProcessingOverlay status={overlayStatus} errorMessage={displayError} />}\n\n {/* Wallet buttons (Apple Pay / Google Pay) — own Stripe Elements instance */}\n {shouldRenderWallets && (\n <StripeElements stripe={stripeInstance} options={walletOptions}>\n <WalletButtonInner\n sessionId={sessionId}\n email={resolvedAccount.email}\n billingApiUrl={resolvedBillingApiUrl}\n showApplePay={showApplePay}\n showGooglePay={showGooglePay}\n onTokenizedBody={dispatchTokenizedBody}\n onErrorChange={updateError}\n onDecline={onDecline}\n onLoadStateChange={setWalletLoadState}\n />\n </StripeElements>\n )}\n\n {/* PayPal — own Stripe Elements instance on the dedicated PayPal Stripe account */}\n {shouldRenderPayPal && (\n <StripeElements stripe={paypalStripeInstance} options={paypalOptions}>\n <PayPalButtonInner\n sessionId={sessionId}\n email={resolvedAccount.email}\n billingApiUrl={resolvedBillingApiUrl}\n onTokenizedBody={dispatchTokenizedBody}\n onErrorChange={updateError}\n isProcessing={isSubmitting}\n onDecline={onDecline}\n onLoadStateChange={setPaypalLoadState}\n />\n </StripeElements>\n )}\n\n {/* Divider between wallet/PayPal buttons and card fields */}\n {(shouldDisplayWalletRow || shouldDisplayPayPalRow) && (\n <div style={{\n display: 'flex', alignItems: 'center', gap: '0.75rem',\n margin: '0.5rem 0 0.75rem', color: '#999', fontSize: '0.85rem',\n }}>\n <div style={{ flex: 1, height: 1, backgroundColor: '#ddd' }} />\n <span>or pay with card</span>\n <div style={{ flex: 1, height: 1, backgroundColor: '#ddd' }} />\n </div>\n )}\n\n {cardFormBlock}\n </form>\n );\n}\n","import { useContext } from 'react';\nimport type { FloPay, FloPayElements } from '@flopay/js';\nimport type { CheckoutSession, FloPayError } from '@flopay/shared';\nimport { resolveBillingApiUrl } from '@flopay/shared';\nimport { FloPayContext, CheckoutContext } from './context.js';\nimport type { CheckoutContextValue } from './context.js';\n\n/**\n * Returns the current `FloPay` instance, or `null` if the provider\n * is still loading (i.e. the `loadFloPay()` promise has not resolved yet).\n *\n * Must be called within a `<FloPayProvider>`.\n */\nexport function useFloPay(): FloPay | null {\n const ctx = useContext(FloPayContext);\n return ctx.flopay;\n}\n\n/**\n * Returns the dedicated PayPal `FloPay` instance (loaded with\n * `gatewayData.paypalPublishableKey`), or `null` if PayPal is disabled\n * for this session.\n *\n * Must be called within a `<FloPayProvider>`.\n */\nexport function usePayPalFloPay(): FloPay | null {\n const ctx = useContext(FloPayContext);\n return ctx.paypalFlopay ?? null;\n}\n\n/**\n * Returns the current `FloPayElements` instance, or `null` if the\n * provider is still loading.\n *\n * Must be called within a `<FloPayProvider>`.\n */\nexport function useElements(): FloPayElements | null {\n const ctx = useContext(FloPayContext);\n return ctx.elements;\n}\n\n/** Checkout state exposed by `useCheckout()`. */\nexport interface CheckoutState {\n session: CheckoutSession | null;\n loading: boolean;\n error: FloPayError | null;\n}\n\n/**\n * Returns the current checkout session state.\n *\n * Must be called within a `<CheckoutProvider>` (typically rendered\n * internally by `<CheckoutForm>`).\n */\nexport function useCheckout(): CheckoutState {\n return useContext(CheckoutContext);\n}\n\n/**\n * Returns the resolved billing API URL from the provider context.\n * Falls back to the default `BILLING_API_URL` constant.\n */\nexport function useBillingApiUrl(): string {\n const ctx = useContext(FloPayContext);\n return ctx.billingApiUrl || resolveBillingApiUrl();\n}\n","import React from 'react';\n\nexport type OverlayStatus = 'processing' | 'success' | 'error';\n\nexport const PROCESSING_OVERLAY_SUCCESS_DELAY_MS = 1200;\nexport const PROCESSING_OVERLAY_ERROR_DELAY_MS = 1500;\n\nexport function ProcessingOverlay({\n status,\n errorMessage,\n}: {\n status: OverlayStatus;\n errorMessage?: string | null;\n}) {\n return (\n <div\n data-testid=\"flopay-processing-overlay\"\n data-status={status}\n role=\"dialog\"\n aria-modal=\"true\"\n style={{\n position: 'fixed',\n inset: 0,\n background: 'rgba(0,0,0,0.35)',\n display: 'flex',\n alignItems: 'center',\n justifyContent: 'center',\n zIndex: 1000,\n backdropFilter: 'blur(2px)',\n }}\n >\n <div\n style={{\n background: 'white',\n borderRadius: 12,\n padding: '2rem 2.5rem',\n textAlign: 'center',\n boxShadow: '0 8px 32px rgba(0,0,0,0.18)',\n minWidth: 240,\n display: 'flex',\n flexDirection: 'column',\n alignItems: 'center',\n gap: 16,\n }}\n >\n <div style={{ width: 48, height: 48, position: 'relative' }}>\n {status === 'processing' && (\n <svg\n width=\"48\"\n height=\"48\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n xmlns=\"http://www.w3.org/2000/svg\"\n style={{ animation: 'flopay-spin 0.8s linear infinite' }}\n >\n <circle cx=\"12\" cy=\"12\" r=\"10\" stroke=\"#e5e7eb\" strokeWidth=\"3\" />\n <path d=\"M4 12a8 8 0 018-8v3a5 5 0 00-5 5H4z\" fill=\"#4A49FF\" />\n </svg>\n )}\n {status === 'success' && (\n <div style={{ animation: 'flopay-pop 0.4s cubic-bezier(0.34,1.56,0.64,1)' }}>\n <svg width=\"48\" height=\"48\" viewBox=\"0 0 24 24\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\">\n <circle cx=\"12\" cy=\"12\" r=\"11\" fill=\"#22c55e\" />\n <path\n d=\"M7 12.5l3 3 7-7\"\n stroke=\"white\"\n strokeWidth=\"2.5\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n style={{\n strokeDasharray: 20,\n strokeDashoffset: 20,\n animation: 'flopay-draw 0.4s 0.15s ease forwards',\n }}\n />\n </svg>\n </div>\n )}\n {status === 'error' && (\n <div style={{ animation: 'flopay-shake 0.4s ease' }}>\n <svg width=\"48\" height=\"48\" viewBox=\"0 0 24 24\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\">\n <circle cx=\"12\" cy=\"12\" r=\"11\" fill=\"#ef4444\" />\n <path\n d=\"M8 8l8 8M16 8l-8 8\"\n stroke=\"white\"\n strokeWidth=\"2.5\"\n strokeLinecap=\"round\"\n style={{\n strokeDasharray: 12,\n strokeDashoffset: 12,\n animation: 'flopay-draw 0.3s 0.1s ease forwards',\n }}\n />\n </svg>\n </div>\n )}\n </div>\n <span\n style={{\n fontSize: 14,\n fontWeight: 600,\n letterSpacing: '0.05em',\n color: status === 'success' ? '#16a34a' : status === 'error' ? '#dc2626' : '#374151',\n }}\n >\n {status === 'processing' && 'PROCESSING...'}\n {status === 'success' && 'PAYMENT SUCCESSFUL'}\n {status === 'error' && 'PAYMENT FAILED'}\n </span>\n {status === 'success' && (\n <p\n style={{\n fontSize: 13,\n color: '#6b7280',\n fontWeight: 400,\n maxWidth: 260,\n lineHeight: 1.4,\n margin: 0,\n }}\n >\n You will be automatically redirected, do not close or navigate away from this window.\n </p>\n )}\n {status === 'error' && errorMessage && (\n <p\n style={{\n fontSize: 13,\n color: '#6b7280',\n fontWeight: 400,\n maxWidth: 260,\n lineHeight: 1.4,\n margin: 0,\n }}\n >\n {errorMessage}\n </p>\n )}\n <style>{`\n @keyframes flopay-spin { to { transform: rotate(360deg); } }\n @keyframes flopay-pop { 0% { transform: scale(0); } 100% { transform: scale(1); } }\n @keyframes flopay-draw { to { stroke-dashoffset: 0; } }\n @keyframes flopay-shake { 0%,100% { transform: translateX(0); } 20%,60% { transform: translateX(-4px); } 40%,80% { transform: translateX(4px); } }\n `}</style>\n </div>\n </div>\n );\n}\n","import type {\n CheckoutAccount,\n CheckoutButtonMethod,\n CheckoutMode,\n CheckoutSession,\n DeclineEvent,\n InlineSessionDraft,\n InlineSessionParams,\n InlineSessionPatch,\n PaymentResult,\n TokenizedBody,\n} from '@flopay/shared';\nimport { FloPayError } from '@flopay/shared';\n\nexport function mergeInlineSessionPatches(\n base: InlineSessionPatch | undefined,\n patch: InlineSessionPatch | undefined,\n): InlineSessionPatch | undefined {\n if (!patch) return base;\n if (!base) return patch;\n\n return {\n account: { ...(base.account ?? {}), ...(patch.account ?? {}) },\n couponCodes: patch.couponCodes ?? base.couponCodes,\n tagsData: {\n ...(base.tagsData ?? {}),\n ...(patch.tagsData ?? {}),\n },\n utmMetadata: patch.utmMetadata ?? base.utmMetadata,\n };\n}\n\nexport function mergeInlineSessionPatch(\n params: InlineSessionDraft,\n patch: InlineSessionPatch | undefined,\n): InlineSessionDraft {\n if (!patch) return params;\n\n return {\n ...params,\n account: {\n ...params.account,\n ...(patch.account ?? {}),\n },\n couponCodes: patch.couponCodes ?? params.couponCodes,\n tagsData: {\n ...(params.tagsData ?? {}),\n ...(patch.tagsData ?? {}),\n },\n utmMetadata: patch.utmMetadata ?? params.utmMetadata,\n };\n}\n\nexport function buildSyntheticSession(\n params: InlineSessionDraft,\n checkoutModeOverride?: CheckoutMode,\n): CheckoutSession {\n const totalAmount = [\n ...(params.items ?? []).map((item) => (item.overrideAmount ?? item.totalAmount) ?? 0),\n ...(params.subscriptions ?? []).map((subscription) => (subscription.overrideAmount ?? subscription.totalAmount) ?? 0),\n ].reduce((sum, value) => sum + value, 0);\n const currency = params.items?.[0]?.currency\n ?? params.subscriptions?.[0]?.currency\n ?? 'USD';\n\n return {\n id: '',\n clientSecret: '',\n mode: 'payment',\n amount: Math.round(totalAmount * 100),\n currency,\n status: 'open',\n customer: {\n id: params.account.userId,\n email: params.account.email ?? '',\n firstName: params.account.firstName,\n lastName: params.account.lastName,\n gender: params.account.gender ?? undefined,\n city: params.account.city ?? undefined,\n state: params.account.state ?? undefined,\n country: params.account.country ?? undefined,\n zip: params.account.zip ?? undefined,\n },\n successUrl: params.successUrl,\n cancelUrl: params.cancelUrl,\n checkoutMode: (checkoutModeOverride ?? params.checkoutMode ?? 'full') as CheckoutMode,\n items: (params.items ?? []).map((item, idx) => ({\n uuid: `synthetic-item-${idx}`,\n checkoutSessionId: '',\n providerItemId: item.providerItemId,\n providerItemName: item.providerItemName ?? item.providerItemId,\n quantity: item.quantity ?? 1,\n totalAmount: item.totalAmount,\n overrideAmount: item.overrideAmount ?? null,\n currency: item.currency ?? currency,\n })),\n subscriptions: (params.subscriptions ?? []).map((subscription, idx) => ({\n uuid: `synthetic-sub-${idx}`,\n checkoutSessionId: '',\n providerPlanId: subscription.providerPlanId,\n providerPlanName: subscription.providerPlanName ?? subscription.providerPlanId,\n quantity: subscription.quantity ?? 1,\n totalAmount: subscription.totalAmount,\n overrideAmount: subscription.overrideAmount ?? null,\n currency: subscription.currency ?? currency,\n })),\n };\n}\n\nexport function ensureInlineSessionReady(\n params: InlineSessionDraft,\n): asserts params is InlineSessionParams {\n if (!params.account.email?.trim()) {\n throw new FloPayError(\n 'Email is required before continuing with card checkout.',\n 'validation_error',\n { param: 'createSession.account.email' },\n );\n }\n}\n\nexport function splitFullName(name: string | null | undefined): {\n firstName?: string;\n lastName?: string;\n} {\n const parts = name?.trim().split(/\\s+/).filter(Boolean) ?? [];\n if (parts.length === 0) return {};\n return {\n firstName: parts[0],\n lastName: parts.length > 1 ? parts.slice(1).join(' ') : undefined,\n };\n}\n\nexport function mergeAccountPatch<T extends {\n userId?: string;\n email?: string;\n firstName?: string;\n lastName?: string;\n country?: string | null;\n zip?: string | null;\n}>(\n base: T,\n patch: Partial<CheckoutAccount> | undefined,\n): T {\n if (!patch) return base;\n return {\n ...base,\n ...patch,\n };\n}\n\nexport function buildDeclineEvent(\n method: CheckoutButtonMethod,\n input: string | FloPayError,\n overrides?: {\n code?: string;\n declineCode?: string;\n },\n): DeclineEvent {\n const message = typeof input === 'string' ? input : input.message;\n const code = typeof input === 'string' ? overrides?.code : overrides?.code ?? input.code;\n const declineCode = typeof input === 'string'\n ? overrides?.declineCode\n : overrides?.declineCode ?? input.declineCode;\n\n return {\n method,\n message,\n ...(code ? { code } : {}),\n ...(declineCode ? { declineCode } : {}),\n };\n}\n\ntype ApiErrorPayload = Record<string, unknown> | null;\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null;\n}\n\nfunction readString(payload: ApiErrorPayload, key: string): string | undefined {\n const value = payload?.[key];\n return typeof value === 'string' && value.trim() ? value : undefined;\n}\n\nexport function buildFloPayApiError(\n payload: ApiErrorPayload,\n fallbackMessage: string,\n): FloPayError {\n const nestedError = isRecord(payload?.error) ? payload.error : null;\n const message =\n readString(payload, 'message') ??\n readString(nestedError, 'message') ??\n fallbackMessage;\n const code =\n readString(payload, 'code') ??\n readString(payload, 'gatewayErrorCode') ??\n readString(nestedError, 'code');\n const declineCode =\n readString(payload, 'declineCode') ??\n readString(payload, 'gatewayDeclineReason') ??\n readString(payload, 'decline_code') ??\n readString(nestedError, 'decline_code');\n\n return new FloPayError(message, 'api_error', {\n ...(code ? { code } : {}),\n ...(declineCode ? { declineCode } : {}),\n });\n}\n\nexport async function buildFloPayApiErrorFromResponse(\n response: Response,\n fallbackMessage: string,\n): Promise<FloPayError> {\n const payload = await response.json().catch(() => null) as ApiErrorPayload;\n return buildFloPayApiError(payload, fallbackMessage);\n}\n\nexport function mapPayPalIntentStatusToPaymentResult(\n status: string | null | undefined,\n): PaymentResult['status'] {\n if (status === 'succeeded') {\n return 'succeeded';\n }\n\n if (status === 'processing' || status === 'requires_capture') {\n return 'processing';\n }\n\n return 'failed';\n}\n\nexport type StripePaymentIntentLike = {\n id?: string;\n status?: string;\n payment_method?: string | { id?: string | null } | null;\n};\n\ntype PaymentIntentRetriever = {\n retrievePaymentIntent?: (clientSecret: string) => Promise<{\n paymentIntent?: StripePaymentIntentLike | null;\n error?: { message?: string; code?: string };\n }>;\n};\n\nexport function resolvePaymentIntentPaymentMethodId(\n paymentIntent: StripePaymentIntentLike | null | undefined,\n): string | undefined {\n const paymentMethod = paymentIntent?.payment_method;\n if (typeof paymentMethod === 'string' && paymentMethod.startsWith('pm_')) {\n return paymentMethod;\n }\n if (paymentMethod && typeof paymentMethod === 'object' && typeof paymentMethod.id === 'string') {\n return paymentMethod.id;\n }\n return undefined;\n}\n\nexport async function retrievePaymentIntentFromProvider(\n provider: unknown,\n clientSecret: string,\n): Promise<StripePaymentIntentLike | null> {\n const retriever = provider as PaymentIntentRetriever | null;\n if (!retriever?.retrievePaymentIntent) {\n return null;\n }\n\n const { paymentIntent, error } = await retriever.retrievePaymentIntent(clientSecret);\n if (error) {\n throw new FloPayError(error.message ?? 'Failed to retrieve payment intent.', 'api_error', {\n ...(error.code ? { code: error.code } : {}),\n });\n }\n\n return paymentIntent ?? null;\n}\n\nexport function resolveTokenizedPaymentMethodId(\n tokenizedBody: TokenizedBody | null | undefined,\n): string | undefined {\n const candidates = [\n tokenizedBody?.id,\n tokenizedBody?.originalPaymentMethodId,\n ];\n\n for (const candidate of candidates) {\n if (typeof candidate === 'string' && candidate.startsWith('pm_')) {\n return candidate;\n }\n }\n\n return undefined;\n}\n","// Cross-component, cross-remount signal for \"this session was just /process'd\n// successfully and is mid-completion.\" Written synchronously by SplitCardForm\n// (and the saved-payment / auto-mode flows in FloPayCheckout) the moment the\n// `/process` response is OK — *before* the 1.2s success-overlay delay — so a\n// bootstrap that re-runs during the overlay window can detect that the cache\n// hit's `status: 'complete'` is from THIS journey rather than treat it as\n// a stale leftover and POST a duplicate session.\n//\n// Backed by `sessionStorage` rather than module state because:\n// 1. SplitCardForm and FloPayCheckout are different modules; sessionStorage\n// is the cheapest cross-module bus.\n// 2. It survives a real component remount (which resets useRef/useState)\n// without needing a module-level Map.\n// 3. The TTL gives natural staleness — a buyer who genuinely returns to\n// `/checkout` long after a previous successful checkout still gets the\n// \"clear stale cache and POST a fresh session\" path.\n\nconst STORAGE_KEY_PREFIX = 'flopay_recent_completion_';\nconst RECENT_COMPLETION_TTL_MS = 60 * 1000;\n\ninterface PersistedRecentCompletion {\n expiresAt: number;\n}\n\nexport function markSessionRecentlyCompleted(sessionId: string | null | undefined): void {\n if (!sessionId || typeof window === 'undefined') return;\n try {\n const payload: PersistedRecentCompletion = {\n expiresAt: Date.now() + RECENT_COMPLETION_TTL_MS,\n };\n window.sessionStorage.setItem(STORAGE_KEY_PREFIX + sessionId, JSON.stringify(payload));\n } catch {\n // sessionStorage unavailable (private mode etc.); not safety-critical.\n }\n}\n\nexport function wasSessionRecentlyCompleted(sessionId: string | null | undefined): boolean {\n if (!sessionId || typeof window === 'undefined') return false;\n try {\n const raw = window.sessionStorage.getItem(STORAGE_KEY_PREFIX + sessionId);\n if (!raw) return false;\n const parsed = JSON.parse(raw) as PersistedRecentCompletion;\n if (typeof parsed?.expiresAt !== 'number') {\n window.sessionStorage.removeItem(STORAGE_KEY_PREFIX + sessionId);\n return false;\n }\n if (parsed.expiresAt <= Date.now()) {\n window.sessionStorage.removeItem(STORAGE_KEY_PREFIX + sessionId);\n return false;\n }\n return true;\n } catch {\n return false;\n }\n}\n","/**\n * Internal heuristic detector for in-app browser / WebView environments where\n * PayPal and digital wallets often fail to initialize.\n *\n * `SplitCardForm` uses this as a proactive signal to avoid mounting\n * unsupported express-checkout rows before Stripe reports availability.\n * Stripe load state still covers the long tail: ad-blockers, new WebViews we\n * haven't seen, and account misconfiguration surfacing as `unavailable`.\n *\n * Tradeoffs:\n * - False positives possible. Some modern WebViews (iOS SFSafariViewController\n * on recent iOS, Chrome Custom Tabs) handle PayPal fine but match these\n * patterns. Card checkout remains available, so we accept it.\n * - False negatives possible. New social-app WebViews ship without us knowing.\n * That's why Stripe's reactive load-state collapse remains in place.\n *\n * SSR-safe: returns `false` when `navigator` is undefined.\n */\nexport function isInAppBrowser(userAgent?: string): boolean {\n const ua = userAgent ?? (typeof navigator !== 'undefined' ? navigator.userAgent : '');\n if (!ua) return false;\n\n // Named in-app browsers — most common offenders.\n // FBAN/FBAV/FB_IAB/FBIOS = Facebook + Messenger.\n // musical_ly/BytedanceWebview/TikTok = TikTok across regions.\n if (/FBAN|FBAV|FB_IAB|FBIOS|Instagram|musical_ly|BytedanceWebview|TikTok/i.test(ua)) {\n return true;\n }\n if (/Twitter|Snapchat|Pinterest|LinkedInApp|Line\\/|MicroMessenger|GSA\\//i.test(ua)) {\n return true;\n }\n\n // Generic Android WebView: Chrome UA with the `; wv)` token.\n if (/Android.*;\\s?wv\\)/.test(ua)) return true;\n\n // Generic iOS WebView: iPhone/iPad/iPod with AppleWebKit but no `Safari/`\n // token. Real Mobile Safari always emits `Safari/` — WebViews don't.\n if (/(iPhone|iPad|iPod).*AppleWebKit(?!.*Safari)/.test(ua)) return true;\n\n return false;\n}\n","import type {FloPay} from '@flopay/js';\nimport {loadFloPay, PaymentAPI} from '@flopay/js';\nimport type {\n CheckoutButtonMethod,\n CheckoutProcessError,\n CheckoutSession,\n NormalizedCheckoutSession,\n PaymentResult,\n TokenizedBody,\n} from '@flopay/shared';\nimport {FloPayError} from '@flopay/shared';\nimport {\n buildFloPayApiError,\n resolvePaymentIntentPaymentMethodId,\n resolveTokenizedPaymentMethodId,\n retrievePaymentIntentFromProvider,\n} from './checkout-utils.js';\n\nexport const DEFAULT_SAVED_PAYMENT_DECLINE_METHOD: CheckoutButtonMethod = 'card';\n\nexport type ProcessRedirectResult = {\n type: 'paypal_redirect_required' | '3ds_required';\n threeDSecureToken: string;\n paymentMethodId?: string;\n};\n\nexport type SavedPaymentProcessResult =\n | ProcessRedirectResult\n | {\n type: 'success';\n result: PaymentResult;\n };\n\nexport type SavedPaymentFlowError = FloPayError & {\n checkoutMethod?: CheckoutButtonMethod;\n};\n\nexport function getRedirectResultFromCheckoutProcessError(\n error?: CheckoutProcessError | null,\n): ProcessRedirectResult | null {\n if (!error?.type || !error.threeDSecureToken) {\n return null;\n }\n\n if (\n error.type !== '3ds_required' &&\n error.type !== 'paypal_redirect_required'\n ) {\n return null;\n }\n\n return {\n type: error.type,\n threeDSecureToken: error.threeDSecureToken,\n paymentMethodId: error.paymentMethodId,\n };\n}\n\nexport function checkoutProcessErrorToFloPayError(\n error?: CheckoutProcessError | null,\n fallbackMessage = 'Payment failed. Please try again.',\n options?: {\n checkoutMethod?: CheckoutButtonMethod;\n },\n): SavedPaymentFlowError {\n const checkoutMethod = options?.checkoutMethod\n ?? error?.checkoutMethod\n ?? (error?.type === 'paypal_redirect_required'\n ? 'paypal' as const\n : 'card' as const);\n\n return Object.assign(\n new FloPayError(\n error?.message ?? fallbackMessage,\n 'api_error',\n {\n code: error?.gatewayErrorCode,\n },\n ),\n { checkoutMethod },\n ) satisfies SavedPaymentFlowError;\n}\n\nfunction resolveSavedPaymentReturnUrl(session: CheckoutSession): string | undefined {\n if (typeof window !== 'undefined' && window.location.href) {\n return window.location.href;\n }\n\n return session.successUrl || session.cancelUrl || undefined;\n}\n\nfunction isStripePaymentIntentClientSecret(value: unknown): value is string {\n return typeof value === 'string'\n && value.startsWith('pi_')\n && value.includes('_secret_');\n}\n\nasync function retryOnceOnFetchFailure<T>(action: () => Promise<T>): Promise<T> {\n try {\n return await action();\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n if (!/failed to fetch|fetch failed/i.test(message)) {\n throw err;\n }\n\n return action();\n }\n}\n\nfunction getRedirectTokenFromProcessResponse(\n json: Record<string, unknown> | null,\n options?: { requirePaymentIntentClientSecret?: boolean },\n): string | undefined {\n const directCandidates = [\n json?.threeDSecureToken,\n json?.clientSecret,\n json?.stripeClientSecret,\n ];\n for (const candidate of directCandidates) {\n if (\n typeof candidate === 'string'\n && candidate.length > 0\n && (\n !options?.requirePaymentIntentClientSecret\n || isStripePaymentIntentClientSecret(candidate)\n )\n ) {\n return candidate;\n }\n }\n\n const nested = json?.data;\n if (nested && typeof nested === 'object') {\n const nestedRecord = nested as Record<string, unknown>;\n const nestedCandidates = [\n nestedRecord.threeDSecureToken,\n nestedRecord.clientSecret,\n nestedRecord.stripeClientSecret,\n nestedRecord.id,\n ];\n for (const candidate of nestedCandidates) {\n if (\n typeof candidate === 'string'\n && candidate.length > 0\n && (\n !options?.requirePaymentIntentClientSecret\n || isStripePaymentIntentClientSecret(candidate)\n )\n ) {\n return candidate;\n }\n }\n\n const nestedGatewayData = nestedRecord.gatewayData;\n if (nestedGatewayData && typeof nestedGatewayData === 'object') {\n const nestedGatewayDataRecord = nestedGatewayData as Record<string, unknown>;\n const gatewayCandidates = [\n nestedGatewayDataRecord.stripeClientSecret,\n nestedGatewayDataRecord.clientSecret,\n ];\n for (const candidate of gatewayCandidates) {\n if (\n typeof candidate === 'string'\n && candidate.length > 0\n && (\n !options?.requirePaymentIntentClientSecret\n || isStripePaymentIntentClientSecret(candidate)\n )\n ) {\n return candidate;\n }\n }\n }\n }\n\n return undefined;\n}\n\nasync function recover3DSRedirectResult({\n billingApiUrl,\n sessionId,\n responseJson,\n}: {\n billingApiUrl: string;\n sessionId?: string | null;\n responseJson: Record<string, unknown> | null;\n}): Promise<ProcessRedirectResult | null> {\n const directToken = getRedirectTokenFromProcessResponse(responseJson, {\n requirePaymentIntentClientSecret: true,\n });\n if (typeof directToken === 'string' && directToken.length > 0) {\n return {\n type: '3ds_required',\n threeDSecureToken: directToken,\n };\n }\n\n if (!sessionId) {\n return null;\n }\n\n try {\n const api = new PaymentAPI(billingApiUrl);\n const unified = await api.getUnifiedCheckoutSession(sessionId);\n const refreshedToken = unified.provider === 'stripe'\n ? unified.data.stripe?.clientSecret\n : undefined;\n\n if (isStripePaymentIntentClientSecret(refreshedToken)) {\n return {\n type: '3ds_required',\n threeDSecureToken: refreshedToken,\n };\n }\n } catch {\n // Preserve the original authentication_required error if the recovery fetch fails.\n }\n\n return null;\n}\n\nexport async function processSavedPaymentForMode({\n billingApiUrl,\n sessionId,\n session,\n tokenizedData,\n returnUrl,\n}: {\n billingApiUrl: string;\n sessionId?: string | null;\n session: CheckoutSession;\n tokenizedData?: TokenizedBody;\n returnUrl?: string;\n}): Promise<SavedPaymentProcessResult> {\n const baseUrl = billingApiUrl.replace(/\\/+$/, '');\n const resolvedSessionId = sessionId ?? session.id;\n const customerId = session.customer?.id ?? session.accountData?.userId ?? '';\n const customerEmail = session.customer?.email ?? session.accountData?.email ?? '';\n const firstName = session.customer?.firstName ?? session.accountData?.firstName ?? '';\n const lastName = session.customer?.lastName ?? session.accountData?.lastName ?? '';\n const country = session.customer?.country ?? session.accountData?.country ?? undefined;\n const zip = session.customer?.zip ?? session.accountData?.zip ?? undefined;\n const api = new PaymentAPI(baseUrl);\n\n const response = await retryOnceOnFetchFailure(() => api.processPayment(customerId, {\n sessionId: resolvedSessionId,\n tokenizedData,\n accountData: {\n userId: customerId,\n email: customerEmail,\n firstName,\n lastName,\n country,\n zip,\n },\n returnUrl: returnUrl ?? resolveSavedPaymentReturnUrl(session),\n }));\n\n if (response.ok) {\n return {\n type: 'success',\n result: {\n status: 'succeeded',\n paymentIntentId: tokenizedData?.threeDSecureActionResultTokenId,\n paymentMethodId: resolveTokenizedPaymentMethodId(tokenizedData),\n checkoutMethod: tokenizedData\n ? tokenizedData.isPaypal ? 'paypal' : 'card'\n : undefined,\n },\n };\n }\n\n const json = (await response.json().catch(() => null)) as Record<string, unknown> | null;\n\n if (\n (json?.type === 'paypal_redirect_required' || json?.type === '3ds_required')\n ) {\n const redirectToken = getRedirectTokenFromProcessResponse(json);\n if (!redirectToken) {\n throw new FloPayError(\n 'Authentication is required but no redirect token was provided.',\n 'api_error',\n { code: 'authentication_required' },\n );\n }\n\n return {\n type: json.type as ProcessRedirectResult['type'],\n threeDSecureToken: redirectToken,\n paymentMethodId: json.paymentMethodId as string | undefined,\n };\n }\n\n if (json?.gatewayErrorCode === 'authentication_required') {\n const recoveredRedirect = await recover3DSRedirectResult({\n billingApiUrl: baseUrl,\n sessionId: resolvedSessionId,\n responseJson: json,\n });\n\n if (recoveredRedirect) {\n return recoveredRedirect;\n }\n\n throw Object.assign(\n new FloPayError(\n 'Your card requires authentication. Please enter your payment details below.',\n 'api_error',\n { code: 'authentication_required' },\n ),\n { checkoutMethod: 'card' as CheckoutButtonMethod },\n ) satisfies SavedPaymentFlowError;\n }\n\n throw new FloPayError(\n (json?.message as string) ?? 'Payment failed. Please try again.',\n 'api_error',\n {\n code: (json?.code ?? json?.gatewayErrorCode) as string | undefined,\n declineCode: (json?.declineCode ?? json?.gatewayDeclineReason) as string | undefined,\n },\n );\n}\n\nexport async function processSavedPaymentWithIntent({\n billingApiUrl,\n sessionId,\n session,\n paymentMethodId,\n flopay,\n returnUrl,\n}: {\n billingApiUrl: string;\n sessionId: string;\n session: CheckoutSession;\n paymentMethodId: string;\n flopay: FloPay;\n returnUrl?: string;\n}): Promise<PaymentResult> {\n const customerEmail = session.customer?.email ?? session.accountData?.email ?? '';\n if (!customerEmail) {\n throw Object.assign(\n new FloPayError('Customer email is required to create a payment intent.', 'validation_error', {\n param: 'email',\n }),\n { checkoutMethod: 'card' as CheckoutButtonMethod },\n ) satisfies SavedPaymentFlowError;\n }\n\n const api = new PaymentAPI(billingApiUrl);\n const intentResponse = await retryOnceOnFetchFailure(() => api.createPaymentIntent(\n sessionId,\n customerEmail,\n paymentMethodId,\n ));\n const intentJson = (await intentResponse.json().catch(() => null)) as Record<string, unknown> | null;\n\n if (!intentResponse.ok) {\n const intentError = buildFloPayApiError(\n intentJson,\n 'Failed to create payment intent.',\n );\n\n throw Object.assign(\n intentError,\n { checkoutMethod: 'card' as CheckoutButtonMethod },\n ) satisfies SavedPaymentFlowError;\n }\n\n const intentClientSecret = getRedirectTokenFromProcessResponse(intentJson, {\n requirePaymentIntentClientSecret: true,\n });\n if (!intentClientSecret) {\n throw Object.assign(\n new FloPayError('No client secret in payment intent response.', 'api_error'),\n { checkoutMethod: 'card' as CheckoutButtonMethod },\n ) satisfies SavedPaymentFlowError;\n }\n\n const confirmResult = await flopay.confirmCardPayment({\n clientSecret: intentClientSecret,\n paymentMethodId,\n });\n\n if (confirmResult.error) {\n throw Object.assign(\n confirmResult.error,\n { checkoutMethod: 'card' as CheckoutButtonMethod },\n ) satisfies SavedPaymentFlowError;\n }\n\n const rawProvider = typeof flopay.getRawProvider === 'function' ? flopay.getRawProvider() : null;\n const confirmedPaymentIntent = await retrievePaymentIntentFromProvider(\n rawProvider,\n intentClientSecret,\n );\n const confirmedPaymentIntentId = confirmResult.paymentIntentId ?? confirmedPaymentIntent?.id;\n const confirmedPaymentMethodId =\n confirmResult.paymentMethodId\n ?? resolvePaymentIntentPaymentMethodId(confirmedPaymentIntent)\n ?? paymentMethodId;\n\n if (\n !confirmedPaymentIntentId\n || (\n confirmResult.status !== 'succeeded'\n && confirmResult.status !== 'processing'\n && confirmResult.status !== 'requires_capture'\n )\n ) {\n throw Object.assign(\n new FloPayError(\n `Unfortunately, your payment could not be processed. Please try again using a different payment method or contact your bank for assistance. If the issue persists, feel free to reach out to us for support.`,\n 'api_error',\n {\n code: confirmResult.status === 'requires_action'\n ? 'authentication_required'\n : undefined,\n },\n ),\n { checkoutMethod: 'card' as CheckoutButtonMethod },\n ) satisfies SavedPaymentFlowError;\n }\n\n const followUp = await processSavedPaymentForMode({\n billingApiUrl,\n sessionId,\n session,\n tokenizedData: {\n id: confirmedPaymentMethodId,\n type: 'card',\n threeDSecureActionResultTokenId: confirmedPaymentIntentId,\n },\n returnUrl,\n });\n\n const finalResult = followUp.type === 'success'\n ? followUp.result\n : await handleSavedPaymentRedirectResult(followUp, {\n flopay,\n paypalFlopay: null,\n attempt3DS: true,\n billingApiUrl,\n sessionId,\n session,\n returnUrl,\n });\n\n return {\n ...finalResult,\n paymentIntentId: finalResult.paymentIntentId ?? confirmedPaymentIntentId,\n paymentMethodId: finalResult.paymentMethodId ?? confirmedPaymentMethodId,\n checkoutMethod: finalResult.checkoutMethod ?? 'card',\n };\n}\n\nexport async function handleSavedPaymentRedirectResult(\n redirectResult: ProcessRedirectResult,\n {\n flopay,\n paypalFlopay,\n attempt3DS,\n billingApiUrl,\n sessionId,\n session,\n returnUrl,\n }: {\n flopay: FloPay | null;\n paypalFlopay: FloPay | null;\n attempt3DS?: boolean;\n billingApiUrl: string;\n sessionId?: string | null;\n session: CheckoutSession;\n returnUrl?: string;\n },\n): Promise<PaymentResult> {\n const stripe = flopay?.getRawProvider() as import('@stripe/stripe-js').Stripe | null;\n if (!stripe) {\n throw new FloPayError('Payment provider is not available.', 'api_error');\n }\n\n if (redirectResult.type === '3ds_required') {\n if (!attempt3DS || !redirectResult.threeDSecureToken) {\n throw Object.assign(\n new FloPayError(\n 'Your card requires authentication. Please enter your payment details below.',\n 'api_error',\n { code: 'authentication_required' },\n ),\n { checkoutMethod: 'card' as CheckoutButtonMethod },\n ) satisfies SavedPaymentFlowError;\n }\n\n let paymentIntent: import('@stripe/stripe-js').PaymentIntent | null = null;\n let savedPaymentMethodId = redirectResult.paymentMethodId;\n\n if (typeof stripe.retrievePaymentIntent === 'function') {\n const { paymentIntent: existingPaymentIntent, error: retrieveError } = await stripe.retrievePaymentIntent(\n redirectResult.threeDSecureToken,\n );\n\n if (retrieveError) {\n throw Object.assign(\n new FloPayError(\n retrieveError.message ?? 'Failed to retrieve 3DS payment status.',\n 'api_error',\n { code: retrieveError.code },\n ),\n { checkoutMethod: 'card' as CheckoutButtonMethod },\n ) satisfies SavedPaymentFlowError;\n }\n\n if (!savedPaymentMethodId && existingPaymentIntent?.payment_method) {\n if (typeof existingPaymentIntent.payment_method === 'string') {\n savedPaymentMethodId = existingPaymentIntent.payment_method;\n } else if ('id' in existingPaymentIntent.payment_method) {\n savedPaymentMethodId = existingPaymentIntent.payment_method.id;\n }\n }\n }\n\n if (savedPaymentMethodId && typeof stripe.confirmCardPayment === 'function') {\n const { error: confirmError, paymentIntent: confirmedPaymentIntent } = await stripe.confirmCardPayment(\n redirectResult.threeDSecureToken,\n {\n payment_method: savedPaymentMethodId,\n return_url: returnUrl ?? resolveSavedPaymentReturnUrl(session) ?? window.location.href,\n },\n );\n\n if (confirmError) {\n throw Object.assign(\n new FloPayError(\n confirmError.message ?? '3DS authentication failed.',\n 'api_error',\n { code: confirmError.code },\n ),\n { checkoutMethod: 'card' as CheckoutButtonMethod },\n ) satisfies SavedPaymentFlowError;\n }\n\n paymentIntent = confirmedPaymentIntent ?? null;\n } else {\n const { error: nextActionError, paymentIntent: nextActionPaymentIntent } = await stripe.handleNextAction({\n clientSecret: redirectResult.threeDSecureToken,\n });\n\n if (nextActionError) {\n throw Object.assign(\n new FloPayError(\n nextActionError.message ?? '3DS authentication failed.',\n 'api_error',\n { code: nextActionError.code },\n ),\n { checkoutMethod: 'card' as CheckoutButtonMethod },\n ) satisfies SavedPaymentFlowError;\n }\n\n paymentIntent = nextActionPaymentIntent ?? null;\n }\n\n if (paymentIntent && (\n paymentIntent.status === 'requires_capture' ||\n paymentIntent.status === 'succeeded' ||\n paymentIntent.status === 'processing'\n )) {\n const followUp = await processSavedPaymentForMode({\n billingApiUrl,\n sessionId,\n session,\n tokenizedData: {\n id: paymentIntent.id,\n type: 'card',\n threeDSecureActionResultTokenId: paymentIntent.id,\n },\n returnUrl,\n });\n\n if (followUp.type === 'success') {\n return {\n ...followUp.result,\n paymentIntentId: followUp.result.paymentIntentId ?? paymentIntent.id,\n paymentMethodId: followUp.result.paymentMethodId ?? savedPaymentMethodId,\n };\n }\n\n return handleSavedPaymentRedirectResult(followUp, {\n flopay,\n paypalFlopay,\n attempt3DS,\n billingApiUrl,\n sessionId,\n session,\n returnUrl,\n });\n }\n\n throw Object.assign(\n new FloPayError('3DS authentication did not complete successfully.', 'api_error'),\n { checkoutMethod: 'card' as CheckoutButtonMethod },\n ) satisfies SavedPaymentFlowError;\n }\n\n if (redirectResult.type === 'paypal_redirect_required') {\n const paypalStripe = (paypalFlopay ?? flopay)?.getRawProvider() as import('@stripe/stripe-js').Stripe | null;\n if (!paypalStripe) {\n throw Object.assign(\n new FloPayError('PayPal is not available.', 'api_error'),\n { checkoutMethod: 'paypal' as CheckoutButtonMethod },\n ) satisfies SavedPaymentFlowError;\n }\n\n if (redirectResult.paymentMethodId) {\n // Backend attached the saved PM and confirmed the PI server-side, so\n // the PI is in `requires_action` with the PayPal redirect baked into\n // next_action.redirect_to_url. Use `handleNextAction` to drive that\n // redirect — `confirmPayment` would error with\n // `payment_intent_unexpected_state` on a PI that's already past the\n // confirmation step.\n const { error } = await paypalStripe.handleNextAction({\n clientSecret: redirectResult.threeDSecureToken,\n });\n\n if (error) {\n throw Object.assign(\n new FloPayError(\n error.message ?? 'PayPal authorization failed.',\n 'api_error',\n { code: error.code },\n ),\n { checkoutMethod: 'paypal' as CheckoutButtonMethod },\n ) satisfies SavedPaymentFlowError;\n }\n\n return {\n status: 'succeeded',\n checkoutMethod: 'paypal',\n };\n }\n\n // No `paymentMethodId` on the redirect result: backend created the PI\n // without attaching a PM, so it's sitting in `requires_payment_method`.\n // Drive the redirect by passing `payment_method_data: { type: 'paypal' }`\n // — Stripe creates a fresh PayPal PM during the redirect and attaches it\n // to the PI. No Elements instance needed; no saved-PM reference needed\n // either, so this works for true cross-account scenarios as well.\n const { error } = await paypalStripe.confirmPayment({\n clientSecret: redirectResult.threeDSecureToken,\n confirmParams: {\n return_url: returnUrl ?? resolveSavedPaymentReturnUrl(session) ?? window.location.href,\n payment_method_data: { type: 'paypal' },\n } as { return_url: string },\n redirect: 'if_required',\n });\n\n if (error) {\n throw Object.assign(\n new FloPayError(\n error.message ?? 'PayPal authorization failed.',\n 'api_error',\n { code: error.code },\n ),\n { checkoutMethod: 'paypal' as CheckoutButtonMethod },\n ) satisfies SavedPaymentFlowError;\n }\n\n return {\n status: 'succeeded',\n checkoutMethod: 'paypal',\n };\n }\n\n throw new FloPayError('Unsupported payment redirect state.', 'api_error');\n}\n\nexport function normalizeSavedPaymentError(err: unknown): SavedPaymentFlowError {\n if (err instanceof FloPayError) {\n return err as SavedPaymentFlowError;\n }\n\n return new FloPayError(\n err instanceof Error ? err.message : 'Payment failed. Please try again.',\n 'api_error',\n ) as SavedPaymentFlowError;\n}\n\nexport function resolveSavedPaymentPublishableKeys(\n unified: NormalizedCheckoutSession,\n): {\n publishableKey: string;\n paypalPublishableKey?: string;\n} {\n let publishableKey: string | undefined;\n let paypalPublishableKey: string | undefined;\n\n if (unified.provider === 'stripe') {\n publishableKey = unified.data.stripe?.publishableKey;\n paypalPublishableKey = unified.data.stripe?.paypalPublishableKey ?? undefined;\n }\n\n if (!publishableKey) {\n throw new FloPayError(\n 'No publishable key found in the checkout session. Ensure the session includes gatewayData.publishableKey.',\n 'validation_error',\n );\n }\n\n return {\n publishableKey,\n paypalPublishableKey,\n };\n}\n\nexport async function loadSavedPaymentProviders({\n publishableKey,\n paypalPublishableKey,\n billingApiUrl,\n locale,\n}: {\n publishableKey: string;\n paypalPublishableKey?: string;\n billingApiUrl: string;\n locale?: string;\n}): Promise<{\n flopay: FloPay;\n paypalFlopay: FloPay | null;\n}> {\n const needsSeparatePaypal =\n Boolean(paypalPublishableKey) && paypalPublishableKey !== publishableKey;\n\n const [instance, paypalInstanceOrError] = await Promise.all([\n loadFloPay(publishableKey, {\n billingApiUrl,\n locale,\n }),\n needsSeparatePaypal\n ? loadFloPay(paypalPublishableKey!, {\n billingApiUrl,\n locale,\n }).catch((err: unknown) => {\n console.warn('[FloPay] Failed to load PayPal Stripe instance:', err);\n return null;\n })\n : Promise.resolve(null),\n ]);\n\n return {\n flopay: instance,\n paypalFlopay: paypalPublishableKey\n ? needsSeparatePaypal\n ? (paypalInstanceOrError as FloPay | null)\n : instance\n : null,\n };\n}\n","import type {\n DeclineEvent,\n PaymentResult,\n TokenizedBody,\n} from '@flopay/shared';\nimport { PaymentAPI } from '@flopay/js';\nimport { FloPayError } from '@flopay/shared';\nimport React, { forwardRef, useCallback, useEffect, useImperativeHandle, useState } from 'react';\nimport { useFloPay, usePayPalFloPay, useElements, useBillingApiUrl } from './hooks.js';\nimport { PaymentElement } from './elements.js';\nimport { AddressElement } from './elements.js';\nimport {\n buildDeclineEvent,\n buildFloPayApiErrorFromResponse,\n resolvePaymentIntentPaymentMethodId,\n resolveTokenizedPaymentMethodId,\n retrievePaymentIntentFromProvider,\n} from './checkout-utils.js';\n\n/** localStorage key for persisting wallet payment state across redirects. */\nconst WALLET_RESUME_KEY = 'flopay_wallet_resume';\n\n/** Methods exposed via ref for external 3DS handling. */\nexport interface CheckoutFormRef {\n handleNextAction: (clientSecret: string) => Promise<void>;\n}\n\n/** Props for the drop-in `CheckoutForm` component. */\nexport interface CheckoutFormProps {\n /** The checkout session ID (UUID from billing API). */\n sessionId: string;\n /** Billing API base URL. Optional — defaults to the value from FloPayProvider or the shared constant. */\n billingApiUrl?: string;\n /** User's email (required for creating payment intents). */\n email?: string;\n /** User ID (required for processing payments). */\n userId?: string;\n /**\n * Called when the full payment flow completes successfully.\n * By default the form handles everything: tokenize → create intent →\n * confirm → processPayment → 3DS retry. You just handle the success.\n */\n onComplete?: (result: PaymentResult) => void;\n /** Called when a payment error occurs. */\n onError?: (error: FloPayError) => void;\n /** Called when a payment is declined or the authentication step fails. */\n onDecline?: (decline: DeclineEvent) => void;\n /**\n * **Override**: If provided, the form tokenizes the card and confirms\n * the payment, but delegates backend submission to the caller.\n * When omitted, the form calls `processPayment` internally.\n */\n onTokenizedBody?: (tokenizedBody: TokenizedBody) => void;\n /** Layout style for the PaymentElement. */\n layout?: 'tabs' | 'accordion' | 'auto';\n /** Label for the submit button. */\n submitLabel?: string;\n /** Whether to show an address element. */\n showAddress?: boolean | 'billing' | 'shipping';\n /** Additional CSS class for the form wrapper. */\n className?: string;\n /** Custom children (e.g. a custom submit button). Overrides the default button. */\n children?: React.ReactNode;\n /** First name for billing. */\n firstName?: string;\n /** Last name for billing. */\n lastName?: string;\n /** Checkout version for A/B tracking. */\n chv?: string;\n /** External processing state (used when onTokenizedBody is provided). */\n isProcessing?: boolean;\n /** External error message (used when onTokenizedBody is provided). */\n error?: string | null;\n /** Called when internal error state changes. */\n onErrorChange?: (error: string | null) => void;\n}\n\n/**\n * Drop-in checkout form that handles the full payment lifecycle by default.\n *\n * **Default (self-contained) mode** — just provide config + onComplete:\n * ```tsx\n * <CheckoutForm\n * sessionId=\"uuid\"\n * billingApiUrl=\"https://api.example.com\"\n * email=\"user@example.com\"\n * userId=\"user_1\"\n * onComplete={(result) => router.push('/success')}\n * />\n * ```\n *\n * The form handles internally:\n * 1. Validate → tokenize card → create PaymentIntent → confirm (3DS)\n * 2. Submit token to `POST /v1/checkouts/sessions/process`\n * 3. If backend returns `3ds_required` → re-confirm with new client secret\n * 4. Wallet resume after redirect (PayPal, etc.)\n *\n * **Override mode** — provide `onTokenizedBody` to handle backend submission yourself:\n * ```tsx\n * <CheckoutForm\n * ...\n * onTokenizedBody={(body) => myCustomProcessPayment(body)}\n * />\n * ```\n */\nexport const CheckoutForm = forwardRef<CheckoutFormRef, CheckoutFormProps>(\n function CheckoutForm(props, ref) {\n return <CheckoutFormInner {...props} innerRef={ref} />;\n },\n);\n\n// ─── Internal implementation ────────────────────────────────────────────────\n\nfunction CheckoutFormInner({\n sessionId,\n billingApiUrl,\n email,\n userId,\n onComplete,\n onError,\n onDecline,\n onTokenizedBody,\n layout = 'auto',\n submitLabel = 'Pay',\n showAddress = false,\n className,\n children,\n firstName,\n lastName,\n chv,\n isProcessing: externalProcessing,\n error: externalError,\n onErrorChange,\n innerRef,\n}: CheckoutFormProps & { innerRef: React.Ref<CheckoutFormRef> }) {\n const flopay = useFloPay();\n const paypalFlopay = usePayPalFloPay();\n const elements = useElements();\n const contextBillingUrl = useBillingApiUrl();\n const [processing, setProcessing] = useState(false);\n const [error, setError] = useState<string | null>(null);\n const [is3DSActive, setIs3DSActive] = useState(false);\n\n const displayError = externalError ?? error;\n const isSubmitting = externalProcessing ?? processing;\n const isSelfContained = !onTokenizedBody;\n const baseUrl = (billingApiUrl || contextBillingUrl).replace(/\\/+$/, '');\n\n const updateError = useCallback(\n (err: string | null) => {\n setError(err);\n onErrorChange?.(err);\n },\n [onErrorChange],\n );\n\n const emitDecline = useCallback(\n (\n input: string | FloPayError,\n overrides?: { code?: string; declineCode?: string },\n ) => {\n onDecline?.(buildDeclineEvent('card', input, overrides));\n },\n [onDecline],\n );\n\n // ── Internal: call processPayment and handle 3DS/PayPal responses ──\n\n const processPaymentInternal = useCallback(\n async (\n tokenizedBody: TokenizedBody,\n completionPaymentMethodId?: string,\n ) => {\n setProcessing(true);\n updateError(null);\n\n const resolvedCompletionPaymentMethodId =\n completionPaymentMethodId ?? resolveTokenizedPaymentMethodId(tokenizedBody);\n const requestTokenizedBody = tokenizedBody.originalPaymentMethodId\n ? { ...tokenizedBody, originalPaymentMethodId: undefined }\n : tokenizedBody;\n\n try {\n const api = new PaymentAPI(baseUrl);\n const response = await api.processPayment(userId ?? '', {\n sessionId,\n tokenizedData: requestTokenizedBody,\n accountData: {\n userId: userId ?? '',\n email: email ?? '',\n firstName: firstName ?? '',\n lastName: lastName ?? '',\n },\n chv,\n });\n\n if (response.ok) {\n onComplete?.({\n status: 'succeeded',\n paymentIntentId: tokenizedBody.threeDSecureActionResultTokenId,\n paymentMethodId: resolvedCompletionPaymentMethodId,\n checkoutMethod: tokenizedBody.isPaypal ? 'paypal' : 'card',\n });\n return;\n }\n\n const json = await response.json().catch(() => null) as Record<string, unknown> | null;\n\n // 3DS required — confirm with new client secret, then resubmit\n if (json?.type === '3ds_required') {\n const secret = json['threeDSecureToken'] as string;\n if (!flopay || !secret) {\n updateError('3DS authentication required but no token provided.');\n return;\n }\n\n setIs3DSActive(true);\n try {\n const retryFullName = `${firstName ?? ''} ${lastName ?? ''}`.trim();\n const result = await flopay.confirmPayment({\n clientSecret: secret,\n returnUrl: window.location.href,\n billingDetails: {\n ...(email ? { email } : {}),\n ...(retryFullName ? { name: retryFullName } : {}),\n },\n });\n\n if (result.error) {\n updateError(result.error.message);\n onError?.(result.error);\n emitDecline(result.error);\n return;\n }\n\n if (result.status === 'succeeded' || result.status === 'processing') {\n // Resubmit with the 3DS result. Keep the original reusable PM for\n // completion callbacks, but do not resend it in the process body:\n // the billing API may derive idempotency keys from that PM.\n await processPaymentInternal({\n id: result.paymentIntentId,\n type: 'card',\n threeDSecureActionResultTokenId: result.paymentIntentId,\n }, resolvedCompletionPaymentMethodId);\n }\n } finally {\n setIs3DSActive(false);\n }\n return;\n }\n\n // PayPal redirect required — the PaymentIntent lives on the PayPal\n // Stripe account (gatewayData.paypalPublishableKey), so confirmation\n // must be routed through the PayPal FloPay instance. Falls back to\n // the primary instance when the PayPal account matches the primary.\n if (json?.type === 'paypal_redirect_required') {\n const secret = (json['threeDSecureToken'] ?? json['clientSecret']) as string | undefined;\n const pmId = json['paymentMethodId'] as string | undefined;\n const paypalStripe = (paypalFlopay ?? flopay)?.getRawProvider() as\n | import('@stripe/stripe-js').Stripe\n | null;\n\n if (!paypalStripe || !secret) {\n const message = 'PayPal is not available.';\n updateError(message);\n onDecline?.(buildDeclineEvent('paypal', message));\n return;\n }\n\n // Store state for resume after redirect.\n localStorage.setItem(WALLET_RESUME_KEY, JSON.stringify({\n sessionId,\n paymentIntentId: '',\n tokenType: 'card',\n tokenId: pmId ?? '',\n status: 'pending_redirect',\n }));\n\n const confirmParams: Record<string, unknown> = {\n return_url: window.location.href,\n };\n if (pmId) confirmParams['payment_method'] = pmId;\n\n const { error: confirmError } = await paypalStripe.confirmPayment({\n clientSecret: secret,\n confirmParams: confirmParams as { return_url: string },\n redirect: 'if_required',\n });\n\n if (confirmError) {\n const message = confirmError.message ?? 'PayPal payment failed.';\n updateError(message);\n onDecline?.(buildDeclineEvent('paypal', message, { code: confirmError.code }));\n }\n return;\n }\n\n // Generic error\n const errorMessage = (json?.message as string) ?? 'Payment failed. Please try again.';\n updateError(errorMessage);\n emitDecline(errorMessage, {\n code: json?.code as string | undefined,\n declineCode: (json?.declineCode ?? json?.gatewayDeclineReason) as string | undefined,\n });\n } catch (err) {\n updateError(err instanceof Error ? err.message : 'An unexpected error occurred');\n } finally {\n setProcessing(false);\n }\n },\n [baseUrl, sessionId, userId, email, firstName, lastName, chv, flopay, paypalFlopay, onComplete, onError, onDecline, updateError, emitDecline],\n );\n\n // ── Dispatch tokenized body: self-contained or delegated ──\n\n const dispatchTokenizedBody = useCallback(\n (tokenizedBody: TokenizedBody) => {\n if (onTokenizedBody) {\n // Delegated mode — caller handles backend submission\n onTokenizedBody(tokenizedBody);\n } else {\n // Self-contained mode — process internally\n processPaymentInternal(tokenizedBody);\n }\n },\n [onTokenizedBody, processPaymentInternal],\n );\n\n // ── Expose imperative 3DS handler (for delegated mode) ──\n\n useImperativeHandle(innerRef, () => ({\n async handleNextAction(secret: string) {\n if (!flopay) return;\n\n setIs3DSActive(true);\n try {\n const result = await flopay.confirmPayment({\n clientSecret: secret,\n returnUrl: window.location.href,\n });\n\n if (result.error) {\n updateError(result.error.message);\n onError?.(result.error);\n emitDecline(result.error);\n } else if (result.status === 'succeeded' || result.status === 'processing') {\n dispatchTokenizedBody({\n id: result.paymentIntentId,\n type: 'card',\n threeDSecureActionResultTokenId: result.paymentIntentId,\n });\n }\n } catch (err) {\n updateError(err instanceof Error ? err.message : 'Payment authentication failed.');\n } finally {\n setIs3DSActive(false);\n }\n },\n }), [flopay, dispatchTokenizedBody, onError, updateError, emitDecline]);\n\n // ── Resume wallet payments after redirect ──\n\n useEffect(() => {\n if (typeof window === 'undefined') return;\n\n const stored = localStorage.getItem(WALLET_RESUME_KEY);\n if (!stored) return;\n\n try {\n const payload = JSON.parse(stored) as {\n sessionId: string;\n paymentIntentId: string;\n tokenType: string;\n tokenId: string;\n status: string;\n };\n\n if (payload.sessionId === sessionId) {\n localStorage.removeItem(WALLET_RESUME_KEY);\n dispatchTokenizedBody({\n id: payload.tokenId,\n type: payload.tokenType,\n threeDSecureActionResultTokenId: payload.paymentIntentId,\n });\n }\n } catch {\n localStorage.removeItem(WALLET_RESUME_KEY);\n }\n }, [sessionId, dispatchTokenizedBody]);\n\n // ── Submit: tokenize → create intent → confirm → dispatch ──\n\n const handleSubmit = useCallback(\n async (e: React.FormEvent) => {\n e.preventDefault();\n if (!flopay || !elements || isSubmitting) return;\n\n setProcessing(true);\n updateError(null);\n let handedOff = false;\n\n try {\n // Matches checkout/StripeCardForm exactly:\n // 1. createPaymentMethod → 2. createPaymentIntent → 3. confirmCardPayment → 4. onTokenizedBody\n\n // 1. Validate\n const submitResult = await flopay.submitElements();\n if (submitResult.error) {\n updateError(submitResult.error.message);\n onError?.(submitResult.error);\n return;\n }\n\n // 2. Tokenize card → PaymentMethod\n const fullName = `${firstName ?? ''} ${lastName ?? ''}`.trim();\n const pmResult = await flopay.createPaymentMethod({\n ...(email ? { email } : {}),\n ...(fullName ? { name: fullName } : {}),\n });\n if (pmResult.error || !pmResult.paymentMethodId) {\n updateError(pmResult.error?.message ?? 'Failed to create payment method.');\n return;\n }\n\n if (!sessionId || !email) {\n throw new FloPayError('Missing sessionId or email', 'validation_error');\n }\n\n // 3. Create PaymentIntent via billing API (backend uses capture_method: 'manual')\n const intentResponse = await fetch(`${baseUrl}/v1/checkouts/payments/intents`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n sessionId,\n email,\n paymentMethodType: pmResult.paymentMethodId,\n isPaypal: false,\n }),\n });\n\n if (!intentResponse.ok) {\n const intentError = await buildFloPayApiErrorFromResponse(\n intentResponse,\n 'Failed to create payment intent',\n );\n updateError(intentError.message);\n onError?.(intentError);\n emitDecline(intentError);\n return;\n }\n\n const intentJson = await intentResponse.json() as { data?: { id?: string } };\n const intentClientSecret = intentJson.data?.id;\n if (!intentClientSecret) throw new FloPayError('No client_secret in payment intent response', 'api_error');\n\n // 4. Confirm card payment (handles 3DS automatically via Stripe)\n const confirmResult = await flopay.confirmCardPayment({\n clientSecret: intentClientSecret,\n paymentMethodId: pmResult.paymentMethodId,\n });\n\n if (confirmResult.error) {\n updateError(confirmResult.error.message);\n onError?.(confirmResult.error);\n emitDecline(confirmResult.error);\n return;\n }\n\n const rawProvider = typeof flopay.getRawProvider === 'function' ? flopay.getRawProvider() : null;\n const confirmedPaymentIntent = await retrievePaymentIntentFromProvider(\n rawProvider,\n intentClientSecret,\n );\n const paymentIntentId = confirmResult.paymentIntentId ?? confirmedPaymentIntent?.id;\n const paymentMethodId =\n confirmResult.paymentMethodId\n ?? resolvePaymentIntentPaymentMethodId(confirmedPaymentIntent)\n ?? pmResult.paymentMethodId;\n\n if (!paymentIntentId) {\n const error = new FloPayError('No payment intent returned after confirmation.', 'api_error');\n updateError(error.message);\n onError?.(error);\n return;\n }\n\n // 5. Send PM + PI to processPaymentInternal (or parent via onTokenizedBody)\n handedOff = isSelfContained;\n dispatchTokenizedBody({\n id: paymentMethodId,\n type: 'card',\n threeDSecureActionResultTokenId: paymentIntentId,\n originalPaymentMethodId: pmResult.paymentMethodId,\n });\n } catch (err) {\n updateError(err instanceof Error ? err.message : 'An unexpected error occurred');\n } finally {\n if (!handedOff) {\n setProcessing(false);\n }\n }\n },\n [flopay, elements, isSubmitting, sessionId, email, baseUrl, isSelfContained, dispatchTokenizedBody, onError, updateError, emitDecline],\n );\n\n const isReady = flopay !== null && elements !== null;\n\n return (\n <form onSubmit={handleSubmit} className={className} style={{ position: 'relative' }}>\n {(is3DSActive || isSubmitting) && (\n <div data-testid=\"flopay-overlay\" style={{\n position: 'absolute', inset: 0,\n background: 'rgba(255,255,255,0.7)',\n display: 'flex', alignItems: 'center', justifyContent: 'center',\n zIndex: 10,\n }}>\n {is3DSActive ? 'Verifying payment...' : 'Processing...'}\n </div>\n )}\n\n {!isReady && (\n <div data-testid=\"flopay-loading\" aria-busy=\"true\">\n Loading payment form...\n </div>\n )}\n\n {isReady && (\n <>\n <PaymentElement options={{ layout }} />\n\n {showAddress && (\n <AddressElement options={{ mode: showAddress === true ? 'billing' : showAddress }} />\n )}\n\n {displayError && (\n <div role=\"alert\" data-testid=\"flopay-error\" style={{ color: 'red', margin: '0.75rem 0' }}>\n {displayError}\n </div>\n )}\n\n {children ?? (\n <button\n type=\"submit\"\n disabled={isSubmitting || !isReady}\n data-testid=\"flopay-submit\"\n >\n {isSubmitting ? 'Processing...' : submitLabel}\n </button>\n )}\n </>\n )}\n </form>\n );\n}\n","import type { TokenizedBody } from '@flopay/shared';\nimport { PaymentAPI } from '@flopay/js';\nimport { FloPayError } from '@flopay/shared';\nimport React, { useCallback, useEffect, useRef, useState } from 'react';\nimport { useFloPay, useElements, useBillingApiUrl } from './hooks.js';\n\n/**\n * Props for the `PayPalButton` component.\n *\n * Must be rendered inside its own `FloPayProvider` with `paymentMethodCreation: undefined`\n * (not 'manual') — PayPal cannot share the same Elements instance as card fields.\n */\nexport interface PayPalButtonProps {\n /** The checkout session ID (UUID from billing API). */\n sessionId: string;\n /** Billing API base URL. Optional — defaults to the value from FloPayProvider or the shared constant. */\n billingApiUrl?: string;\n /** User's email. */\n email?: string;\n /** User ID for processing payments. */\n userId?: string;\n /** First name for billing. */\n firstName?: string;\n /** Last name for billing. */\n lastName?: string;\n /** Checkout version for tracking. */\n chv?: string;\n /**\n * Called with tokenized data after PayPal authorization.\n * If omitted, the component calls processPayment internally.\n */\n onTokenizedBody?: (body: TokenizedBody) => void;\n /** Called on successful payment (self-contained mode). */\n onComplete?: () => void;\n /** Called when an error occurs. */\n onErrorChange?: (error: string | null) => void;\n /** External processing state. */\n isProcessing?: boolean;\n}\n\n/**\n * PayPal button that handles the full PayPal payment flow.\n *\n * **Important**: PayPal requires its own `FloPayProvider` — it cannot share\n * the same Stripe Elements instance as card fields when they use\n * `paymentMethodCreation: 'manual'`. This matches `checkout/StripeCardForm`\n * which renders PayPal in a separate `<Elements>` wrapper.\n *\n * ```tsx\n * {/* Card fields provider (paymentMethodCreation: 'manual') *\\/}\n * <FloPayProvider flopay={flopay} options={{ amount, currency }}>\n * <SplitCardForm ... />\n * </FloPayProvider>\n *\n * {/* PayPal provider (no paymentMethodCreation) *\\/}\n * <FloPayProvider flopay={flopay} options={{ amount, currency, paymentMethodCreation: 'auto' }}>\n * <PayPalButton ... />\n * </FloPayProvider>\n * ```\n */\nexport function PayPalButton({\n sessionId,\n billingApiUrl,\n email,\n userId,\n firstName,\n lastName,\n chv,\n onTokenizedBody,\n onComplete,\n onErrorChange,\n isProcessing = false,\n}: PayPalButtonProps): React.ReactElement {\n const flopay = useFloPay();\n const elements = useElements();\n const contextBillingUrl = useBillingApiUrl();\n const [ready, setReady] = useState(false);\n const [submitting, setSubmitting] = useState(false);\n const paypalResumeAttempted = useRef(false);\n const baseUrl = (billingApiUrl || contextBillingUrl).replace(/\\/+$/, '');\n\n // ── Internal processPayment (self-contained mode) ──\n\n const processPaymentInternal = useCallback(\n async (tokenizedBody: TokenizedBody) => {\n try {\n const api = new PaymentAPI(baseUrl);\n const response = await api.processPayment(userId ?? '', {\n sessionId,\n tokenizedData: tokenizedBody,\n accountData: {\n userId: userId ?? '',\n email: email ?? '',\n firstName: firstName ?? '',\n lastName: lastName ?? '',\n },\n chv,\n });\n\n if (response.ok) {\n onComplete?.();\n return;\n }\n\n const json = await response.json().catch(() => null) as Record<string, unknown> | null;\n onErrorChange?.((json?.message as string) ?? 'Payment failed. Please try again.');\n } catch (err) {\n onErrorChange?.(err instanceof Error ? err.message : 'An unexpected error occurred');\n }\n },\n [baseUrl, sessionId, userId, email, firstName, lastName, chv, onComplete, onErrorChange],\n );\n\n const dispatchTokenizedBody = useCallback(\n (body: TokenizedBody) => {\n if (onTokenizedBody) {\n onTokenizedBody(body);\n } else {\n processPaymentInternal(body);\n }\n },\n [onTokenizedBody, processPaymentInternal],\n );\n\n // ── Resume PayPal redirect return ──\n\n useEffect(() => {\n if (!flopay || paypalResumeAttempted.current) return;\n\n const params = new URLSearchParams(window.location.search);\n const paymentIntentId = params.get('payment_intent');\n const clientSecret = params.get('payment_intent_client_secret');\n const redirectStatus = params.get('redirect_status');\n\n if (!paymentIntentId || !clientSecret) return;\n paypalResumeAttempted.current = true;\n\n (async () => {\n try {\n setSubmitting(true);\n\n if (redirectStatus === 'failed') {\n onErrorChange?.('PayPal payment was declined. Please try again.');\n return;\n }\n\n // Retrieve the PaymentIntent to check status (matches checkout/StripeCardForm resume)\n const provider = flopay.getRawProvider() as { retrievePaymentIntent?: (cs: string) => Promise<{ paymentIntent?: { id: string; status: string; payment_method: string | { id: string } }; error?: { message: string } }> } | null;\n if (!provider?.retrievePaymentIntent) {\n onErrorChange?.('Cannot retrieve PayPal payment status.');\n return;\n }\n\n const { paymentIntent, error: retrieveError } = await provider.retrievePaymentIntent(clientSecret);\n if (retrieveError) {\n onErrorChange?.(retrieveError.message ?? 'Failed to retrieve PayPal payment status.');\n return;\n }\n\n if (paymentIntent && (paymentIntent.status === 'requires_capture' || paymentIntent.status === 'succeeded')) {\n const pmId = typeof paymentIntent.payment_method === 'string'\n ? paymentIntent.payment_method\n : paymentIntent.payment_method?.id;\n\n dispatchTokenizedBody({\n id: pmId ?? paymentIntent.id,\n type: 'card',\n threeDSecureActionResultTokenId: paymentIntent.id,\n isPaypal: true,\n });\n\n // Clean up URL params\n const url = new URL(window.location.href);\n url.searchParams.delete('payment_intent');\n url.searchParams.delete('payment_intent_client_secret');\n url.searchParams.delete('redirect_status');\n window.history.replaceState({}, '', url.toString());\n } else {\n onErrorChange?.('PayPal payment was not completed. Please try again.');\n }\n } catch (err) {\n onErrorChange?.(err instanceof Error ? err.message : 'Failed to complete PayPal payment.');\n } finally {\n setSubmitting(false);\n }\n })();\n }, [flopay, dispatchTokenizedBody, onErrorChange]);\n\n // ── PayPal confirm handler ──\n\n const handlePayPalConfirm = useCallback(async () => {\n if (!flopay || !elements) return;\n\n try {\n setSubmitting(true);\n onErrorChange?.(null);\n\n if (!sessionId || !email) {\n throw new FloPayError('Missing sessionId or email for PayPal payment', 'validation_error');\n }\n\n const result = await flopay.confirmPayPalPayment({\n billingApiUrl: baseUrl,\n sessionId,\n email,\n returnUrl: window.location.href,\n });\n\n if (result.error) {\n onErrorChange?.(result.error.message);\n return;\n }\n\n // Defensive future inline-completion path: `confirmPayPalPayment` currently\n // redirects and returns no `paymentIntentId`, so the redirect-resume effect\n // is what normally reaches `dispatchTokenizedBody`. If\n // `confirmPayPalPayment` ever starts completing inline, it must also return\n // `paymentIntentId` so this branch can finish the checkout immediately.\n if (\n result.paymentIntentId\n && (result.status === 'succeeded' || result.status === 'processing' || result.status === 'requires_capture')\n ) {\n dispatchTokenizedBody({\n id: result.paymentMethodId ?? result.paymentIntentId,\n type: 'card',\n threeDSecureActionResultTokenId: result.paymentIntentId,\n isPaypal: true,\n });\n }\n } catch (err) {\n onErrorChange?.(err instanceof Error ? err.message : 'PayPal payment failed. Please try again.');\n } finally {\n setSubmitting(false);\n }\n }, [flopay, elements, sessionId, email, baseUrl, dispatchTokenizedBody, onErrorChange]);\n\n if (!flopay || !elements) {\n return <div style={{ height: 45, background: '#f0f0f0', borderRadius: 6, animation: 'pulse 1.5s infinite' }} />;\n }\n\n return (\n <>\n {!ready && (\n <div style={{ height: 45, background: '#f0f0f0', borderRadius: 6 }} />\n )}\n <div style={ready ? {} : { display: 'none' }}>\n <button\n type=\"button\"\n onClick={handlePayPalConfirm}\n disabled={submitting || isProcessing}\n style={{\n width: '100%',\n height: 45,\n backgroundColor: '#ffc439',\n color: '#003087',\n border: 'none',\n borderRadius: 6,\n fontSize: '1rem',\n fontWeight: 700,\n cursor: submitting || isProcessing ? 'not-allowed' : 'pointer',\n opacity: submitting || isProcessing ? 0.6 : 1,\n }}\n ref={() => setReady(true)}\n >\n {submitting ? 'Processing...' : 'PayPal'}\n </button>\n </div>\n\n {(submitting || isProcessing) && (\n <div style={{\n position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.4)',\n display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 1000,\n }}>\n <div style={{\n background: 'white', borderRadius: 8, padding: '1.5rem',\n textAlign: 'center', boxShadow: '0 4px 24px rgba(0,0,0,0.15)', width: 280,\n }}>\n Processing PayPal payment...\n </div>\n </div>\n )}\n </>\n );\n}\n","import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport { PaymentAPI } from '@flopay/js';\nimport type {\n CheckoutButtonMethod,\n CheckoutSession,\n DeclineEvent,\n InlineSessionDraft,\n PaymentResult,\n} from '@flopay/shared';\nimport type { ButtonsLayoutStyles, ButtonsLayoutTheme, CheckoutItem, CheckoutSubscription } from '@flopay/shared';\nimport { FloPayError, resolveBillingApiUrl, resolveButtonsLayoutTheme } from '@flopay/shared';\nimport { CardButtonContentSlot } from './card-button-content.js';\nimport { buildDeclineEvent, mapPayPalIntentStatusToPaymentResult } from './checkout-utils.js';\nimport { FloPayCheckout } from './flopay-checkout.js';\nimport {\n PROCESSING_OVERLAY_ERROR_DELAY_MS,\n PROCESSING_OVERLAY_SUCCESS_DELAY_MS,\n ProcessingOverlay,\n type OverlayStatus,\n} from './processing-overlay.js';\nimport {\n checkoutProcessErrorToFloPayError,\n DEFAULT_SAVED_PAYMENT_DECLINE_METHOD,\n getRedirectResultFromCheckoutProcessError,\n handleSavedPaymentRedirectResult,\n loadSavedPaymentProviders,\n normalizeSavedPaymentError,\n processSavedPaymentForMode,\n processSavedPaymentWithIntent,\n resolveSavedPaymentPublishableKeys,\n} from './saved-payment-flow.js';\n\nconst DEFAULT_BUTTONS_LAYOUT_BUTTON_HEIGHT = 44;\nconst PAYPAL_RESUME_STORAGE_KEY = 'flopay_automatic_payment_button_resume';\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nfunction coerceError(err: unknown, fallbackMessage: string): FloPayError {\n if (err instanceof FloPayError) {\n return err;\n }\n\n return new FloPayError(\n err instanceof Error ? err.message : fallbackMessage,\n 'api_error',\n );\n}\n\nfunction canUseStorage() {\n return typeof window !== 'undefined' && typeof window.sessionStorage !== 'undefined';\n}\n\ninterface PayPalResumeState {\n sessionId: string | null;\n publishableKey: string;\n paypalPublishableKey?: string;\n}\n\nfunction shouldShowFallbackCheckout(\n error: FloPayError & { checkoutMethod?: CheckoutButtonMethod },\n sessionId: string | null,\n): boolean {\n if (!sessionId) return false;\n if (error.type === 'validation_error') return false;\n if (error.checkoutMethod && error.checkoutMethod !== 'card' && error.checkoutMethod !== 'paypal') {\n return false;\n }\n return true;\n}\n\nfunction readPayPalResumeState(): PayPalResumeState | null {\n if (!canUseStorage()) return null;\n\n try {\n const raw = window.sessionStorage.getItem(PAYPAL_RESUME_STORAGE_KEY);\n if (!raw) return null;\n return JSON.parse(raw) as PayPalResumeState;\n } catch {\n return null;\n }\n}\n\nfunction persistPayPalResumeState(state: PayPalResumeState) {\n if (!canUseStorage()) return;\n try {\n window.sessionStorage.setItem(PAYPAL_RESUME_STORAGE_KEY, JSON.stringify(state));\n } catch (error) {\n console.warn('[FloPayAutomaticPaymentButton] Failed to persist PayPal resume state.', error);\n }\n}\n\nfunction clearPayPalResumeState() {\n if (!canUseStorage()) return;\n try {\n window.sessionStorage.removeItem(PAYPAL_RESUME_STORAGE_KEY);\n } catch (error) {\n console.warn('[FloPayAutomaticPaymentButton] Failed to clear PayPal resume state.', error);\n }\n}\n\nfunction clearPayPalRedirectParams() {\n if (typeof window === 'undefined') return;\n\n const url = new URL(window.location.href);\n const keys = ['payment_intent', 'payment_intent_client_secret', 'redirect_status'];\n let changed = false;\n\n for (const key of keys) {\n if (url.searchParams.has(key)) {\n url.searchParams.delete(key);\n changed = true;\n }\n }\n\n if (changed) {\n window.history.replaceState({}, '', url.toString());\n }\n}\n\nexport interface FloPayAutomaticPaymentSuccessEvent {\n result: PaymentResult;\n session: CheckoutSession | null;\n sessionId: string | null;\n autoCompleted: boolean;\n}\n\nexport interface FloPayAutomaticPaymentButtonProps\n extends Omit<React.ButtonHTMLAttributes<HTMLButtonElement>, 'children' | 'onError'> {\n sessionId?: string;\n createSession?: InlineSessionDraft;\n paymentMethodId?: string;\n checkoutMethod?: CheckoutButtonMethod;\n clientId?: string;\n items?: CheckoutItem[];\n subscriptions?: CheckoutSubscription[];\n account?: InlineSessionDraft['account'];\n successUrl?: string;\n cancelUrl?: string;\n couponCodes?: string[];\n tagsData?: InlineSessionDraft['tagsData'];\n utmMetadata?: InlineSessionDraft['utmMetadata'];\n billingApiUrl?: string;\n locale?: string;\n buttonsTheme?: ButtonsLayoutTheme;\n buttonsStyles?: ButtonsLayoutStyles;\n onSuccess?: (event: FloPayAutomaticPaymentSuccessEvent) => void;\n onError?: (error: FloPayError) => void;\n onDecline?: (decline: DeclineEvent) => void;\n children?: React.ReactNode;\n}\n\nfunction resolveCreateSessionDraft(props: FloPayAutomaticPaymentButtonProps): InlineSessionDraft | null {\n if (props.createSession) {\n return {\n ...props.createSession,\n checkoutMode: 'auto',\n };\n }\n\n if (!props.clientId || !props.account || !props.successUrl || !props.cancelUrl) {\n return null;\n }\n\n return {\n clientId: props.clientId,\n items: props.items,\n subscriptions: props.subscriptions,\n account: props.account,\n successUrl: props.successUrl,\n cancelUrl: props.cancelUrl,\n couponCodes: props.couponCodes,\n tagsData: props.tagsData,\n utmMetadata: props.utmMetadata,\n checkoutMode: 'auto',\n };\n}\n\nexport function FloPayAutomaticPaymentButton({\n sessionId,\n createSession,\n paymentMethodId,\n checkoutMethod,\n clientId,\n items,\n subscriptions,\n account,\n successUrl,\n cancelUrl,\n couponCodes,\n tagsData,\n utmMetadata,\n billingApiUrl,\n locale,\n buttonsTheme,\n buttonsStyles: stylesOverride,\n onSuccess,\n onError,\n onDecline,\n children,\n disabled = false,\n type = 'button',\n style,\n ...buttonProps\n}: FloPayAutomaticPaymentButtonProps) {\n const resolvedBillingUrl = useMemo(\n () => resolveBillingApiUrl(billingApiUrl),\n [billingApiUrl],\n );\n const createSessionDraft = useMemo(\n () => resolveCreateSessionDraft({\n createSession,\n clientId,\n items,\n subscriptions,\n account,\n successUrl,\n cancelUrl,\n couponCodes,\n tagsData,\n utmMetadata,\n }),\n [\n account,\n cancelUrl,\n clientId,\n couponCodes,\n createSession,\n items,\n subscriptions,\n successUrl,\n tagsData,\n utmMetadata,\n ],\n );\n const [isProcessing, setIsProcessing] = useState(false);\n const [overlayStatus, setOverlayStatus] = useState<OverlayStatus | null>(null);\n const [overlayError, setOverlayError] = useState<string | null>(null);\n const [fallbackSession, setFallbackSession] = useState<{\n sessionId: string;\n errorMessage: string;\n } | null>(null);\n const automaticPaymentToken = useMemo(\n () => paymentMethodId\n ? {\n id: paymentMethodId,\n type: 'card' as const,\n ...(checkoutMethod === 'paypal' ? { isPaypal: true } : {}),\n }\n : undefined,\n [checkoutMethod, paymentMethodId],\n );\n\n const isMountedRef = useRef(true);\n const resumeAttemptedRef = useRef(false);\n const fallbackSessionRef = useRef(fallbackSession);\n const onSuccessRef = useRef(onSuccess);\n const onErrorRef = useRef(onError);\n const onDeclineRef = useRef(onDecline);\n\n useEffect(() => {\n fallbackSessionRef.current = fallbackSession;\n }, [fallbackSession]);\n\n useEffect(() => {\n onSuccessRef.current = onSuccess;\n }, [onSuccess]);\n\n useEffect(() => {\n onErrorRef.current = onError;\n }, [onError]);\n\n useEffect(() => {\n onDeclineRef.current = onDecline;\n }, [onDecline]);\n\n useEffect(() => {\n isMountedRef.current = true;\n return () => {\n isMountedRef.current = false;\n };\n }, []);\n\n useEffect(() => {\n if (!fallbackSession || typeof window === 'undefined') {\n return;\n }\n\n const handleKeyDown = (event: KeyboardEvent) => {\n if (event.key === 'Escape') {\n setFallbackSession(null);\n }\n };\n\n window.addEventListener('keydown', handleKeyDown);\n return () => {\n window.removeEventListener('keydown', handleKeyDown);\n };\n }, [fallbackSession]);\n\n const emitDecline = useCallback((error: FloPayError, method = DEFAULT_SAVED_PAYMENT_DECLINE_METHOD) => {\n onDeclineRef.current?.(buildDeclineEvent(method, error, {\n code: error.code,\n declineCode: error.declineCode,\n }));\n }, []);\n\n const showSuccess = useCallback(async (event: FloPayAutomaticPaymentSuccessEvent) => {\n if (!isMountedRef.current) return;\n\n setOverlayError(null);\n setOverlayStatus('success');\n await sleep(PROCESSING_OVERLAY_SUCCESS_DELAY_MS);\n\n if (!isMountedRef.current) return;\n onSuccessRef.current?.(event);\n }, []);\n\n const showError = useCallback(async (\n error: FloPayError,\n options?: {\n emitDecline?: boolean;\n method?: CheckoutButtonMethod;\n },\n ) => {\n if (!isMountedRef.current) return;\n\n onErrorRef.current?.(error);\n if (options?.emitDecline) {\n emitDecline(error, options.method);\n }\n\n setOverlayError(error.message);\n setOverlayStatus('error');\n await sleep(PROCESSING_OVERLAY_ERROR_DELAY_MS);\n }, [emitDecline]);\n\n const processResolvedSession = useCallback(async (\n apiResult: Awaited<ReturnType<PaymentAPI['getUnifiedCheckoutSession']>>,\n resolvedSessionId: string | null,\n options?: {\n fromCreateSession?: boolean;\n },\n ) => {\n const session = apiResult.data.session ?? null;\n if (!session) {\n throw new FloPayError('No session data returned', 'api_error');\n }\n\n if (session.status === 'complete') {\n await showSuccess({\n result: { status: 'succeeded' },\n session,\n sessionId: session.id || resolvedSessionId,\n autoCompleted: false,\n });\n return;\n }\n\n if (session.status === 'expired') {\n throw new FloPayError('Checkout session has expired.', 'api_error', {\n code: 'checkout_session_expired',\n });\n }\n\n try {\n let paymentResult: PaymentResult | null = null;\n const redirectResult = getRedirectResultFromCheckoutProcessError(apiResult.autoProcessingError);\n const shouldTreatCreateSessionFlowAsServerAutoAttempt =\n options?.fromCreateSession\n && (\n apiResult.autoProcessingAttempted === true\n || !!apiResult.autoProcessingError\n || !!redirectResult\n );\n const shouldRetryPayPalClientSide =\n checkoutMethod === 'paypal'\n && automaticPaymentToken?.isPaypal === true\n && options?.fromCreateSession === true;\n\n if (apiResult.autoProcessingPending) {\n const api = new PaymentAPI(resolvedBillingUrl);\n const completed = await api.waitForCheckoutSessionCompletion(apiResult.autoProcessingPending.sessionId, {\n initialDelayMs: apiResult.autoProcessingPending.retryAfterMs,\n });\n const completedSession = completed.data.session;\n\n if (!completedSession || completedSession.status !== 'complete') {\n throw new FloPayError('Automatic payment failed. Please try again.', 'api_error', {\n code: completedSession?.status === 'expired'\n ? 'checkout_session_expired'\n : 'checkout_processing_timeout',\n });\n }\n\n await showSuccess({\n result: {\n status: 'succeeded',\n paymentMethodId: paymentMethodId ?? undefined,\n checkoutMethod,\n },\n session: completedSession,\n sessionId: completedSession.id || resolvedSessionId,\n autoCompleted: false,\n });\n return;\n }\n\n if (redirectResult) {\n const {\n publishableKey,\n paypalPublishableKey,\n } = resolveSavedPaymentPublishableKeys(apiResult);\n\n if (redirectResult.type === 'paypal_redirect_required') {\n persistPayPalResumeState({\n sessionId: session.id || resolvedSessionId,\n publishableKey,\n paypalPublishableKey,\n });\n }\n\n const {\n flopay,\n paypalFlopay,\n } = await loadSavedPaymentProviders({\n publishableKey,\n paypalPublishableKey,\n billingApiUrl: resolvedBillingUrl,\n locale,\n });\n\n paymentResult = await handleSavedPaymentRedirectResult(redirectResult, {\n flopay,\n paypalFlopay,\n attempt3DS: true,\n billingApiUrl: resolvedBillingUrl,\n sessionId: session.id || resolvedSessionId,\n session,\n });\n\n if (redirectResult.type === 'paypal_redirect_required') {\n clearPayPalResumeState();\n }\n } else if (apiResult.autoProcessingError && !shouldRetryPayPalClientSide) {\n throw checkoutProcessErrorToFloPayError(\n apiResult.autoProcessingError,\n 'Automatic payment failed. Please try again.',\n {\n checkoutMethod: apiResult.autoProcessingError.checkoutMethod,\n },\n );\n } else if (shouldTreatCreateSessionFlowAsServerAutoAttempt && !shouldRetryPayPalClientSide) {\n throw checkoutProcessErrorToFloPayError(\n {\n type: 'unknown',\n message: 'Automatic payment failed. Please try again.',\n },\n 'Automatic payment failed. Please try again.',\n );\n } else {\n const result = await processSavedPaymentForMode({\n billingApiUrl: resolvedBillingUrl,\n sessionId: resolvedSessionId ?? session.id,\n session,\n tokenizedData: automaticPaymentToken,\n });\n\n paymentResult = result.type === 'success'\n ? result.result\n : null;\n\n if (result.type !== 'success') {\n const {\n publishableKey,\n paypalPublishableKey,\n } = resolveSavedPaymentPublishableKeys(apiResult);\n\n if (result.type === 'paypal_redirect_required') {\n persistPayPalResumeState({\n sessionId: session.id || resolvedSessionId,\n publishableKey,\n paypalPublishableKey,\n });\n }\n\n const {\n flopay,\n paypalFlopay,\n } = await loadSavedPaymentProviders({\n publishableKey,\n paypalPublishableKey,\n billingApiUrl: resolvedBillingUrl,\n locale,\n });\n\n paymentResult = await handleSavedPaymentRedirectResult(result, {\n flopay,\n paypalFlopay,\n attempt3DS: true,\n billingApiUrl: resolvedBillingUrl,\n sessionId: session.id || resolvedSessionId,\n session,\n });\n\n if (result.type === 'paypal_redirect_required') {\n clearPayPalResumeState();\n }\n }\n }\n\n await showSuccess({\n result: paymentResult\n ? {\n ...paymentResult,\n paymentMethodId: paymentResult.paymentMethodId ?? paymentMethodId,\n checkoutMethod: paymentResult.checkoutMethod ?? checkoutMethod,\n }\n : {\n status: 'succeeded',\n paymentMethodId: paymentMethodId ?? undefined,\n checkoutMethod,\n },\n session,\n sessionId: session.id || resolvedSessionId,\n autoCompleted: false,\n });\n } catch (err) {\n let floPayErr = normalizeSavedPaymentError(err);\n const fallbackSessionId = session.id || resolvedSessionId;\n const shouldTreatCreateSessionFlowAsServerAutoAttempt =\n options?.fromCreateSession\n && apiResult.autoProcessingAttempted === true;\n\n if (\n !shouldTreatCreateSessionFlowAsServerAutoAttempt &&\n floPayErr.code === 'authentication_required'\n && fallbackSessionId\n && automaticPaymentToken?.id\n && automaticPaymentToken.id.startsWith('pm_')\n ) {\n try {\n const {\n publishableKey,\n paypalPublishableKey,\n } = resolveSavedPaymentPublishableKeys(apiResult);\n const {\n flopay,\n } = await loadSavedPaymentProviders({\n publishableKey,\n paypalPublishableKey,\n billingApiUrl: resolvedBillingUrl,\n locale,\n });\n\n const paymentResult = await processSavedPaymentWithIntent({\n billingApiUrl: resolvedBillingUrl,\n sessionId: fallbackSessionId,\n session,\n paymentMethodId: automaticPaymentToken.id,\n flopay,\n });\n\n await showSuccess({\n result: {\n ...paymentResult,\n paymentMethodId: paymentResult.paymentMethodId ?? paymentMethodId,\n checkoutMethod: paymentResult.checkoutMethod ?? checkoutMethod,\n },\n session,\n sessionId: fallbackSessionId,\n autoCompleted: false,\n });\n return;\n } catch (intentRecoveryErr) {\n floPayErr = normalizeSavedPaymentError(intentRecoveryErr);\n }\n }\n\n // When `confirmPayment` resumes after a PayPal redirect and the PI is\n // already past `requires_action` (manual-capture PayPal lands at\n // `requires_capture` post-authorization), Stripe.js rejects the original\n // promise with `payment_intent_unexpected_state`. The redirect itself\n // succeeded — the resume `useEffect` below will pick up the URL params\n // and finish the capture via /process. Don't open the fallback in that\n // case, otherwise we'd double-charge by re-running PayPal in the modal.\n const inResumeWindow = typeof window !== 'undefined'\n && new URLSearchParams(window.location.search).has('payment_intent_client_secret')\n && !!readPayPalResumeState();\n if (floPayErr.code === 'payment_intent_unexpected_state' && inResumeWindow) {\n return;\n }\n\n // Silent-fallback for cross-account PayPal saved-PM auto attempts: the\n // backend can't attach the saved PM to a PI on the dedicated PayPal\n // gateway, so it returns `paypal_redirect_required` without a\n // `paymentMethodId`. `handleSavedPaymentRedirectResult` recognizes this\n // and throws `paypal_requires_user_interaction` for us. The recovery\n // path is the full-checkout fallback (where `ExpressCheckoutElement`\n // mints a fresh PM during user-driven PayPal click) — open it directly\n // without surfacing an error toast or a decline event, since this\n // isn't a real failure, just a flow handoff.\n //\n // We also catch `payment_intent_unexpected_state` outside the resume\n // window as a defense-in-depth: if Stripe.js returns it for any other\n // reason on the saved-payment auto path, the fallback can recover.\n const isSilentFallbackCase =\n (floPayErr.code === 'paypal_requires_user_interaction'\n || floPayErr.code === 'payment_intent_unexpected_state')\n && shouldShowFallbackCheckout(floPayErr, fallbackSessionId)\n && !!fallbackSessionId\n && isMountedRef.current;\n if (isSilentFallbackCase) {\n setFallbackSession({\n sessionId: fallbackSessionId,\n errorMessage: '',\n });\n return;\n }\n\n await showError(floPayErr, {\n emitDecline: true,\n method: floPayErr.checkoutMethod ?? DEFAULT_SAVED_PAYMENT_DECLINE_METHOD,\n });\n if (\n shouldShowFallbackCheckout(floPayErr, fallbackSessionId) &&\n fallbackSessionId &&\n isMountedRef.current\n ) {\n setFallbackSession({\n sessionId: fallbackSessionId,\n errorMessage: floPayErr.message,\n });\n }\n }\n }, [\n checkoutMethod,\n locale,\n automaticPaymentToken,\n paymentMethodId,\n resolvedBillingUrl,\n showError,\n showSuccess,\n ]);\n\n const handleButtonClick = useCallback(async (event: React.MouseEvent<HTMLButtonElement>) => {\n buttonProps.onClick?.(event);\n\n if (event.defaultPrevented || disabled || isProcessing) {\n return;\n }\n\n setFallbackSession(null);\n\n if (sessionId && createSessionDraft) {\n const error = new FloPayError(\n 'Provide either sessionId or create-session props, not both.',\n 'validation_error',\n );\n await showError(error);\n if (isMountedRef.current) {\n setOverlayStatus(null);\n setOverlayError(null);\n }\n return;\n }\n\n if (!sessionId && !createSessionDraft) {\n const error = new FloPayError(\n 'Provide a sessionId or the props required to create an automatic payment session.',\n 'validation_error',\n );\n await showError(error);\n if (isMountedRef.current) {\n setOverlayStatus(null);\n setOverlayError(null);\n }\n return;\n }\n\n setIsProcessing(true);\n setOverlayError(null);\n setOverlayStatus('processing');\n\n try {\n const api = new PaymentAPI(resolvedBillingUrl);\n\n if (sessionId) {\n const result = await api.getUnifiedCheckoutSession(sessionId);\n await processResolvedSession(result, sessionId);\n return;\n }\n\n try {\n const result = await api.createAndFetchSession({\n ...createSessionDraft!,\n ...(automaticPaymentToken ? { tokenizedData: automaticPaymentToken } : {}),\n });\n await processResolvedSession(result, result.data.session?.id ?? null, {\n fromCreateSession: true,\n });\n } catch (err) {\n if (err instanceof FloPayError && err.code === 'session_auto_completed') {\n await showSuccess({\n result: { status: 'succeeded' },\n session: null,\n sessionId: null,\n autoCompleted: true,\n });\n return;\n }\n\n throw err;\n }\n } catch (err) {\n await showError(\n coerceError(err, 'Automatic payment failed. Please try again.'),\n );\n } finally {\n if (isMountedRef.current) {\n setOverlayStatus(null);\n setOverlayError(null);\n setIsProcessing(false);\n }\n }\n }, [\n buttonProps,\n createSessionDraft,\n disabled,\n isProcessing,\n processResolvedSession,\n resolvedBillingUrl,\n sessionId,\n showError,\n showSuccess,\n ]);\n\n const handleFallbackComplete = useCallback((result: PaymentResult) => {\n const activeFallback = fallbackSessionRef.current;\n setFallbackSession(null);\n onSuccessRef.current?.({\n result,\n session: null,\n sessionId: activeFallback?.sessionId ?? null,\n autoCompleted: false,\n });\n }, []);\n\n const handleFallbackError = useCallback((error: FloPayError) => {\n onErrorRef.current?.(error);\n }, []);\n\n const handleFallbackDecline = useCallback((decline: DeclineEvent) => {\n onDeclineRef.current?.(decline);\n }, []);\n\n useEffect(() => {\n if (typeof window === 'undefined' || resumeAttemptedRef.current) {\n return;\n }\n\n const params = new URLSearchParams(window.location.search);\n const clientSecret = params.get('payment_intent_client_secret');\n if (!clientSecret) {\n return;\n }\n\n const resumeState = readPayPalResumeState();\n if (!resumeState) {\n return;\n }\n\n resumeAttemptedRef.current = true;\n\n void (async () => {\n setIsProcessing(true);\n setOverlayError(null);\n setOverlayStatus('processing');\n\n try {\n if (params.get('redirect_status') === 'failed') {\n throw Object.assign(\n new FloPayError('PayPal payment was declined. Please try again.', 'api_error'),\n { checkoutMethod: 'paypal' as const },\n );\n }\n\n const {\n flopay,\n paypalFlopay,\n } = await loadSavedPaymentProviders({\n publishableKey: resumeState.publishableKey,\n paypalPublishableKey: resumeState.paypalPublishableKey,\n billingApiUrl: resolvedBillingUrl,\n locale,\n });\n\n const paypalStripe = (paypalFlopay ?? flopay).getRawProvider() as import('@stripe/stripe-js').Stripe | null;\n if (!paypalStripe) {\n throw Object.assign(\n new FloPayError('PayPal is not available.', 'api_error'),\n { checkoutMethod: 'paypal' as const },\n );\n }\n\n const { paymentIntent, error } = await paypalStripe.retrievePaymentIntent(clientSecret);\n if (error) {\n throw Object.assign(\n new FloPayError(\n error.message ?? 'Failed to retrieve PayPal payment status.',\n 'api_error',\n { code: error.code },\n ),\n { checkoutMethod: 'paypal' as const },\n );\n }\n\n const resultStatus = mapPayPalIntentStatusToPaymentResult(paymentIntent?.status);\n\n if (!paymentIntent || resultStatus === 'failed') {\n throw Object.assign(\n new FloPayError('PayPal payment was not completed. Please try again.', 'api_error'),\n { checkoutMethod: 'paypal' as const },\n );\n }\n\n const paymentMethodId = typeof paymentIntent.payment_method === 'string'\n ? paymentIntent.payment_method\n : paymentIntent.payment_method?.id;\n\n // Backend has manual capture mode, so PayPal-authorized PIs land at\n // `requires_capture` and the backend must be told to capture via\n // POST /v1/checkouts/sessions/process. Without this call the PI sits\n // at requires_capture forever (\"Uncaptured\" in Stripe).\n if (!resumeState.sessionId) {\n throw Object.assign(\n new FloPayError('Missing session id on PayPal resume.', 'api_error'),\n { checkoutMethod: 'paypal' as const },\n );\n }\n\n const api = new PaymentAPI(resolvedBillingUrl);\n const sessionResult = await api.getUnifiedCheckoutSession(resumeState.sessionId);\n let resumeSession = sessionResult.data.session;\n if (!resumeSession) {\n throw Object.assign(\n new FloPayError('Could not load session to capture PayPal payment.', 'api_error'),\n { checkoutMethod: 'paypal' as const },\n );\n }\n\n let finalResultStatus: PaymentResult['status'] = resultStatus;\n if (resumeSession.status !== 'complete') {\n const processResult = await processSavedPaymentForMode({\n billingApiUrl: resolvedBillingUrl,\n sessionId: resumeState.sessionId,\n session: resumeSession,\n tokenizedData: {\n id: paymentMethodId ?? paymentIntent.id,\n type: 'card',\n threeDSecureActionResultTokenId: paymentIntent.id,\n isPaypal: true,\n },\n });\n\n if (processResult.type !== 'success') {\n throw Object.assign(\n new FloPayError('Failed to finalize PayPal payment.', 'api_error'),\n { checkoutMethod: 'paypal' as const },\n );\n }\n\n // /process succeeded -> backend captured the PI and marked the\n // session complete. Refresh the session so the snapshot we hand to\n // `onSuccess` reflects the post-capture state instead of the\n // pre-capture one we fetched above. Trust /process's result.status\n // ('succeeded') over the PI's pre-capture status mapping.\n finalResultStatus = processResult.result.status;\n try {\n const refreshed = await api.getUnifiedCheckoutSession(resumeState.sessionId);\n if (refreshed.data.session) {\n resumeSession = refreshed.data.session;\n }\n } catch {\n // Refresh is best-effort; if it fails the buyer is still captured\n // and we'll fall back to the pre-capture session snapshot rather\n // than failing the whole flow.\n }\n }\n\n await showSuccess({\n result: {\n status: finalResultStatus,\n paymentIntentId: paymentIntent.id,\n paymentMethodId,\n checkoutMethod: 'paypal',\n },\n session: resumeSession,\n sessionId: resumeState.sessionId,\n autoCompleted: false,\n });\n } catch (err) {\n const floPayErr = normalizeSavedPaymentError(err);\n await showError(floPayErr, {\n emitDecline: true,\n method: floPayErr.checkoutMethod ?? 'paypal',\n });\n } finally {\n clearPayPalResumeState();\n clearPayPalRedirectParams();\n\n if (isMountedRef.current) {\n setOverlayStatus(null);\n setOverlayError(null);\n setIsProcessing(false);\n }\n }\n })();\n }, [locale, resolvedBillingUrl, showError, showSuccess]);\n\n const bStyles = useMemo<ButtonsLayoutStyles>(() => {\n const base = resolveButtonsLayoutTheme(buttonsTheme);\n if (!stylesOverride) return base;\n return {\n ...base,\n ...stylesOverride,\n cardButton: { ...base.cardButton, ...stylesOverride.cardButton },\n };\n }, [buttonsTheme, stylesOverride]);\n\n const cardButtonSizing = children === undefined\n ? { boxSizing: 'border-box' as const, height: DEFAULT_BUTTONS_LAYOUT_BUTTON_HEIGHT, padding: '0 1rem' }\n : { padding: '0.9rem 1rem' };\n\n return (\n <>\n <button\n {...buttonProps}\n type={type}\n onClick={handleButtonClick}\n disabled={disabled || isProcessing}\n aria-busy={isProcessing}\n style={{\n width: '100%',\n ...cardButtonSizing,\n backgroundColor: 'white',\n color: '#262833',\n border: '1px solid #d1d5db',\n borderRadius: '8px',\n fontSize: bStyles.cardButtonFontSize ?? '0.95rem',\n fontWeight: 600,\n cursor: disabled || isProcessing ? 'not-allowed' : 'pointer',\n display: 'flex',\n alignItems: 'center',\n justifyContent: 'center',\n gap: '0.625rem',\n boxShadow: '0 1px 2px rgba(0,0,0,0.04)',\n transition: 'border-color 0.2s, box-shadow 0.2s, transform 0.1s',\n position: 'relative',\n opacity: disabled || isProcessing ? 0.6 : 1,\n ...bStyles.cardButton as React.CSSProperties,\n ...style,\n }}\n onMouseDown={(e) => {\n buttonProps.onMouseDown?.(e);\n if (!e.defaultPrevented) {\n e.currentTarget.style.transform = 'scale(0.985)';\n }\n }}\n onMouseUp={(e) => {\n buttonProps.onMouseUp?.(e);\n if (!e.defaultPrevented) {\n e.currentTarget.style.transform = 'scale(1)';\n }\n }}\n >\n <CardButtonContentSlot content={children} />\n </button>\n {overlayStatus && (\n <ProcessingOverlay\n status={overlayStatus}\n errorMessage={overlayError}\n />\n )}\n {fallbackSession && (\n <div\n data-testid=\"flopay-automatic-payment-fallback\"\n role=\"dialog\"\n aria-modal=\"true\"\n onClick={(event) => {\n if (event.target === event.currentTarget) {\n setFallbackSession(null);\n }\n }}\n style={{\n position: 'fixed',\n inset: 0,\n background: 'rgba(0, 0, 0, 0.45)',\n display: 'flex',\n alignItems: 'center',\n justifyContent: 'center',\n padding: '1.5rem',\n zIndex: 1100,\n }}\n >\n <div\n style={{\n width: '100%',\n maxWidth: 520,\n maxHeight: '90vh',\n overflowY: 'auto',\n background: 'white',\n borderRadius: 20,\n padding: '1.5rem',\n boxShadow: '0 24px 80px rgba(15, 23, 42, 0.28)',\n display: 'flex',\n flexDirection: 'column',\n gap: '1rem',\n }}\n >\n <FloPayCheckout\n sessionId={fallbackSession.sessionId}\n checkoutMode=\"full\"\n billingApiUrl={resolvedBillingUrl}\n initialErrorMessage={fallbackSession.errorMessage}\n cardTitleContent={null}\n showSecurityFooter={false}\n onComplete={handleFallbackComplete}\n onError={handleFallbackError}\n onDecline={handleFallbackDecline}\n />\n </div>\n </div>\n )}\n </>\n );\n}\n"],"mappings":";AAAA,SAAgB,WAAW,UAAU,eAAe;AAGpD,SAAS,4BAA4B;;;ACHrC,SAAS,qBAAqB;AAmCvB,IAAM,gBAAgB,cAAkC;AAAA,EAC7D,QAAQ;AAAA,EACR,cAAc;AAAA,EACd,UAAU;AAAA,EACV,eAAe;AACjB,CAAC;AAEM,IAAM,kBAAkB,cAAoC;AAAA,EACjE,SAAS;AAAA,EACT,SAAS;AAAA,EACT,OAAO;AACT,CAAC;;;AD+FG;AA/FG,SAAS,eAAe;AAAA,EAC7B,QAAQ;AAAA,EACR,cAAc;AAAA,EACd;AAAA,EACA;AACF,GAA4C;AAC1C,QAAM,CAAC,QAAQ,SAAS,IAAI;AAAA,IAC1B,sBAAsB,UAAU,OAAO;AAAA,EACzC;AACA,QAAM,CAAC,cAAc,eAAe,IAAI;AAAA,IACtC,4BAA4B,WAAW,CAAC,mBAAmB,OAAO;AAAA,EACpE;AACA,QAAM,CAAC,UAAU,WAAW,IAAI,SAAgC,IAAI;AAGpE,YAAU,MAAM;AACd,QAAI,YAAY;AAEhB,QAAI,sBAAsB,SAAS;AACjC,iBAAW,KAAK,CAAC,aAAa;AAC5B,YAAI,CAAC,WAAW;AACd,oBAAU,QAAQ;AAAA,QACpB;AAAA,MACF,CAAC;AAAA,IACH,OAAO;AACL,gBAAU,UAAU;AAAA,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UAAU;AAClB,cAAI,MAAM,WAAW,MAAM,eAAe;AACxC,+BAAmB,IAAI;AAAA,UACzB;AAAA,QACF;AAAA,QACA,OAAO;AAAA,UACL,UAAU;AAAA,UACV,OAAO;AAAA,UACP,YAAY;AAAA,UACZ,SAAS;AAAA,UACT,YAAY;AAAA,UACZ,gBAAgB;AAAA,UAChB,SAAS;AAAA,UACT,QAAQ;AAAA,QACV;AAAA,QAEA,0BAAAA;AAAA,UAAC;AAAA;AAAA,YACC,OAAO;AAAA,cACL,OAAO;AAAA,cACP,UAAU;AAAA,cACV,WAAW;AAAA,cACX,WAAW;AAAA,cACX,YAAY;AAAA,cACZ,cAAc;AAAA,cACd,SAAS;AAAA,cACT,WAAW;AAAA,cACX,SAAS;AAAA,cACT,eAAe;AAAA,cACf,KAAK;AAAA,YACP;AAAA,YAEA,0BAAAA;AAAA,cAAC;AAAA;AAAA,gBACC,WAAW,gBAAgB;AAAA,gBAC3B,cAAa;AAAA,gBACb,eAAe;AAAA,gBACf,qBAAqB,gBAAgB;AAAA,gBACrC,kBAAkB;AAAA,gBAClB,oBAAoB;AAAA,gBACpB,YAAY;AAAA,gBACZ,SAAS;AAAA,gBACT,WAAW;AAAA;AAAA,YACb;AAAA;AAAA,QACF;AAAA;AAAA,IACF;AAAA,KAEJ;AAEJ;","names":["React","useCallback","useEffect","useMemo","useRef","useState","PaymentAPI","FloPayError","resolveBillingApiUrl","resolveButtonsLayoutTheme","jsx","useEffect","jsx","useEffect","useContext","useEffect","useMemo","useRef","useState","useContext","resolveBillingApiUrl","useContext","resolveBillingApiUrl","jsx","jsxs","FloPayError","Fragment","jsx","jsxs","SplitCardForm","useState","useEffect","useRef","useContext","useMemo","stateValue","message","error","PaymentAPI","FloPayError","FloPayError","PaymentAPI","error","Fragment","jsx","jsxs","DEFAULT_BUTTONS_LAYOUT_BUTTON_HEIGHT","resolveBillingApiUrl","useState","useRef","useEffect","useMemo","useCallback","activeSessionId","PaymentAPI","FloPayError","React","resolveButtonsLayoutTheme","PaymentAPI","FloPayError","forwardRef","useCallback","useEffect","useImperativeHandle","useState","Fragment","jsx","jsxs","WALLET_RESUME_KEY","forwardRef","CheckoutForm","useState","useCallback","PaymentAPI","useImperativeHandle","useEffect","FloPayError","error","PaymentAPI","FloPayError","useCallback","useEffect","useRef","useState","Fragment","jsx","jsxs","useState","useRef","useCallback","PaymentAPI","useEffect","FloPayError","useCallback","useEffect","useMemo","useRef","useState","PaymentAPI","FloPayError","resolveBillingApiUrl","resolveButtonsLayoutTheme","Fragment","jsx","jsxs","DEFAULT_BUTTONS_LAYOUT_BUTTON_HEIGHT","PAYPAL_RESUME_STORAGE_KEY","sleep","FloPayError","canUseStorage","readPayPalResumeState","persistPayPalResumeState","clearPayPalResumeState","clearPayPalRedirectParams","useMemo","resolveBillingApiUrl","useState","useRef","useEffect","useCallback","PaymentAPI","paymentMethodId","resolveButtonsLayoutTheme"]}
|