@flopay/react 1.2.0 → 1.2.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +9 -1
- package/dist/index.cjs +170 -32
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +30 -2
- package/dist/index.d.ts +30 -2
- package/dist/index.mjs +170 -32
- package/dist/index.mjs.map +1 -1
- package/package.json +5 -5
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../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/direct-paypal-button.tsx","../src/saved-payment-flow.ts","../src/checkout-form.tsx","../src/paypal-button.tsx","../src/automatic-payment-button.tsx"],"sourcesContent":["// Provider\nexport { FloPayProvider } from './provider.js';\nexport type { FloPayProviderProps } from './provider.js';\n\n// FloPayCheckout (recommended — all-in-one checkout)\nexport { FloPayCheckout } from './flopay-checkout.js';\nexport type { FloPayCheckoutProps } from './flopay-checkout.js';\nexport type {\n BeforeButtonClickEvent,\n CheckoutButtonMethod,\n DeclineEvent,\n InlineSessionDraft,\n InlineSessionPatch,\n} from '@flopay/shared';\n\n// Hooks\nexport { useFloPay, usePayPalFloPay, useElements, useCheckout } from './hooks.js';\nexport type { CheckoutState } from './hooks.js';\n\n// Element Components\nexport {\n PaymentElement,\n CardElement,\n CardNumberElement,\n CardExpiryElement,\n CardCvcElement,\n AddressElement,\n} from './elements.js';\nexport type { ElementComponentProps } from './elements.js';\n\n// CheckoutForm\nexport { CheckoutForm } from './checkout-form.js';\nexport type { CheckoutFormProps, CheckoutFormRef } from './checkout-form.js';\n\n// SplitCardForm\nexport { SplitCardForm } from './split-card-form.js';\nexport type { SplitCardFormProps, SplitCardFormRef } from './split-card-form.js';\n\n// PayPalButton (Stripe-rendered fallback)\nexport { PayPalButton } from './paypal-button.js';\nexport type { PayPalButtonProps } from './paypal-button.js';\n\n// DirectPayPalButton (PayPal JS SDK — in-app browser compatible)\nexport { DirectPayPalButton } from './direct-paypal-button.js';\nexport type { DirectPayPalButtonProps } from './direct-paypal-button.js';\n\n// FloPayAutomaticPaymentButton\nexport { FloPayAutomaticPaymentButton } from './automatic-payment-button.js';\nexport type {\n FloPayAutomaticPaymentButtonProps,\n FloPayAutomaticPaymentSuccessEvent,\n} from './automatic-payment-button.js';\n","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 Stripe `FloPay` instance used to drive the Stripe-rendered PayPal\n * fallback. When omitted or `null`, the Stripe-rendered PayPal button is\n * not rendered. Direct PayPal (`gateways.paypal`) does not use this prop.\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 * Stripe FloPay instance used for the Stripe-rendered PayPal fallback. When\n * direct PayPal (`gateways.paypal`) is configured this isn't used for\n * rendering — DirectPayPalButton talks to PayPal directly — but the\n * Stripe-PayPal saved-PM redirect leg still relies on it.\n * `null` or absent means the Stripe-rendered PayPal fallback is unavailable.\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, resolveTheme } 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 { DirectPayPalButton } from './direct-paypal-button.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\ninterface DirectPayPalConfig {\n clientId: string;\n environment?: import('@flopay/shared').GatewayEnvironment;\n}\n\nfunction resolveDirectPaypalConfig(\n unified: NormalizedCheckoutSession | null,\n): DirectPayPalConfig | undefined {\n const clientId = unified?.data.paypal?.publishableKey;\n if (!clientId) return undefined;\n return {\n clientId,\n environment: unified?.data.paypal?.environment,\n };\n}\n\nfunction isPayPalOnlyUnified(unified: NormalizedCheckoutSession | null): boolean {\n if (!unified) return false;\n if (unified.data.stripe?.publishableKey) return false;\n return Boolean(resolveDirectPaypalConfig(unified)?.clientId);\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 * Session-bound checkout token (the `nonce` returned when the session was\n * created). Sent as the `x-checkout-session-token` header when fetching a\n * session by `sessionId`. Required by post-#640 backends, which no longer\n * let the UUID alone authorize a session read; harmless on older backends.\n * Only consulted in the `sessionId` flow — inline `createSession` sessions\n * carry their own freshly-minted nonce server-side.\n */\n nonce?: 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 /**\n * Show the PayPal payment surface (default: `true`). Renderer is chosen\n * from `gateways.paypal` on the session — DirectPayPalButton when present,\n * Stripe-rendered PayPal otherwise.\n */\n showPayPal?: boolean;\n /**\n * Show the Stripe-rendered checkout — card fields, ExpressCheckoutElement,\n * and the PaymentElement accordion (default: `true`). When `false`, only\n * `DirectPayPalButton` can render. Both `showStripe=false` and\n * `showPayPal=false` (with no PayPal gateway configured) triggers a\n * bootstrap-time validation error.\n */\n showStripe?: boolean;\n /**\n * @deprecated Apple Pay availability is now driven by\n * `gateways.stripe.enabledPaymentMethods` on the per-session response from\n * the billing API. Setting this prop emits a one-time deprecation warning\n * and is otherwise ignored once the backend ships the list.\n */\n showApplePay?: boolean;\n /**\n * @deprecated See {@link FloPayCheckoutProps.showApplePay}.\n */\n showGooglePay?: boolean;\n /**\n * Enables on-screen diagnostic panels (PayPal gate decision, DirectPayPalButton\n * lifecycle). Intended for debugging in-app browsers (Facebook, Instagram, etc.)\n * where remote console access is impractical. Off by default.\n */\n debug?: boolean;\n /** Layout mode: 'default' (all visible) or 'buttons' (PayPal/wallets + expandable card form). */\n layout?: 'default' | 'buttons';\n /**\n * High-level theme bundle that styles both the Stripe-side appearance and\n * the FloPay wrapper / submit / inputs. One of: `'classic'` (historic FloPay\n * look, no bundle applied), `'modern-light'`, `'modern-dark'`,\n * `'bold-light'`, `'bold-dark'`, `'glass-light'`, `'glass-dark'`. Explicit\n * `appearance` / `buttonsStyles` props still override their respective\n * halves when supplied.\n */\n theme?: import('@flopay/shared').ThemeId;\n /**\n * @deprecated Use `theme` instead. Legacy buttons-layout preset\n * (`'default' | 'minimal' | 'rounded' | 'dark'`). Still honored for\n * back-compat.\n */\n buttonsTheme?: import('@flopay/shared').ButtonsLayoutTheme;\n /** Style overrides merged on top of the resolved theme bundle / buttonsTheme 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 /**\n * @deprecated No longer rendered — the default-layout security footer was\n * removed alongside the theme-bundle refactor. Retained as an optional\n * prop so existing integrations type-check without changes.\n */\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 `gateways.stripe.publishableKey`. Accepted only\n * for 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 nonce: nonceProp,\n createSession: createSessionParams,\n billingApiUrl,\n appearance: appearanceOverride,\n locale,\n loading: loadingNode,\n error: errorNode,\n onComplete,\n onError,\n onDecline,\n onFullNameChange,\n onCountryChange,\n onZipChange,\n showPayPal = true,\n showStripe = true,\n showApplePay = true,\n showGooglePay = true,\n debug = false,\n layout,\n theme,\n buttonsTheme,\n buttonsStyles,\n cardButtonContent,\n cardBackButtonContent,\n cardTitleContent,\n showSecurityFooter: _showSecurityFooter,\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 // High-level `theme` resolves to a coherent {appearance, buttonsLayout}\n // bundle from `@flopay/shared`'s `THEMES` map. Explicit `appearance` /\n // `buttonsStyles` props still win — see the precedence comment in\n // `SplitCardForm`.\n const themeBundle = useMemo(() => resolveTheme(theme), [theme]);\n const appearance = appearanceOverride ?? themeBundle?.appearance;\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?.publishableKey\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?.publishableKey\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 cur: params?.currency ?? '',\n a: {\n e: params?.account?.email?.trim().toLowerCase() ?? '',\n country: params?.account?.country ?? '',\n },\n successUrl: params?.successUrl,\n cancelUrl: params?.cancelUrl,\n // Unified products[] is the post-#760 wire shape. Must be included or\n // carts that only set `products` (no legacy items/subscriptions) all\n // hash to the same key — the bootstrap effect's `createSessionHash`\n // dep then never changes when products change, the session-id cache\n // hits the wrong session, and the backend's enabledPaymentMethods\n // result for the *previous* cart sticks until a fresh page-load with\n // the session cache cleared.\n p: params?.products?.map(x => `${x.type ?? ''}:${x.code ?? x.providerItemId ?? x.providerPlanId ?? ''}:${x.totalAmount ?? ''}:${x.overrideAmount ?? ''}:${x.quantity ?? 1}`).sort(),\n i: params?.items?.map(x => `${x.code ?? x.providerItemId ?? ''}:${x.totalAmount ?? ''}:${x.overrideAmount ?? ''}:${x.quantity ?? 1}`).sort(),\n s: params?.subscriptions?.map(x => `${x.code ?? 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 // PayPal-only sessions can't run saved-payment auto-checkout:\n // `handleSavedPaymentRedirectResult` requires a Stripe provider for\n // 3DS recovery, and there's no card-on-file to charge. Skip the\n // auto flow and let the render path drop to `DirectPayPalButton`.\n const resolvedPaypalOnly = isPayPalOnlyUnified(resolved.result);\n\n if (\n !cancelled &&\n shouldAutoProcessInlineSession &&\n resolvedSession &&\n !resolvedPaypalOnly\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 if (resolvedPaypalOnly) {\n autoCheckoutAttempted.current = true;\n }\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, nonceProp);\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 // PayPal-only sessions skip auto saved-payment processing — there's\n // no Stripe provider for 3DS recovery, so the render path drops\n // straight to `DirectPayPalButton`.\n const paypalOnly = isPayPalOnlyUnified(result);\n\n if (\n effectiveMode === 'auto' &&\n !autoCheckoutAttempted.current &&\n !hasPayPalRedirectParams &&\n !paypalOnly\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 nonceProp,\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 const directPaypalConfig = resolveDirectPaypalConfig(unified);\n // PayPal-only sessions advertise `gateways.paypal` without `gateways.stripe`.\n // Stripe Elements (and the SplitCardForm card surface that depends on them)\n // can't mount in that case, so we render `DirectPayPalButton` as the sole\n // payment surface and bypass `FloPayProvider` entirely.\n const isPaypalOnlySession = isPayPalOnlyUnified(unified);\n\n // Provider options from session data. Only meaningful when Stripe is\n // available — PayPal-only sessions never mount Stripe Elements.\n const providerOptions = useMemo(() => {\n if (!unified || !session || !unified.data.stripe?.publishableKey) 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 (unified.data.stripe?.clientSecret) {\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 !isPaypalOnlySession &&\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. Wallet/card skeletons are\n // gated on `showStripe` so a PayPal-only checkout doesn't briefly flash\n // Stripe affordances during bootstrap.\n if (layout === 'buttons') {\n // Match the theme's tile border-radius so the loading skeletons line\n // up with the eventual buttons. `bundleRadius` reads from the\n // resolved theme bundle's `cardButton.borderRadius` (e.g. `14px` for\n // modern, `20px` for glass) and falls back to the appearance\n // variable, then `8px` for classic.\n const bundleRadius =\n (themeBundle?.buttonsLayout?.cardButton?.borderRadius as string | number | undefined) ??\n (themeBundle?.appearance.variables?.borderRadius as string | undefined) ??\n 8;\n const skeletonBar = (h: number) => (\n <div style={{\n height: h, borderRadius: bundleRadius, 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 {showStripe && (showApplePay || showGooglePay) && skeletonBar(DEFAULT_BUTTONS_LAYOUT_BUTTON_HEIGHT)}\n {showStripe && 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 showStripe={showStripe}\n showApplePay={showApplePay}\n showGooglePay={showGooglePay}\n theme={theme}\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 // PayPal-only session: render DirectPayPalButton as the sole payment\n // surface. Stripe Elements never mount, so we bypass FloPayProvider /\n // SplitCardForm entirely.\n if (isPaypalOnlySession && session && directPaypalConfig) {\n return (\n <>\n <CheckoutContext.Provider value={checkoutValue}>\n <div className={className} style={{ display: 'flex', flexDirection: 'column', gap: '0.5rem' }}>\n {modeError && (\n <div\n role=\"alert\"\n data-testid=\"flopay-error\"\n style={{\n padding: '0.625rem 0.875rem',\n background: '#FEF2F2',\n border: '1px solid #FECACA',\n borderRadius: '8px',\n color: '#991B1B',\n fontSize: '0.85rem',\n fontWeight: 600,\n }}\n >\n {modeError}\n </div>\n )}\n <DirectPayPalButton\n sessionId={activeSessionId}\n billingApiUrl={resolvedBillingUrl}\n email={session.customer?.email}\n clientId={directPaypalConfig.clientId}\n environment={directPaypalConfig.environment}\n currency={(session.currency ?? 'usd').toUpperCase()}\n isSubscription={session.mode === 'subscription'}\n onComplete={onComplete}\n onErrorChange={setModeError}\n onDecline={onDecline}\n onButtonClick={onButtonClick}\n session={session}\n debug={debug}\n />\n </div>\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 showStripe={showStripe}\n enabledPaymentMethods={unified?.data.stripe?.enabledPaymentMethods}\n showApplePay={showApplePay}\n showGooglePay={showGooglePay}\n layout={layout}\n theme={theme}\n buttonsTheme={buttonsTheme}\n buttonsStyles={buttonsStyles}\n appearance={appearance}\n cardButtonContent={cardButtonContent}\n cardBackButtonContent={cardBackButtonContent}\n cardTitleContent={cardTitleContent}\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 directPaypal={resolveDirectPaypalConfig(unified)}\n isSubscription={session?.mode === 'subscription'}\n session={session}\n debug={debug}\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 showStripe = true,\n showApplePay,\n showGooglePay,\n theme,\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 showStripe?: boolean;\n showApplePay: boolean;\n showGooglePay: boolean;\n theme?: import('@flopay/shared').ThemeId;\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 themeBundle = useMemo(() => resolveTheme(theme), [theme]);\n const bStyles = useMemo<ButtonsLayoutStyles>(() => {\n const base = themeBundle?.buttonsLayout ?? 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 }, [themeBundle, buttonsTheme, stylesOverride]);\n\n // Match the theme's tile radius so the interim skeletons line up with the\n // eventual buttons. Same derivation as the FloPayCheckout loading path\n // above — keeps the two skeleton surfaces consistent.\n const skeletonRadius =\n (themeBundle?.buttonsLayout?.cardButton?.borderRadius as string | number | undefined) ??\n (themeBundle?.appearance.variables?.borderRadius as string | undefined) ??\n 8;\n const skeleton = (h: number) => (\n <div style={{\n height: h, borderRadius: skeletonRadius, 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={{\n flex: 1, backgroundColor: inputBg,\n borderTop: 'none', borderRight: 'none',\n borderBottom: `1px solid ${inputBorder}`, borderLeft: `1px solid ${inputBorder}`,\n borderBottomLeftRadius: 8, padding: 12, height: 45,\n }}>\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={{\n flex: 1, backgroundColor: inputBg,\n borderTop: 'none',\n borderRight: `1px solid ${inputBorder}`,\n borderBottom: `1px solid ${inputBorder}`,\n borderLeft: `1px solid ${inputBorder}`,\n borderBottomRightRadius: 8, padding: 12, height: 45,\n }}>\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 {showStripe && (showApplePay || showGooglePay) && skeleton(DEFAULT_BUTTONS_LAYOUT_BUTTON_HEIGHT)}\n {showStripe && (\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 )}\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 PaymentElement,\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 CheckoutSession,\n DeclineEvent,\n GatewayEnvironment,\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 filterStripeMethodsByCurrency,\n filterStripeMethodsByCountry,\n filterStripeMethodsByAmount,\n getStripeMethodDisplayName,\n hasVendoredStripeMethodLogo,\n needsStripeMethodExplicitConfirm,\n resolveStripeMethodBrandVariant,\n partitionStripeMethods,\n stripeExpressMethodToOptionKey,\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';\nimport { DirectPayPalButton } from './direct-paypal-button.js';\n\nimport { FloPayError, resolveTheme } from '@flopay/shared';\n\n/**\n * localStorage key for persisting Stripe-redirect payment state across the\n * round-trip to an external authorization page (PayPal, Cash App Pay, Klarna,\n * iDEAL, …). The legacy `flopay_wallet_resume` key is still read for one\n * minor — payloads written by older SDK builds keep resuming after upgrade.\n */\nconst STRIPE_RESUME_KEY = 'flopay_stripe_resume';\nconst LEGACY_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\n// PayPal SDK's .paypal-buttons wrapper is `display: inline-block` with a\n// default margin. In a block container it leaves baseline-descender space\n// below, which visually doubles the parent's flex `gap`. Force margin: 0 +\n// vertical-align: top to neutralise both.\nconst FLOPAY_KEYFRAMES = `\n.paypal-buttons { margin: 0 !important; vertical-align: top !important; }\n@keyframes flopay-spin { to { transform: rotate(360deg); } }\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\n/**\n * Shared \"primary button\" base style for the two buyer-action buttons in the\n * buttons-layout (the \"Credit / Debit Card\" button + `FloPayAutomaticPaymentButton`).\n *\n * - `'classic'` / no theme: white background, grey border — historic look\n * that lines up with the wallet ECE row's flat tiles.\n * - Any theme bundle (`modern-*`, `bold-*`, `glass-*`): reads its surface\n * directly off the theme's `submitButton` (the \"Confirm Payment\" CTA at\n * the bottom of the card form) — same `backgroundColor`, `color`,\n * `borderRadius`, `boxShadow` — so the drill-in action is visually\n * indistinguishable from the action it leads to. `colorPrimary` is\n * *only* used as a fallback when a bundle's `submitButton` doesn't pin\n * its own `backgroundColor`.\n */\nexport function derivePrimaryTileStyle(opts: {\n themeBundle: import('@flopay/shared').ThemeBundle | null | undefined;\n resolvedPrimaryColor: string;\n resolvedBorderRadius: string;\n submitButtonStyle?: React.CSSProperties;\n}): React.CSSProperties {\n if (!opts.themeBundle) {\n return {\n backgroundColor: 'white',\n color: '#262833',\n border: '1px solid #d1d5db',\n borderRadius: '8px',\n boxShadow: '0 1px 2px rgba(0,0,0,0.04)',\n };\n }\n const submit = opts.submitButtonStyle ?? {};\n return {\n backgroundColor: (submit.backgroundColor as string | undefined) ?? opts.resolvedPrimaryColor,\n color: (submit.color as string | undefined) ?? 'white',\n border: (submit.border as string | undefined) ?? 'none',\n borderRadius: (submit.borderRadius as string | number | undefined) ?? opts.resolvedBorderRadius,\n boxShadow: submit.boxShadow as string | undefined,\n };\n}\n\n// Buttons-panel hide style used in `layout=\"buttons\"` when the card form is in\n// view. PayPal's Stripe ExpressCheckoutElement (and the direct PayPal SDK)\n// renders its button into a cross-origin iframe whose painted content ignores\n// the parent's `visibility: hidden`. Without `height: 0 + overflow: hidden`\n// the PayPal button stays visually painted on the card-details step even\n// though it is logically hidden. Keeping the panel mounted (rather than\n// unmounting) preserves PayPal/wallet Elements state across the transition.\nconst BUTTONS_PANEL_HIDDEN_STYLE: React.CSSProperties = {\n visibility: 'hidden',\n position: 'absolute',\n pointerEvents: 'none',\n width: '100%',\n height: 0,\n overflow: 'hidden',\n};\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<string>,\n): ExpressCheckoutLoadState {\n const available = event.availablePaymentMethods as Record<string, boolean | undefined> | undefined;\n if (!available) return 'unavailable';\n\n return methods.some((method) => available[method]) ? 'ready' : 'unavailable';\n}\n\nfunction ExpressCheckoutReadySwap({\n state,\n placeholderTestId,\n borderRadius = 8,\n children,\n}: {\n state: ExpressCheckoutLoadState;\n placeholderTestId?: string;\n /**\n * Border radius for the pulse-skeleton placeholder. Defaults to `8` for\n * the classic look; consumers pass the theme's `borderRadius` (or the\n * theme bundle's `cardButton.borderRadius`) so the skeleton matches the\n * eventual button's corners — otherwise the placeholder reads as\n * visually unrelated to the wallet tile that replaces it.\n */\n borderRadius?: string | number;\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,\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 the PayPal payment surface above card fields. Defaults to `true`.\n * The renderer is chosen from `session.gateways.paypal`: when that gateway\n * is configured, `DirectPayPalButton` (PayPal JS SDK) takes over and Stripe\n * drops `paypal` from its express row to avoid double-rendering; otherwise\n * PayPal renders inside `ExpressCheckoutElement` (using either a dedicated\n * `gateways.stripe.paypalPublishableKey` sub-account or the main Stripe\n * account when the enabled-methods list includes `paypal`).\n */\n showPayPal?: boolean;\n /**\n * Show the Stripe-rendered checkout (card fields + ExpressCheckoutElement +\n * PaymentElement). Defaults to `true`. When `false`, every Stripe surface\n * is hidden — only `DirectPayPalButton` can render. Setting both\n * `showStripe={false}` and `showPayPal={false}` (with no PayPal gateway\n * configured) throws a bootstrap-time validation error.\n */\n showStripe?: boolean;\n /**\n * Per-session list of Stripe payment method type identifiers (as returned\n * by the billing API on `gateways.stripe.enabledPaymentMethods`). When\n * supplied, drives the contents of the `ExpressCheckoutElement` row and the\n * accordion `PaymentElement` instead of the historic hardcoded\n * Apple/Google/PayPal set. When omitted, the SDK falls back to the legacy\n * `showApplePay`/`showGooglePay`/`showPayPal` toggles.\n */\n enabledPaymentMethods?: string[];\n /**\n * @deprecated The Apple Pay / Google Pay surface is now driven by the\n * `gateways.stripe.enabledPaymentMethods` list returned per-session by the\n * billing API. Pass {@link SplitCardFormProps.enabledPaymentMethods} (or\n * upgrade the backend so `FloPayCheckout` threads it through automatically).\n * Setting this prop emits a one-time deprecation warning and is otherwise\n * ignored when `enabledPaymentMethods` is supplied.\n */\n showApplePay?: boolean;\n /**\n * @deprecated See {@link SplitCardFormProps.showApplePay}.\n */\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 * High-level theme bundle that styles the whole checkout (Stripe-side\n * appearance + FloPay wrapper / submit button / inputs). One of:\n * `'classic'` (historic FloPay look, no bundle applied), `'modern-light'`,\n * `'modern-dark'`, `'bold-light'`, `'bold-dark'`, `'glass-light'`,\n * `'glass-dark'`. Explicit `appearance` / `buttonsStyles` props still\n * override their respective halves when provided.\n */\n theme?: import('@flopay/shared').ThemeId;\n /**\n * @deprecated Use `theme` instead. Legacy buttons-layout preset\n * (`'default' | 'minimal' | 'rounded' | 'dark'`). Still honored for\n * back-compat — the new union accepts the bundle ids too but you should\n * migrate to the `theme` prop.\n */\n buttonsTheme?: import('@flopay/shared').ButtonsLayoutTheme;\n /** Style overrides merged on top of the resolved theme bundle / buttonsTheme preset. */\n buttonsStyles?: import('@flopay/shared').ButtonsLayoutStyles;\n /**\n * Appearance from `FloPayProvider` / `FloPayCheckout`. Threaded through so\n * the React-rendered wrapper, submit button, title, and per-element card\n * field styling can derive colors from `appearance.variables` when no\n * explicit `buttonsStyles` is supplied. Bundle consumers (`THEMES[id]`) get\n * a coherent look without having to forward both halves manually.\n */\n appearance?: import('@flopay/shared').FloPayAppearance;\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 /**\n * @deprecated No longer rendered — the default-layout security footer was\n * removed alongside the theme-bundle refactor. Retained as an optional\n * prop so existing integrations type-check without changes.\n */\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 * Direct PayPal gateway configuration. When provided, PayPal renders via\n * the official PayPal JS SDK (in-app browser compliant) instead of via\n * Stripe's ExpressCheckoutElement. Selection is mutually exclusive:\n * setting this disables the Stripe-rendered PayPal path automatically.\n */\n directPaypal?: {\n clientId: string;\n environment?: GatewayEnvironment;\n };\n /** Whether the active session represents a subscription (drives direct PayPal intent). */\n isSubscription?: boolean;\n /** Backing session — forwarded to direct-PayPal so it can populate accountData. */\n session?: CheckoutSession | null;\n /**\n * Enables on-screen diagnostic panels for the PayPal/wallet gating decision\n * and the `DirectPayPalButton` lifecycle. Intended for debugging in-app\n * browsers where remote console access is impractical. Off by default.\n */\n debug?: 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 placeholderBorderRadius,\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 placeholderBorderRadius?: string | number;\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\n state={loadState}\n placeholderTestId=\"flopay-paypal-placeholder\"\n borderRadius={placeholderBorderRadius}\n >\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 expressMethods,\n onTokenizedBody,\n onErrorChange,\n onButtonClick,\n onDecline,\n runBeforeButtonClick,\n onLoadStateChange,\n placeholderBorderRadius,\n}: {\n sessionId: string;\n email?: string;\n billingApiUrl: string;\n /**\n * Stripe-wire method identifiers to render in the ExpressCheckoutElement\n * (`apple_pay`, `google_pay`, `link`, `amazon_pay`, `klarna`, `paypal`).\n * Already filtered against {@link STRIPE_EXPRESS_METHODS}; `paypal` is\n * dropped upstream when `DirectPayPalButton` owns the PayPal surface.\n */\n expressMethods: string[];\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 placeholderBorderRadius?: string | number;\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. Stripe's\n // `expressPaymentType` covers Apple/Google Pay; the SDK collapses\n // anything else (Link, Amazon Pay, Klarna) onto `google_pay` for the\n // existing analytics enum surface.\n const walletType = (event as unknown as { expressPaymentType?: string }).expressPaymentType;\n let prepared = beforeClickRef.current;\n beforeClickRef.current = null;\n\n const buttonMethod: CheckoutButtonMethod = walletType === 'apple_pay' ? 'apple_pay' : 'google_pay';\n if (!prepared && runBeforeButtonClick) {\n const beforeClick = await runBeforeButtonClick(buttonMethod);\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 = buttonMethod;\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 // ExpressCheckoutElement's `paymentMethods` map uses camelCase keys; every\n // method not present in `expressMethods` is explicitly set to `'never'` so\n // Stripe collapses it instead of falling back to its own defaults. Only\n // `applePay` and `googlePay` accept `'always'`; `link`, `klarna`, `amazonPay`,\n // and `paypal` are typed as `'auto' | 'never'` by Stripe and throw an\n // IntegrationError at mount if `'always'` is passed.\n const expressMethodMap = useMemo(() => {\n const allKeys = ['applePay', 'googlePay', 'paypal', 'link', 'amazonPay', 'klarna'] as const;\n const alwaysCapable = new Set<string>(['applePay', 'googlePay']);\n const enabledKeys = new Set(expressMethods.map(stripeExpressMethodToOptionKey));\n const out: Record<string, 'always' | 'auto' | 'never'> = {};\n for (const key of allKeys) {\n if (!enabledKeys.has(key)) {\n out[key] = 'never';\n } else {\n out[key] = alwaysCapable.has(key) ? 'always' : 'auto';\n }\n }\n return out;\n }, [expressMethods]);\n const availableMethodKeys = useMemo(\n () => expressMethods.map(stripeExpressMethodToOptionKey),\n [expressMethods],\n );\n\n return (\n <>\n <ExpressCheckoutReadySwap\n state={loadState}\n placeholderTestId=\"flopay-wallet-placeholder\"\n borderRadius={placeholderBorderRadius}\n >\n <ExpressCheckoutElement\n onReady={(event) => {\n setLoadState(resolveExpressCheckoutLoadState(event, availableMethodKeys));\n }}\n onLoadError={(_event) => {\n setLoadState('load_error');\n }}\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: expressMethodMap,\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// ─── Stripe PaymentElement (non-express APMs: Cash App Pay / Klarna / Affirm / iDEAL / SEPA …) ─\n\n/**\n * PaymentElement region — rendered as one button per enabled APM, styled to\n * match the wallet ECE row above it. Each button's behaviour is determined\n * by {@link needsStripeMethodExplicitConfirm} in the shared method matrix:\n *\n * - **Auto-confirm methods** (Cash App, Affirm, …): clicking the button\n * swaps it for a loading spinner, and the SDK goes straight to\n * `stripe.confirmPayment({ payment_method_data: { type, billing_details } })`\n * with no PaymentElement involvement. Stripe takes over with its popup /\n * redirect; on cancel the spinner reverts back to the button.\n *\n * - **Input-form methods** (SEPA Debit, EPS, iDEAL, …): clicking the\n * button collapses the row to just that method and mounts an inline\n * PaymentElement scoped to `paymentMethodTypes: [method]` in a separate\n * Elements group. The inline form shows the method's required input\n * (IBAN, bank picker, …) plus a \"Pay with X\" button. A back link\n * restores the full button row.\n *\n * Each expanded form mounts its own {@link StripeElements} group rather\n * than sharing a parent group across methods, because `paymentMethodTypes`\n * cannot be mutated on an existing Elements group (`elements.update()`\n * explicitly rejects it). The trade-off is a ~500ms `/v1/elements/sessions`\n * call on first expansion of each method — acceptable cost for the focused\n * per-method UX.\n */\n\n/**\n * Reusable method-tile button — same 44px contract as the wallet ECE row.\n * Lifted out so both the unselected list and the expanded-method header\n * reuse the same shape and theming. The pressed state (`submitting`)\n * replaces the label with a spinner so the buyer sees feedback during the\n * `POST /payments/intents` → `stripe.confirmPayment` round-trip on\n * auto-confirm methods.\n */\nfunction StripeMethodButton({\n method,\n themeId,\n submitting = false,\n disabled = false,\n highlighted = false,\n hasNextStep = false,\n onClick,\n backgroundColor,\n borderColor,\n textColor,\n borderRadius,\n fontFamily,\n}: {\n method: string;\n /**\n * Active FloPay theme id — drives which `STRIPE_METHOD_MATRIX[method]\n * .theme.{light,dark}` variant the button picks up its brand colors\n * (and eventually logo) from. `null`/`undefined`/`classic` falls back\n * to the matrix's `light` variant; any `*-dark` theme picks the `dark`\n * variant.\n */\n themeId?: import('@flopay/shared').ThemeId | null;\n submitting?: boolean;\n disabled?: boolean;\n highlighted?: boolean;\n /**\n * Render a right-chevron at the trailing edge of the button label,\n * signalling that clicking the tile drills into a second page (the\n * inline form for input-requiring APMs like SEPA Debit / EPS / iDEAL).\n * Auto-confirm methods (Cash App, Affirm) leave this off — their click\n * goes straight to Stripe's authorization UI with no intermediate page.\n */\n hasNextStep?: boolean;\n onClick: () => void;\n backgroundColor?: string;\n borderColor?: string;\n textColor?: string;\n borderRadius?: string | number;\n fontFamily?: string;\n}) {\n // Resolution order:\n // 1. Brand variant pulled from `STRIPE_METHOD_MATRIX[method].theme`\n // keyed by mode — gives Cash App green, Klarna pink, etc., out of\n // the box. Brand wins over the surrounding theme bundle's neutral\n // `cardButton` styling because the *method's* identity is more\n // specific than the *layout's* tile design — and the parent always\n // passes the theme bundle's `cardButton` colors through the prop\n // channel, so otherwise no branded button would ever surface.\n // 2. Inline `buttonAppearance` prop — bundle-level overrides for\n // methods without a brand variant in the matrix.\n // 3. Defaults — white + grey border, matching the legacy tile.\n const brand = resolveStripeMethodBrandVariant(method, themeId);\n const resolvedBackground = brand?.backgroundColor ?? backgroundColor ?? '#ffffff';\n const resolvedBorder = brand?.borderColor ?? borderColor ?? '#d1d5db';\n const resolvedTextColor = brand?.textColor ?? textColor ?? '#262833';\n return (\n <button\n type=\"button\"\n data-testid={`flopay-stripe-method-button-${method}`}\n data-method={method}\n onClick={() => { if (!submitting && !disabled) onClick(); }}\n disabled={submitting || disabled}\n aria-busy={submitting || undefined}\n style={{\n position: 'relative',\n width: '100%',\n boxSizing: 'border-box',\n height: DEFAULT_BUTTONS_LAYOUT_BUTTON_HEIGHT,\n padding: '0 1rem',\n backgroundColor: resolvedBackground,\n color: resolvedTextColor,\n border: `1px solid ${resolvedBorder}`,\n borderRadius: borderRadius ?? 8,\n fontSize: '0.95rem',\n fontWeight: 600,\n fontFamily,\n cursor: submitting || disabled ? 'not-allowed' : 'pointer',\n opacity: disabled && !submitting ? 0.55 : 1,\n // Submitting state pulses the whole button background, mirroring\n // the wallet ECE's `flopay-pulse` skeleton. This keeps the loading\n // affordance consistent between embedded wallets (Apple Pay,\n // Google Pay) and these custom APM tile buttons — same animation\n // curve, same duration, only the surface colour changes (grey for\n // the wallet skeleton vs. brand colour for an in-flight tile).\n animation: submitting ? 'flopay-pulse 1.5s ease-in-out infinite' : undefined,\n display: 'flex',\n alignItems: 'center',\n // Always center the logo+name group. The drill-in chevron (input\n // methods) is absolutely positioned at the right edge below so it\n // doesn't pull the label off-center.\n justifyContent: 'center',\n gap: 8,\n transition: 'transform 0.1s, opacity 140ms ease-out, border-color 140ms ease-out',\n boxShadow: highlighted ? '0 0 0 2px rgba(74, 73, 255, 0.15)' : undefined,\n }}\n >\n {submitting ? (\n // Pulse-skeleton parity with the wallet ECE: no spinner, just the\n // status text on top of the pulsing background. Keeps the loading\n // affordance shape-equivalent across both kinds of tile.\n <span style={{ margin: '0 auto' }}>\n {`Connecting to ${getStripeMethodDisplayName(method)}…`}\n </span>\n ) : (\n <>\n {/* Group: logo + name sit adjacent (8px gap) so the brand mark\n reads as part of the same label, not as a separately\n left-justified icon. The group is always centered (the button's\n `justifyContent: 'center'`); the drill-in chevron is absolutely\n positioned at the right edge so it never pulls the label\n off-center. */}\n <span\n style={{\n display: 'inline-flex',\n alignItems: 'center',\n // Real vendored logos are self-contained brand cards, so they\n // get an 8px gap from the label. The generated placeholder\n // monogram reads as part of the label (the tile's first letter),\n // so it sits flush (0px) against the name.\n gap: hasVendoredStripeMethodLogo(method) ? 8 : 0,\n }}\n >\n {brand?.logoSvg && (\n <span\n aria-hidden=\"true\"\n style={{\n // 3:2 box matching the vendored datatrans logos' 120×80\n // viewBox. Each logo ships with its own white rounded-rect\n // background baked in, so the mark stays legible on any\n // brand-coloured tile without an extra chip wrapper here.\n width: 30,\n height: 20,\n flexShrink: 0,\n display: 'inline-flex',\n borderRadius: 3,\n overflow: 'hidden',\n }}\n // Logo markup originates from the matrix (`StripeMethodEntry\n // .theme.{light,dark}.logoSvg`); we trust it here because the\n // matrix is owned by the SDK, not user input.\n dangerouslySetInnerHTML={{ __html: brand.logoSvg }}\n />\n )}\n <span>{getStripeMethodDisplayName(method)}</span>\n </span>\n {hasNextStep && (\n <svg\n width=\"14\"\n height=\"14\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke={resolvedTextColor}\n strokeWidth=\"2.5\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n style={{\n position: 'absolute',\n right: '1rem',\n top: '50%',\n transform: 'translateY(-50%)',\n flexShrink: 0,\n opacity: 0.7,\n }}\n aria-hidden=\"true\"\n >\n <path d=\"M9 18l6-6-6-6\" />\n </svg>\n )}\n </>\n )}\n </button>\n );\n}\n\n/**\n * Inline form rendered beneath the selected method button for APMs that\n * need data collection. Mounts a single-method PaymentElement (Stripe's\n * accordion with one item, default-expanded) plus the \"Pay with X\" submit\n * button. Lives inside its own `<StripeElements>` group keyed by method, so\n * switching between methods unmounts the previous group cleanly.\n */\nfunction StripeMethodInlineForm({\n method,\n sessionId,\n email,\n billingName,\n billingApiUrl,\n onTokenizedBody,\n onErrorChange,\n onDecline,\n onCancel,\n runBeforeButtonClick,\n onButtonClick,\n isProcessing,\n submitButtonColor,\n submitButtonBorderRadius,\n submitButtonStyle,\n}: {\n method: string;\n sessionId: string;\n email?: string;\n billingName?: string;\n billingApiUrl: string;\n onTokenizedBody: InternalTokenizedBodyHandler;\n onErrorChange?: (error: string | null) => void;\n onDecline?: (decline: DeclineEvent) => void;\n onCancel: () => void;\n runBeforeButtonClick?: RunBeforeButtonClick;\n onButtonClick?: (method: CheckoutButtonMethod) => void;\n isProcessing?: boolean;\n submitButtonColor: string;\n submitButtonBorderRadius: string | number;\n submitButtonStyle?: React.CSSProperties;\n}) {\n const stripe = useStripeRaw();\n const elements = useStripeElements();\n const [submitting, setSubmitting] = useState(false);\n const submittingRef = useRef(false);\n const [isMethodComplete, setIsMethodComplete] = useState(false);\n const [loadState, setLoadState] = useState<'loading' | 'ready' | 'load_error'>('loading');\n const baseUrl = billingApiUrl.replace(/\\/+$/, '');\n\n const handlePay = useCallback(async () => {\n if (!stripe || !elements || isProcessing || submittingRef.current || !isMethodComplete) return;\n submittingRef.current = true;\n setSubmitting(true);\n\n const beforeClick = runBeforeButtonClick\n ? await runBeforeButtonClick('card')\n : { proceed: true } as BeforeButtonClickResult;\n if (!beforeClick.proceed) {\n submittingRef.current = false;\n setSubmitting(false);\n return;\n }\n onButtonClick?.('card');\n\n const effectiveSessionId = beforeClick.sessionId ?? sessionId;\n const effectiveEmail = beforeClick.accountPatch?.email ?? email;\n\n try {\n onErrorChange?.(null);\n\n const submitRes = await elements.submit();\n if (submitRes.error) {\n onErrorChange?.(submitRes.error.message ?? 'Payment failed.');\n return;\n }\n\n const pmRes = await stripe.createPaymentMethod({ elements });\n if (pmRes.error || !pmRes.paymentMethod) {\n onErrorChange?.(pmRes.error?.message ?? 'Failed to create payment method.');\n return;\n }\n const paymentMethod = pmRes.paymentMethod;\n\n if (!effectiveSessionId || !effectiveEmail) {\n throw new Error('Missing sessionId or email for payment.');\n }\n\n // Send the resolved wire type so the backend scopes the PI to just\n // this method (`payment_method_types: [<type>]`) — avoids the\n // `apple_pay invalid` PI-creation reject path on accounts without\n // domain verification.\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.type || method,\n isPaypal: false,\n }),\n });\n if (!intentResponse.ok) {\n const intentError = await buildFloPayApiErrorFromResponse(intentResponse, 'Failed to create payment intent');\n onErrorChange?.(intentError.message);\n onDecline?.(buildDeclineEvent('card', intentError));\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 // Persist the resume payload before confirmPayment — same contract as\n // the legacy region, picked up by the resume handler on redirect return.\n if (typeof window !== 'undefined') {\n try {\n localStorage.setItem(STRIPE_RESUME_KEY, JSON.stringify({\n sessionId: effectiveSessionId,\n paymentMethodId: paymentMethod.id,\n paymentMethodType: paymentMethod.type ?? method,\n gateway: 'stripe',\n }));\n } catch { /* localStorage unavailable */ }\n }\n\n const { error: confirmError, paymentIntent } = await stripe.confirmPayment({\n clientSecret: intentClientSecret,\n confirmParams: {\n return_url: window.location.href,\n payment_method: paymentMethod.id,\n } as { return_url: string; payment_method?: string },\n redirect: 'if_required',\n });\n\n if (confirmError) {\n if (typeof window !== 'undefined') {\n try { localStorage.removeItem(STRIPE_RESUME_KEY); } catch { /* ignore */ }\n }\n const message = confirmError.message ?? 'Payment failed.';\n onErrorChange?.(message);\n onDecline?.(buildDeclineEvent('card', message, { code: confirmError.code }));\n return;\n }\n\n const SUCCESSFUL_PI_STATUSES = new Set(['succeeded', 'requires_capture', 'processing']);\n const piStatus = paymentIntent?.status;\n if (!piStatus || !SUCCESSFUL_PI_STATUSES.has(piStatus)) {\n if (typeof window !== 'undefined') {\n try { localStorage.removeItem(STRIPE_RESUME_KEY); } catch { /* ignore */ }\n }\n const message = piStatus === 'canceled'\n ? 'Payment was canceled.'\n : 'Payment was not completed. Please try again.';\n onErrorChange?.(message);\n onDecline?.(buildDeclineEvent('card', message, { code: piStatus ?? 'missing_payment_intent' }));\n return;\n }\n\n if (typeof window !== 'undefined') {\n try { localStorage.removeItem(STRIPE_RESUME_KEY); } catch { /* ignore */ }\n }\n const confirmedPmId = typeof paymentIntent?.payment_method === 'string'\n ? paymentIntent.payment_method\n : paymentIntent?.payment_method?.id;\n\n onTokenizedBody({\n id: confirmedPmId ?? paymentMethod.id,\n type: 'card',\n threeDSecureActionResultTokenId: paymentIntent?.id,\n gateway: 'stripe',\n paymentMethodType: paymentMethod.type ?? method,\n }, {\n accountPatch: beforeClick.accountPatch,\n sessionId: effectiveSessionId,\n });\n } catch (err) {\n onErrorChange?.(err instanceof Error ? err.message : 'Payment failed. Please try again.');\n } finally {\n submittingRef.current = false;\n setSubmitting(false);\n }\n }, [stripe, elements, isProcessing, isMethodComplete, runBeforeButtonClick, onButtonClick,\n sessionId, email, baseUrl, method, onTokenizedBody, onErrorChange, onDecline]);\n\n // The back/cancel control is rendered by the parent (\"Go back\" button at\n // the top of the 2nd-page panel that mirrors the card form's 2nd page),\n // so `onCancel` is intentionally unused here — kept on the prop signature\n // so other call sites that still embed the form inline can wire their\n // own back link if needed.\n void onCancel;\n\n return (\n <div data-testid={`flopay-stripe-method-form-${method}`} style={{ display: 'flex', flexDirection: 'column' }}>\n <PaymentElement\n onReady={() => setLoadState('ready')}\n onLoadError={() => setLoadState('load_error')}\n onChange={(event) => {\n const evRecord = event as unknown as { complete?: boolean };\n setIsMethodComplete(!!evRecord.complete);\n }}\n // Single-method group: only this method's accordion item renders,\n // default-expanded so the inline form (IBAN / bank picker) is\n // immediately visible.\n options={{\n layout: { type: 'accordion', defaultCollapsed: false, radios: 'never' },\n defaultValues: {\n billingDetails: {\n name: billingName && billingName.trim().length >= 3\n ? billingName.trim()\n : 'FloPay Customer',\n ...(email ? { email } : {}),\n },\n },\n } as unknown as Parameters<typeof PaymentElement>[0]['options']}\n />\n\n <button\n type=\"button\"\n data-testid={`flopay-stripe-method-pay-${method}`}\n onClick={() => { void handlePay(); }}\n disabled={!isMethodComplete || submitting || isProcessing || loadState !== 'ready'}\n style={{\n width: '100%',\n marginTop: '0.75rem',\n padding: '0.875rem',\n backgroundColor: submitButtonColor,\n color: 'white',\n border: 'none',\n borderRadius: submitButtonBorderRadius,\n fontSize: '1rem',\n fontWeight: 600,\n cursor: (!isMethodComplete || submitting || isProcessing || loadState !== 'ready') ? 'not-allowed' : 'pointer',\n opacity: (!isMethodComplete || submitting || isProcessing || loadState !== 'ready') ? 0.5 : 1,\n transition: 'opacity 120ms ease-out',\n ...(submitButtonStyle ?? {}),\n }}\n >\n {submitting ? 'Processing…' : `Pay with ${getStripeMethodDisplayName(method)}`}\n </button>\n </div>\n );\n}\nfunction StripePaymentElementInner({\n sessionId,\n email,\n billingName,\n billingApiUrl,\n paymentElementMethods,\n stripeInstance,\n paymentElementBaseOptions,\n onTokenizedBody,\n onErrorChange,\n onButtonClick,\n onDecline,\n runBeforeButtonClick,\n onLoadStateChange,\n isProcessing = false,\n submitButtonColor = '#4A49FF',\n submitButtonBorderRadius = 8,\n submitButtonStyle,\n buttonAppearance,\n themeId,\n onExpandApm,\n expandedApmMethod,\n}: {\n sessionId: string;\n email?: string;\n /**\n * Buyer's full name, prefilled into the inline PaymentElement's billing\n * details so `elements.submit()` for methods that mandate a name (SEPA,\n * Bancontact, Klarna, …) doesn't reject with `invalid_name_<method>`.\n * Falls back to `'FloPay Customer'` only if the session has no buyer\n * name at all.\n */\n billingName?: string;\n billingApiUrl: string;\n paymentElementMethods: string[];\n /**\n * Raw Stripe instance from the parent `FloPayProvider`. The component\n * uses it directly for `confirmPayment` on auto-confirm methods (no\n * Elements group needed) and as the `stripe` prop on each expanded\n * method's inline `<StripeElements>` group.\n */\n stripeInstance: Stripe | null;\n /**\n * Shared Elements options (mode/amount/currency/appearance) without\n * `paymentMethodTypes`. Each expanded method spreads this and adds its\n * own `paymentMethodTypes: [method]` to scope its inline form.\n */\n paymentElementBaseOptions: Record<string, unknown>;\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: 'loading' | 'ready' | 'load_error') => void;\n isProcessing?: boolean;\n submitButtonColor?: string;\n submitButtonBorderRadius?: string | number;\n submitButtonStyle?: React.CSSProperties;\n /**\n * Theme overrides applied to each method tile button. Defaults to the\n * historic white-with-grey-border styling that matches the legacy\n * \"Credit / Debit Card\" button in the buttons-layout flow.\n */\n buttonAppearance?: {\n backgroundColor?: string;\n borderColor?: string;\n textColor?: string;\n borderRadius?: string | number;\n fontFamily?: string;\n };\n /**\n * Active FloPay theme id — passed through to each tile so it can look up\n * its per-mode brand styling from `STRIPE_METHOD_MATRIX[method].theme`.\n * `null`/`undefined`/`classic` resolves to the matrix's `light` variant;\n * any `*-dark` theme resolves to the `dark` variant.\n */\n themeId?: import('@flopay/shared').ThemeId | null;\n /**\n * Called when the buyer clicks a tile for a method that requires inline\n * data collection (SEPA Debit IBAN, EPS bank picker, …). The parent\n * decides how to present the expanded form — typically by transitioning\n * to a second page (mirroring the card-form 2nd page in buttons layout).\n * Auto-confirm methods (Cash App, Affirm) don't call this; they handle\n * the click locally with a button spinner + direct `confirmPayment`.\n */\n onExpandApm?: (method: string) => void;\n /**\n * The method whose 2nd-page form is currently visible (parent-managed).\n * Used to disable the *other* tile buttons during the drill-in so the\n * buyer either submits or backs out before switching methods.\n */\n expandedApmMethod?: string | null;\n}) {\n const baseUrl = billingApiUrl.replace(/\\/+$/, '');\n // Which method is showing its expanded inline form (input methods only).\n const [expandedMethod, setExpandedMethod] = useState<string | null>(null);\n // Which method is mid-`confirmPayment` (auto-confirm methods only). The\n // tile button replaces its label with a spinner while this is set.\n const [submittingMethod, setSubmittingMethod] = useState<string | null>(null);\n const submittingRef = useRef(false);\n\n // The legacy `StripePaymentElementInner` mounted one big PaymentElement,\n // so the `load_state` signal came from the element's `ready`/`loaderror`\n // events. The custom-button version has no upfront PaymentElement —\n // signal ready as soon as we have a Stripe instance and at least one\n // method to render, so the parent's gate (`shouldDisplayPaymentElementRow`)\n // can stop showing the loading skeleton.\n useEffect(() => {\n if (paymentElementMethods.length > 0 && stripeInstance) {\n onLoadStateChange?.('ready');\n } else if (!stripeInstance) {\n onLoadStateChange?.('loading');\n }\n }, [paymentElementMethods.length, stripeInstance, onLoadStateChange]);\n\n // ─── Auto-confirm flow (Cash App / Affirm / …) ─────────────────────────\n // No PaymentElement: the method has no inline data to collect, so we go\n // POST /intents → stripe.confirmPayment with `payment_method_data.type`\n // and let Stripe handle tokenization + popup/redirect inside its own UI.\n // Saves a `/v1/elements/sessions` round-trip per click compared to the\n // PaymentElement-driven path used for input methods.\n const handleAutoConfirm = useCallback(async (method: string) => {\n if (!stripeInstance) return;\n if (submittingRef.current || isProcessing) return;\n submittingRef.current = true;\n setSubmittingMethod(method);\n\n const beforeClick = runBeforeButtonClick\n ? await runBeforeButtonClick('card')\n : { proceed: true } as BeforeButtonClickResult;\n if (!beforeClick.proceed) {\n submittingRef.current = false;\n setSubmittingMethod(null);\n return;\n }\n onButtonClick?.('card');\n\n const effectiveSessionId = beforeClick.sessionId ?? sessionId;\n const effectiveEmail = beforeClick.accountPatch?.email ?? email;\n\n try {\n onErrorChange?.(null);\n\n if (!effectiveSessionId || !effectiveEmail) {\n throw new Error('Missing sessionId or email for payment.');\n }\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 // Wire type, not pm_xxx — backend scopes `payment_method_types`\n // to this single method so unrelated account-wide methods\n // (apple_pay without domain verification, …) don't poison PI\n // creation.\n paymentMethodType: method,\n isPaypal: false,\n }),\n });\n if (!intentResponse.ok) {\n const intentError = await buildFloPayApiErrorFromResponse(intentResponse, 'Failed to create payment intent');\n onErrorChange?.(intentError.message);\n onDecline?.(buildDeclineEvent('card', intentError));\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 // Persist the resume payload before confirmPayment in case Stripe\n // redirects (Cash App Pay does on some platforms; Affirm always\n // does). The parent's resume handler picks this up on return.\n if (typeof window !== 'undefined') {\n try {\n localStorage.setItem(STRIPE_RESUME_KEY, JSON.stringify({\n sessionId: effectiveSessionId,\n paymentMethodType: method,\n gateway: 'stripe',\n }));\n } catch { /* localStorage unavailable in private mode */ }\n }\n\n const { error: confirmError, paymentIntent } = await stripeInstance.confirmPayment({\n clientSecret: intentClientSecret,\n confirmParams: {\n return_url: window.location.href,\n // Inline the method data — no Elements / PaymentElement\n // required. Stripe creates the PaymentMethod during confirm\n // and proceeds to its popup/redirect UI.\n payment_method_data: {\n type: method,\n billing_details: {\n name: billingName && billingName.trim().length >= 3 ? billingName.trim() : 'FloPay Customer',\n ...(effectiveEmail ? { email: effectiveEmail } : {}),\n },\n },\n } as never,\n redirect: 'if_required',\n });\n\n if (confirmError) {\n if (typeof window !== 'undefined') {\n try { localStorage.removeItem(STRIPE_RESUME_KEY); } catch { /* ignore */ }\n }\n const message = confirmError.message ?? 'Payment failed.';\n onErrorChange?.(message);\n onDecline?.(buildDeclineEvent('card', message, { code: confirmError.code }));\n return;\n }\n\n // `redirect: 'if_required'` returns *without* `confirmError` even\n // when the buyer closed an inline confirmation UI without\n // approving — `paymentIntent.status` is the authoritative signal.\n const SUCCESSFUL_PI_STATUSES = new Set(['succeeded', 'requires_capture', 'processing']);\n const piStatus = paymentIntent?.status;\n if (!piStatus || !SUCCESSFUL_PI_STATUSES.has(piStatus)) {\n if (typeof window !== 'undefined') {\n try { localStorage.removeItem(STRIPE_RESUME_KEY); } catch { /* ignore */ }\n }\n const message = piStatus === 'canceled'\n ? 'Payment was canceled.'\n : 'Payment was not completed. Please try again.';\n onErrorChange?.(message);\n onDecline?.(buildDeclineEvent('card', message, { code: piStatus ?? 'missing_payment_intent' }));\n return;\n }\n\n if (typeof window !== 'undefined') {\n try { localStorage.removeItem(STRIPE_RESUME_KEY); } catch { /* ignore */ }\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 gateway: 'stripe',\n paymentMethodType: method,\n }, {\n accountPatch: beforeClick.accountPatch,\n sessionId: effectiveSessionId,\n });\n } catch (err) {\n onErrorChange?.(err instanceof Error ? err.message : 'Payment failed. Please try again.');\n } finally {\n submittingRef.current = false;\n setSubmittingMethod(null);\n }\n }, [stripeInstance, isProcessing, runBeforeButtonClick, onButtonClick, sessionId, email,\n baseUrl, billingName, onTokenizedBody, onErrorChange, onDecline]);\n\n // Fallback expansion state for callers that *don't* provide `onExpandApm`\n // (e.g. the default-layout site, which has no concept of a 2nd page).\n // When the parent owns the navigation (buttons layout), we never touch\n // this and read from `expandedApmMethod` instead.\n const [localExpandedMethod, setLocalExpandedMethod] = useState<string | null>(null);\n const activeExpandedMethod = onExpandApm ? (expandedApmMethod ?? null) : localExpandedMethod;\n\n const handleMethodClick = useCallback((method: string) => {\n if (submittingRef.current || isProcessing) return;\n // While one method is expanded, the other tile buttons are disabled —\n // the buyer has to submit or back out before switching.\n if (activeExpandedMethod && activeExpandedMethod !== method) return;\n\n if (needsStripeMethodExplicitConfirm(method)) {\n if (onExpandApm) {\n // Parent (buttons layout) drives the `viewState` machine and\n // mounts the 2nd-page form there.\n onExpandApm(method);\n } else {\n // Default-layout fallback — expand the form inline beneath the\n // tile button. Same Elements-group-per-method scoping, just\n // without the page transition.\n setLocalExpandedMethod(method);\n }\n } else {\n void handleAutoConfirm(method);\n }\n }, [activeExpandedMethod, isProcessing, handleAutoConfirm, onExpandApm]);\n\n // Per-method Elements options for the local (default-layout) inline form.\n // Mirrors the buttons-layout's `apmInlineOptions` derivation in the\n // parent component.\n const localInlineElementsOptions = useMemo(() => {\n if (!localExpandedMethod) return null;\n return {\n ...paymentElementBaseOptions,\n paymentMethodTypes: [localExpandedMethod],\n } as Parameters<typeof StripeElements>[0]['options'];\n }, [localExpandedMethod, paymentElementBaseOptions]);\n\n return (\n <div\n data-testid=\"flopay-stripe-payment-element-region\"\n style={{ display: 'flex', flexDirection: 'column', gap: '0.5rem' }}\n >\n {paymentElementMethods.map((method) => {\n const isExpanded = expandedApmMethod === method;\n const isSubmittingThis = submittingMethod === method;\n const otherInProgress =\n (submittingMethod !== null && submittingMethod !== method) ||\n (expandedApmMethod !== null && expandedApmMethod !== undefined && expandedApmMethod !== method);\n\n return (\n <React.Fragment key={method}>\n <StripeMethodButton\n method={method}\n themeId={themeId}\n submitting={isSubmittingThis}\n disabled={otherInProgress}\n highlighted={isExpanded}\n // Tile buttons for input methods drill into a 2nd page; the\n // trailing chevron echoes the \"Credit / Debit Card\" button so\n // the affordance reads the same across both kinds of tiles.\n hasNextStep={needsStripeMethodExplicitConfirm(method)}\n onClick={() => handleMethodClick(method)}\n backgroundColor={buttonAppearance?.backgroundColor}\n borderColor={buttonAppearance?.borderColor}\n textColor={buttonAppearance?.textColor}\n borderRadius={buttonAppearance?.borderRadius}\n fontFamily={buttonAppearance?.fontFamily}\n />\n {/* Default-layout fallback: when the parent hasn't wired a 2nd\n page (`onExpandApm`), expand the form inline beneath the\n tile button. Buttons layout never hits this branch — it\n renders the form on its own gridArea-1/1 panel instead. */}\n {!onExpandApm && localExpandedMethod === method && localInlineElementsOptions && stripeInstance && (\n <StripeElements\n key={method}\n stripe={stripeInstance}\n options={localInlineElementsOptions}\n >\n <StripeMethodInlineForm\n method={method}\n sessionId={sessionId}\n email={email}\n billingName={billingName}\n billingApiUrl={billingApiUrl}\n onTokenizedBody={onTokenizedBody}\n onErrorChange={onErrorChange}\n onDecline={onDecline}\n onCancel={() => setLocalExpandedMethod(null)}\n runBeforeButtonClick={runBeforeButtonClick}\n onButtonClick={onButtonClick}\n isProcessing={isProcessing}\n submitButtonColor={submitButtonColor}\n submitButtonBorderRadius={submitButtonBorderRadius}\n submitButtonStyle={submitButtonStyle}\n />\n </StripeElements>\n )}\n </React.Fragment>\n );\n })}\n </div>\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 showStripe = true,\n enabledPaymentMethods,\n showApplePay = true,\n showGooglePay = true,\n layout = 'default',\n theme,\n buttonsTheme,\n buttonsStyles: buttonsStylesOverride,\n appearance: appearanceOverride,\n cardButtonContent,\n cardBackButtonContent,\n cardTitleContent,\n showSecurityFooter: _showSecurityFooter,\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 directPaypal,\n isSubscription = false,\n session,\n debug = 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 ↔ APM transition state machine. The `apm-*` branches\n // mirror the `card` branches one-for-one so the inline-form APM 2nd\n // page (SEPA / EPS / iDEAL / …) animates in and out the same way as the\n // card form's 2nd page, with the same back-button + title chrome.\n type ViewState =\n | 'buttons'\n | 'expanding'\n | 'card'\n | 'collapsing'\n | 'apm-expanding'\n | 'apm-form'\n | 'apm-collapsing';\n const [viewState, setViewState] = useState<ViewState>(initialCardOpen ? 'card' : 'buttons');\n const [expandedApmMethod, setExpandedApmMethod] = useState<string | null>(null);\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 const expandToApm = useCallback((method: string) => {\n setExpandedApmMethod(method);\n setViewState('apm-expanding');\n setTimeout(() => setViewState('apm-form'), TRANSITION_MS);\n }, []);\n\n const collapseFromApm = useCallback(() => {\n setViewState('apm-collapsing');\n setTimeout(() => {\n setViewState('buttons');\n setExpandedApmMethod(null);\n }, 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 // `paypal_direct_required` retry surface. Set when /process returns the\n // discriminator with a fresh PayPal Order/Subscription id — re-binds the\n // direct PayPal button to that id so the buyer can confirm with one more\n // click. Cleared on success or when the buyer dismisses. `attempts` caps\n // the loop at 2 retries so a backend stuck throwing the same exception\n // can't trap the buyer forever.\n const [paypalDirectRetry, setPaypalDirectRetry] = useState<{\n orderId: string;\n attempts: number;\n } | null>(null);\n // Ref-mirror so the processPaymentInternal callback can read current\n // attempt count without recreating on every retry-state change (which\n // would invalidate downstream effects depending on the callback).\n const paypalDirectRetryRef = useRef(paypalDirectRetry);\n useEffect(() => { paypalDirectRetryRef.current = paypalDirectRetry; }, [paypalDirectRetry]);\n\n const resolvedBillingApiUrl = billingApiUrl || contextBillingUrl;\n const displayError = externalError ?? error;\n\n // Resolution order for the wrapper / button styles:\n // 1. `theme` bundle (high-level — pulls a coherent ButtonsLayoutStyles from THEMES)\n // 2. Legacy `buttonsTheme` preset (for back-compat — only applied when `theme` is absent)\n // 3. Explicit `buttonsStyles` override (per-field merge on top of either base)\n // Resolution order for the Stripe-side `appearance`:\n // 1. Explicit `appearance` prop (wins outright)\n // 2. `theme` bundle's appearance (when `appearance` is not supplied)\n const themeBundle = useMemo(() => resolveTheme(theme), [theme]);\n const bStyles = useMemo<ButtonsLayoutStyles>(() => {\n const base = themeBundle?.buttonsLayout ?? 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 }, [themeBundle, buttonsTheme, buttonsStylesOverride]);\n const appearance = appearanceOverride ?? themeBundle?.appearance;\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 Stripe-rendered PayPal Elements provider.\n // When direct PayPal is configured (`directPaypal`) or no PayPal FloPay\n // instance is available, the Stripe-rendered PayPal path is suppressed.\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 // `FloPayAppearance` is a superset of Stripe's `Appearance` type (it adds\n // `variables.fontSizeBase` etc.) — the Stripe public typings reject the\n // wider shape, but the runtime accepts every extra field. Cast through\n // `Record<string, unknown>` so the spread below stays type-safe at the\n // option-construction site without `any`.\n const stripeAppearanceProp = appearance\n ? { appearance: appearance as unknown as Record<string, unknown> }\n : null;\n\n // PaymentElement-specific appearance: target Stripe's `.AccordionItem` and\n // `.AccordionItemContents` so each method card visually matches the 44px\n // wallet ECE buttons above it. Stripe accepts `padding` / `borderRadius` /\n // border styling in `rules`; `height` is not a supported property, so we\n // pin via padding (10px top/bottom × ~24px line-height ≈ 44px total).\n //\n // Stripe's default `spacedAccordionItems` rendering paints a subtle drop\n // shadow under each method card. The wallet ECE row above this region uses\n // flat buttons with no shadow, so we explicitly null the shadow here for\n // visual parity — without this, Cash App Pay sat noticeably \"above\" the\n // wallet buttons stacked just above it. Consumer overrides still win via\n // the `baseRules` spread.\n const paymentElementAppearance = useMemo(() => {\n const base = (appearance ?? {}) as Record<string, unknown>;\n const baseRules = (base.rules as Record<string, Record<string, string>> | undefined) ?? {};\n return {\n ...base,\n rules: {\n ...baseRules,\n '.AccordionItem': {\n padding: '10px 14px',\n boxShadow: 'none',\n ...(baseRules['.AccordionItem'] ?? {}),\n },\n '.AccordionItemContents': {\n padding: '6px 14px 12px',\n boxShadow: 'none',\n ...(baseRules['.AccordionItemContents'] ?? {}),\n },\n },\n };\n }, [appearance]);\n\n // Wallet (Apple/Google Pay) Elements options — uses paymentMethodCreation: 'manual'\n // to match the main card Elements, allowing explicit createPaymentMethod() calls.\n // `appearance` is forwarded so the ExpressCheckoutElement iframe inherits the\n // shared theme variables (e.g. `borderRadius`) instead of falling back to\n // Stripe's defaults.\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 ...stripeAppearanceProp,\n }), [amountInCents, currency, stripeAppearanceProp]);\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 ...stripeAppearanceProp,\n }), [amountInCents, currency, stripeAppearanceProp]);\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 // ── Method partitioning ──\n //\n // Backend now ships `enabledPaymentMethods` per-session (e.g. ['apple_pay',\n // 'cashapp', 'google_pay', 'link', 'sepa_debit']). We partition it into:\n // - `expressMethods`: the subset supported by `ExpressCheckoutElement`\n // (filtered against STRIPE_EXPRESS_METHODS).\n // - `paymentElementMethods`: everything else (Cash App Pay, Affirm, iDEAL,\n // SEPA debit, …) — rendered in the accordion PaymentElement region.\n //\n // PayPal is dropped from the express set when `DirectPayPalButton` owns the\n // PayPal surface (controlled by `gateways.paypal` upstream → `directPaypal`\n // prop here), so the SDK doesn't double-render.\n //\n // Legacy fallback: when the billing API hasn't been upgraded to ship\n // `enabledPaymentMethods`, fall back to the historic\n // `showApplePay`/`showGooglePay` toggle behaviour so existing integrations\n // keep working unchanged.\n const directPaypalConfigured = !!directPaypal?.clientId;\n // `hasEnabledMethodsPayload` distinguishes \"backend shipped the field\" from\n // \"backend shipped the field with at least one entry\". A provided-but-empty\n // array means the new gateway-driven path is in effect with no enabled\n // methods — it must NOT fall back to legacy `showApplePay`/`showGooglePay`\n // behaviour, and PayPal must stay suppressed unless `'paypal'` is in the\n // list (or `directPaypal` is configured separately).\n const hasEnabledMethodsPayload = Array.isArray(enabledPaymentMethods);\n const hasEnabledMethods = hasEnabledMethodsPayload && enabledPaymentMethods.length > 0;\n const paypalEnabled = hasEnabledMethodsPayload && enabledPaymentMethods.includes('paypal');\n const { expressMethods, paymentElementMethods } = useMemo(\n () => partitionStripeMethods(enabledPaymentMethods, {\n excludePaypal: directPaypalConfigured,\n }),\n [enabledPaymentMethods, directPaypalConfigured],\n );\n // Get raw Stripe instance early so we can decide whether PayPal renders\n // separately. `paypalStripeInstance` lives on the dedicated PayPal sub-\n // account when `gateways.stripe.paypalPublishableKey` is set; otherwise\n // PayPal can ride along inside the main wallet ECE.\n const paypalRenderedSeparately = directPaypalConfigured || !!paypalFlopay;\n // Drop PayPal from the main wallet ECE only when something else is going\n // to render it (DirectPayPal or the dedicated PayPal sub-account\n // PayPalButtonInner). When neither is configured, PayPal stays in the\n // express set so Stripe still shows the button on supported envs.\n const expressMethodsForWalletRow = useMemo(\n () => paypalRenderedSeparately\n ? expressMethods.filter((m) => m !== 'paypal')\n : expressMethods,\n [expressMethods, paypalRenderedSeparately],\n );\n const legacyExpressMethods = useMemo(() => {\n const out: string[] = [];\n if (showApplePay) out.push('apple_pay');\n if (showGooglePay) out.push('google_pay');\n return out;\n }, [showApplePay, showGooglePay]);\n // Final list driving WalletButtonInner. New path wins when the backend\n // ships the field; legacy props are used as the fallback only.\n // `hasEnabledMethodsPayload` (not `hasEnabledMethods`) gates the new-vs-legacy\n // switch: a provided-but-empty `enabledPaymentMethods=[]` means \"no methods\n // enabled\" under the new path, not \"fall back to legacy props\".\n const walletExpressMethods = hasEnabledMethodsPayload ? expressMethodsForWalletRow : legacyExpressMethods;\n const showWallets = showStripe && walletExpressMethods.length > 0;\n\n // Drop methods that don't support the session currency, the buyer's\n // country, or whose per-currency amount range excludes the session amount —\n // before we hand the list to Stripe. The `/v1/elements/sessions` endpoint\n // hard-400's when `paymentMethodTypes` contains a single method that\n // violates currency *or* amount, and the failed mount silently blanks out\n // the whole accordion as an empty `<div class=\"\">` shell. The triggers:\n //\n // - `bancontact` / `eps` / `giropay` on a USD cart — wrong currency.\n // - `affirm` on a sub-$35 USD cart — below Affirm's $35.00 minimum\n // (Stripe returns `amount_too_small` on the elements/sessions call).\n //\n // Country gating is the additional axis Stripe applies from the buyer's\n // locale: a Dutch buyer on a EUR cart sees iDEAL + SEPA but not Bancontact\n // (BE-only) or EPS (AT-only). We mirror that here off the session customer\n // country so the tile row matches what Stripe would ultimately accept.\n // A missing country leaves the country filter as a pass-through.\n const paymentElementMethodsForCurrency = useMemo(\n () => filterStripeMethodsByAmount(\n filterStripeMethodsByCountry(\n filterStripeMethodsByCurrency(paymentElementMethods, currency),\n countryProp,\n ),\n currency,\n amountInCents,\n ),\n [paymentElementMethods, currency, countryProp, amountInCents],\n );\n\n // PaymentElement Elements options — same `paymentMethodCreation: 'manual'`\n // mode as the card Elements so `createPaymentMethod({ elements })` works.\n // `paymentMethodTypes` is filtered to the non-express portion of the\n // backend-supplied enabled list (and to the methods Stripe accepts for the\n // session currency *and* amount) so the accordion never double-renders the\n // big buttons the wallet row already shows, and never includes a method\n // Stripe will reject.\n //\n // `captureMethod` is intentionally omitted (defaults to `automatic`): most\n // PaymentElement APMs (Cash App Pay, Affirm, Klarna, iDEAL, SEPA debit,\n // Bancontact, EPS, Giropay, …) do not support `manual` capture, and Stripe\n // rejects the entire Elements mount with a 400 on\n // `/v1/elements?type=deferred_intent` (\"Frame not initialized\"). The\n // accordion ends up rendered as an empty `<div class=\"\">` shell. Letting\n // capture default keeps the deferred-intent options accepted for the full\n // set of APMs we partition into this region.\n //\n // `appearance` is forwarded so the PaymentElement iframe picks up the same\n // theme variables (colours, border radius, font family) as the card row.\n // Without this, Stripe falls back to its grey defaults and the accordion\n // looks visually unrelated to the rest of the FloPay surface.\n // Base options for every per-method `<StripeElements>` group mounted by\n // `StripePaymentElementInner` (one per expanded inline form). The child\n // spreads this and tacks on `paymentMethodTypes: [<method>]` per group.\n // The per-method split is what lets each expanded form scope its\n // accordion to a single method without an `elements.update({\n // paymentMethodTypes })` call (which Stripe refuses).\n const paymentElementBaseOptions = useMemo(() => ({\n mode: 'payment' as const,\n amount: amountInCents,\n currency: currency.toLowerCase(),\n paymentMethodCreation: 'manual' as const,\n appearance: paymentElementAppearance,\n }), [amountInCents, currency, paymentElementAppearance]);\n\n // Stripe's PayPal ExpressCheckoutElement breaks inside known in-app browsers\n // and the existing flow gated it on `inAppBrowserDetected`. With the\n // gateway-driven model the renderer decision moves to `gateways.paypal`\n // (DirectPayPalButton when present, Stripe-rendered PayPal otherwise). When\n // backend ships `enabledPaymentMethods`, the in-app-browser gate is no\n // longer consulted — gateway configuration alone drives renderer choice.\n // Legacy backends keep the historic UA-based gate.\n const [paypalLoadState, setPaypalLoadState] = useState<ExpressCheckoutLoadState>('loading');\n const [walletLoadState, setWalletLoadState] = useState<ExpressCheckoutLoadState>('loading');\n const [paymentElementLoadState, setPaymentElementLoadState] = useState<'loading' | 'ready' | 'load_error'>('loading');\n const [directPaypalReady, setDirectPaypalReady] = useState(false);\n const [inAppBrowserDetected, setInAppBrowserDetected] = useState<boolean>();\n useEffect(() => {\n setInAppBrowserDetected(isInAppBrowser());\n }, []);\n // When the backend ships `enabledPaymentMethods`, the presence/absence of\n // `'paypal'` in that list decides PayPal visibility — a non-empty list that\n // omits `'paypal'` must suppress PayPal even if `paypalFlopay` is configured.\n // Only fall back to the legacy in-app-browser gate when no payload was sent\n // at all. `directPaypal` overrides both paths.\n const shouldShowPayPal = showPayPal\n && (directPaypalConfigured\n || (hasEnabledMethodsPayload\n ? paypalEnabled\n : inAppBrowserDetected === false));\n const shouldShowWallets = showStripe && showWallets;\n const shouldRenderDirectPayPal = shouldShowPayPal && directPaypalConfigured;\n const shouldRenderStripePayPal = shouldShowPayPal && !directPaypalConfigured && !!paypalStripeInstance;\n const shouldRenderWallets = shouldShowWallets && !!stripeInstance;\n // Suppress the entire PaymentElement region when the currency filter empties\n // the list — Stripe Elements won't mount with `paymentMethodTypes: []` and\n // we'd otherwise paint a blank divider row.\n const shouldRenderPaymentElement = showStripe\n && hasEnabledMethods\n && paymentElementMethodsForCurrency.length > 0\n && !!stripeInstance;\n const shouldDisplayPayPalRow = shouldRenderDirectPayPal\n ? directPaypalReady\n : shouldRenderStripePayPal && isExpressCheckoutRowVisible(paypalLoadState);\n const shouldDisplayWalletRow = shouldRenderWallets && isExpressCheckoutRowVisible(walletLoadState);\n const shouldDisplayPaymentElementRow = shouldRenderPaymentElement && paymentElementLoadState !== 'load_error';\n\n // ── Boot-time validation: nothing to render ──\n //\n // Both `showStripe` and `showPayPal` were turned off (or off + no PayPal\n // gateway present) — there's no payment surface to render. Surface this\n // as `onError` rather than silently rendering an empty form so the bug is\n // caught during integration.\n const validationFiredRef = useRef(false);\n useEffect(() => {\n if (validationFiredRef.current) return;\n if (!showStripe && !showPayPal) {\n validationFiredRef.current = true;\n const err = new FloPayError(\n 'FloPay: both `showStripe` and `showPayPal` are false — nothing to render.',\n 'validation_error',\n );\n onError?.(err);\n updateError(err.message);\n } else if (!showStripe && showPayPal && !directPaypalConfigured && !paypalStripeInstance) {\n validationFiredRef.current = true;\n const err = new FloPayError(\n 'FloPay: `showStripe` is false and no PayPal gateway is configured for this session — nothing to render.',\n 'validation_error',\n );\n onError?.(err);\n updateError(err.message);\n }\n }, [showStripe, showPayPal, directPaypalConfigured, paypalStripeInstance, onError, updateError]);\n\n // ── Deprecation warnings ──\n //\n // Emitted once per mount when consumers pass the legacy\n // `showApplePay`/`showGooglePay`/`directPaypal` props alongside the new\n // `enabledPaymentMethods` surface. The legacy props are *not* fed into the\n // new path (`enabledPaymentMethods` wins outright), so silently honouring\n // them would surprise consumers; the warning makes the migration visible.\n const deprecationLoggedRef = useRef(false);\n useEffect(() => {\n if (deprecationLoggedRef.current) return;\n if (!hasEnabledMethods) return;\n const stale: string[] = [];\n if (showApplePay !== true) stale.push('showApplePay');\n if (showGooglePay !== true) stale.push('showGooglePay');\n if (stale.length === 0) return;\n deprecationLoggedRef.current = true;\n // eslint-disable-next-line no-console\n console.warn(\n `[FloPay] ${stale.join(' / ')} ${stale.length === 1 ? 'is' : 'are'} deprecated: ` +\n 'the Apple Pay / Google Pay surface is now driven by ' +\n '`gateways.stripe.enabledPaymentMethods` on the session response. ' +\n 'Remove the legacy prop(s) to silence this warning.',\n );\n }, [hasEnabledMethods, showApplePay, showGooglePay]);\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 // Clear any pending paypal_direct_required retry — process\n // succeeded, so the re-bound retry button is no longer needed.\n setPaypalDirectRetry(null);\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 // Direct PayPal retry — backend created a fresh PayPal order\n // (typically after a failed inline-session reuse) and wants the SDK\n // to relaunch the PayPal popup against that order id. Re-binds the\n // existing DirectPayPalButton via `paypalDirectRetry` state; the\n // buyer clicks the same button again, PayPal opens with the new\n // order, and onApprove fires another /process call. Bounded to 2\n // retries so a misconfigured backend can't trap the buyer.\n if (json?.type === 'paypal_direct_required') {\n const orderId = json['orderId'] as string | undefined;\n if (!orderId) {\n setOverlayStatus('error');\n updateError('PayPal retry required but no order id provided.');\n return;\n }\n const prevAttempts = paypalDirectRetryRef.current?.attempts ?? 0;\n if (prevAttempts >= 2) {\n setOverlayStatus('error');\n updateError('PayPal payment could not be completed after multiple attempts.');\n emitDecline('paypal', 'paypal_direct_required retry limit exceeded');\n return;\n }\n setPaypalDirectRetry({ orderId, attempts: prevAttempts + 1 });\n // Hide the processing overlay so the buyer can see and act on the\n // re-bound PayPal button. Don't emitDecline — this isn't a decline.\n setOverlayStatus(null);\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 // ── Stripe resume (Cash App Pay / Klarna / iDEAL / Bancontact / …) ──\n //\n // Method-agnostic handler for the buyer returning from any Stripe\n // redirect-based payment method. The PaymentElement region writes its\n // tokenization state to `STRIPE_RESUME_KEY` (or the legacy\n // `flopay_wallet_resume` for back-compat with old SDK builds) *before*\n // calling `confirmPayment`, then we verify the PI status on return.\n //\n // Two gates before we hand off to /process — both required to avoid the\n // class of bugs where the SDK marches to /success on an uncharged PI:\n //\n // 1. **URL params must be present.** Stripe redirects buyers back with\n // `payment_intent` / `payment_intent_client_secret` / `redirect_status`\n // on the query string. If those are missing — the buyer hit back, the\n // auth tab was closed, or this is just a normal `/theme` mount — we\n // do nothing, even if `STRIPE_RESUME_KEY` is still in localStorage.\n //\n // 2. **Stripe-side PI status must be successful.** We `retrievePaymentIntent`\n // and only dispatch when the actual status is one of\n // `succeeded` / `requires_capture` / `processing`. A `redirect_status`\n // of `failed`, a buyer who closed the popup without approving (PI stuck\n // at `requires_action`), or a canceled PI all route to `onDecline`.\n //\n // PayPal-direct uses its own resume effect (`PayPalButtonInner`); this\n // handler intentionally excludes the PayPal Stripe sub-account flow to\n // avoid double-dispatch.\n const stripeResumeAttemptedRef = useRef(false);\n useEffect(() => {\n if (typeof window === 'undefined' || stripeResumeAttemptedRef.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 // No `payment_intent` URL param = buyer didn't actually return from a\n // Stripe redirect. Skip even if `STRIPE_RESUME_KEY` is in localStorage:\n // that key is set *before* confirmPayment, so it lives in localStorage\n // between click and authorization. A page reload, navigation, or close\n // of the auth tab would otherwise replay it as a phantom success.\n if (!paymentIntentId || !clientSecret) return;\n\n const readPayload = (key: string) => {\n const raw = localStorage.getItem(key);\n if (!raw) return null;\n try {\n return JSON.parse(raw) as {\n sessionId?: string;\n paymentIntentId?: string;\n paymentMethodId?: string;\n paymentMethodType?: string;\n gateway?: string;\n tokenType?: string;\n tokenId?: string;\n status?: string;\n } | null;\n } catch {\n localStorage.removeItem(key);\n return null;\n }\n };\n\n const payload =\n readPayload(STRIPE_RESUME_KEY) ?? readPayload(LEGACY_WALLET_RESUME_KEY);\n if (payload?.sessionId && payload.sessionId !== sessionId) return;\n\n stripeResumeAttemptedRef.current = true;\n localStorage.removeItem(STRIPE_RESUME_KEY);\n localStorage.removeItem(LEGACY_WALLET_RESUME_KEY);\n\n // Strip Stripe's redirect params synchronously before any async work, so\n // a remount that races our async retrieval can't re-enter this effect\n // for the same PI.\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 const paymentMethodType =\n payload?.paymentMethodType ?? payload?.tokenType ?? 'card';\n const declineMethod: CheckoutButtonMethod = 'card';\n\n (async () => {\n const rawProvider = flopay?.getRawProvider() as Stripe | null | undefined;\n if (!rawProvider) {\n const message = 'Payment is not available — please refresh and try again.';\n updateError(message);\n emitDecline(declineMethod, message);\n return;\n }\n\n if (redirectStatus === 'failed') {\n const message = 'Payment was declined. Please try again.';\n updateError(message);\n emitDecline(declineMethod, message);\n return;\n }\n\n const { paymentIntent, error } = await rawProvider.retrievePaymentIntent(clientSecret);\n if (error) {\n const message = error.message ?? 'Failed to retrieve payment status.';\n updateError(message);\n emitDecline(declineMethod, message, { code: error.code });\n return;\n }\n\n const piStatus = paymentIntent?.status;\n const successful = piStatus === 'succeeded' || piStatus === 'requires_capture' || piStatus === 'processing';\n if (!paymentIntent || !successful) {\n const message = piStatus === 'canceled'\n ? 'Payment was canceled.'\n : 'Payment was not completed. Please try again.';\n updateError(message);\n emitDecline(declineMethod, message, { code: piStatus ?? 'missing_payment_intent' });\n return;\n }\n\n const resolvedPmId = typeof paymentIntent.payment_method === 'string'\n ? paymentIntent.payment_method\n : paymentIntent.payment_method?.id;\n\n dispatchTokenizedBody({\n id: resolvedPmId ?? payload?.paymentMethodId ?? payload?.tokenId ?? paymentIntent.id,\n type: 'card',\n threeDSecureActionResultTokenId: paymentIntent.id,\n gateway: (payload?.gateway as 'stripe' | 'paypal' | undefined) ?? 'stripe',\n paymentMethodType,\n });\n })();\n }, [sessionId, dispatchTokenizedBody, flopay, updateError, emitDecline]);\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 // Three-tier fallback for visual styling:\n // 1. `bStyles` (resolved from `buttonsTheme` + `buttonsStyles` override) —\n // the explicit, coherent bundle. Wins when present.\n // 2. `appearance.variables` from FloPayProvider — covers consumers who\n // pass only the Stripe-side appearance and still expect the React\n // wrapper / submit / inputs to recolor.\n // 3. Hardcoded layout defaults — back-compat for callers passing neither.\n // This is what makes `<FloPayCheckout appearance={THEMES['glass-dark'].appearance} />`\n // produce a visible recolor even before the demo forwards the buttonsLayout half.\n const appearanceVars = appearance?.variables;\n // `appearance.colorBackground` is, in Stripe terms, the *input* surface — not\n // the outer FloPay wrapper. Treat the SDK's default white as \"consumer did\n // not theme the wrapper\" so the historic `#EDEDFF` FloPay tint stays put on\n // the classic preset. Themed bundles supply non-white backgrounds and still\n // flow through to the wrapper as expected.\n const SDK_DEFAULT_WHITES = new Set(['#FFFFFF', '#ffffff', '#fff', '#FFF', 'white']);\n const appearanceColorBg = appearanceVars?.colorBackground;\n const themedWrapperBg =\n appearanceColorBg && !SDK_DEFAULT_WHITES.has(appearanceColorBg) ? appearanceColorBg : undefined;\n const resolvedBorder = bStyles.cardInputBorder ?? (isButtons ? '#e5e7eb' : '#A4A4FF');\n const cardBg =\n (bStyles.cardFormContainer?.backgroundColor as string)\n ?? themedWrapperBg\n ?? (isButtons ? 'white' : '#EDEDFF');\n const cardInputBg =\n bStyles.cardInputBackground\n ?? appearanceVars?.colorBackground\n ?? 'white';\n const hideBackButtonLabel = isEmptySlotContent(cardBackButtonContent);\n const hideTitle = isEmptySlotContent(cardTitleContent);\n const nameInputOverrides = bStyles.nameInput;\n const resolvedInputFontSize = bStyles.cardInputFontSize\n ?? toCssSize(nameInputOverrides?.fontSize)\n ?? appearanceVars?.fontSizeBase\n ?? '16px';\n const resolvedInputFontFamily = typeof nameInputOverrides?.fontFamily === 'string'\n ? nameInputOverrides.fontFamily\n : (appearanceVars?.fontFamily ?? 'Poppins, sans-serif');\n const resolvedInputFontWeight = toCssWeight(nameInputOverrides?.fontWeight) ?? 400;\n const resolvedInputColor = bStyles.cardInputColor\n ?? (typeof nameInputOverrides?.color === 'string' ? nameInputOverrides.color : undefined)\n ?? appearanceVars?.colorText\n ?? '#262833';\n const resolvedPlaceholderColor = bStyles.cardInputPlaceholderColor ?? '#9ca3af';\n const resolvedBorderRadius = appearanceVars?.borderRadius ?? '8px';\n // `colorPrimary` drives the submit button background when no buttonsStyles\n // override is supplied. Default keeps the historic FloPay indigo.\n const resolvedPrimaryColor = appearanceVars?.colorPrimary ?? '#4A49FF';\n const resolvedTitleColor = appearanceVars?.colorText ?? '#262833';\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 containerOverrides = (bStyles.cardFormContainer ?? {}) as React.CSSProperties;\n const containerPadding = containerOverrides.padding ?? (isButtons ? '0' : '1rem');\n const containerRadius = containerOverrides.borderRadius ?? resolvedBorderRadius;\n const cardFormBlock = (\n <div style={{\n backgroundColor: cardBg, borderRadius: containerRadius,\n ...containerOverrides,\n padding: containerPadding,\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={{\n textAlign: 'center', fontWeight: 600, fontSize: '1.1rem', padding: '0.5rem 0',\n color: resolvedTitleColor,\n ...(bStyles.title as React.CSSProperties | undefined),\n }}>\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,\n // Longhand only — mixing `border` shorthand with per-side\n // overrides triggers React's \"shorthand vs longhand\" warning\n // because render order isn't deterministic.\n borderTop: 'none', borderRight: 'none',\n borderBottom: `1px solid ${resolvedBorder}`,\n borderLeft: `1px solid ${resolvedBorder}`,\n borderBottomLeftRadius: '8px', padding: '10px',\n }}>\n <CardExpiryElement options={stripeElementStyle} />\n </div>\n <div style={{\n flex: 1, backgroundColor: cardInputBg,\n borderTop: 'none',\n borderRight: `1px solid ${resolvedBorder}`,\n borderBottom: `1px solid ${resolvedBorder}`,\n borderLeft: `1px solid ${resolvedBorder}`,\n 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,\n borderTop: `1px solid ${resolvedBorder}`,\n borderRight: `1px solid ${resolvedBorder}`,\n borderBottom: `1px solid ${resolvedBorder}`,\n borderLeft: `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,\n borderTop: `1px solid ${resolvedBorder}`,\n borderRight: `1px solid ${resolvedBorder}`,\n borderBottom: `1px solid ${resolvedBorder}`,\n borderLeft: `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 ...(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: resolvedPrimaryColor, color: 'white', border: 'none',\n borderRadius: resolvedBorderRadius,\n fontSize: bStyles.submitButtonFontSize ?? '1rem',\n fontWeight: 600,\n cursor: !formReady || isSubmitting ? 'not-allowed' : 'pointer',\n opacity: !formReady || isSubmitting ? 0.5 : 1,\n ...(bStyles.submitButton as React.CSSProperties),\n }}\n >\n {isSubmitting ? 'PROCESSING...' : submitLabel}\n </button>\n )}\n </div>\n );\n\n // ── Parent-side debug panels ──\n //\n // Surface the parent-gate decisions for each gateway on-screen so the most\n // common misconfigurations (session missing `gateways.paypal.publishableKey`,\n // Stripe filtering by currency, empty `enabledPaymentMethods`, …) are\n // visible without opening DevTools. When the gateway is disabled via its\n // `show*` prop we still emit a single-line marker so the absence is\n // obvious — silent omission used to look identical to a debug-off SDK.\n const gateDebugStyle: React.CSSProperties = {\n margin: 0,\n padding: '6px 8px',\n background: '#eef2ff',\n border: '1px solid #c7d2fe',\n borderRadius: 6,\n color: '#111827',\n font: '11px/1.35 ui-monospace, SFMono-Regular, Menlo, monospace',\n whiteSpace: 'pre-wrap',\n wordBreak: 'break-word',\n };\n // Reflect the session-response gateways. The DirectPayPal renderer is named\n // after the PayPal JS SDK path, so its \"enabled\" condition is the presence\n // of `gateways.paypal` upstream — surfaced here as `directPaypal.clientId`.\n // Likewise the Stripe parent gate is \"enabled\" when `gateways.stripe.publishable\\\n // Key` was wired up into a Stripe instance. Without either, the matching\n // renderer cannot run on this session regardless of the `show*` toggles, so\n // the panel collapses to the single \"not enabled\" marker.\n const renderDirectPaypalGateDebug = (testId: string) => {\n if (!debug) return null;\n if (!showPayPal || !directPaypalConfigured) {\n return (\n <pre data-testid={testId} style={gateDebugStyle}>\n {'FloPay/DirectPayPal-debug - not enabled'}\n </pre>\n );\n }\n return (\n <pre data-testid={testId} style={gateDebugStyle}>{[\n 'FloPay/DirectPayPal-debug (parent gate)',\n ` showPayPal=${showPayPal}`,\n ` directPaypalConfigured=${directPaypalConfigured}`,\n ` inAppBrowserDetected=${String(inAppBrowserDetected)}`,\n ` shouldRenderDirectPayPal=${shouldRenderDirectPayPal}`,\n ` shouldRenderStripePayPal=${shouldRenderStripePayPal}`,\n ` hasPaypalStripeInstance=${!!paypalStripeInstance}`,\n ].join('\\n')}</pre>\n );\n };\n const renderStripeGateDebug = (testId: string) => {\n if (!debug) return null;\n if (!showStripe || !stripeInstance) {\n return (\n <pre data-testid={testId} style={gateDebugStyle}>\n {'FloPay/Stripe-debug - not enabled'}\n </pre>\n );\n }\n return (\n <pre data-testid={testId} style={gateDebugStyle}>{[\n 'FloPay/Stripe-debug (parent gate)',\n ` showStripe=${showStripe}`,\n ` currency=${currency}`,\n ` amountInCents=${amountInCents}`,\n ` enabledPaymentMethods: ${JSON.stringify(enabledPaymentMethods ?? [])}`,\n ` enabledPaymentMethodsProvided=${hasEnabledMethodsPayload}`,\n ` hasEnabledMethods=${hasEnabledMethods}`,\n ` expressMethods: ${JSON.stringify(expressMethods)}`,\n ` walletExpressMethods: ${JSON.stringify(walletExpressMethods)}`,\n ` paymentElementMethods: ${JSON.stringify(paymentElementMethods)}`,\n ` paymentElementMethodsForCurrency: ${JSON.stringify(paymentElementMethodsForCurrency)}`,\n ` hasStripeInstance=${!!stripeInstance}`,\n ` shouldRenderWallets=${shouldRenderWallets}`,\n ` shouldRenderPaymentElement=${shouldRenderPaymentElement}`,\n ].join('\\n')}</pre>\n );\n };\n\n // ── APM 2nd-page derivations (shared by both layouts) ──\n // Lifted out of the layout branches so the default-layout (card form\n // visible inline) can also use the 2nd-page drill-in for input-form\n // APMs — without this, default-layout clicks on SEPA / EPS / iDEAL\n // were stuck on the local inline-expansion fallback path.\n const isApmView = viewState === 'apm-expanding' || viewState === 'apm-form' || viewState === 'apm-collapsing';\n const apmAnim = viewState === 'apm-expanding'\n ? `flopay-card-enter ${TRANSITION_MS}ms cubic-bezier(0, 0, 0.2, 1) both`\n : viewState === 'apm-collapsing'\n ? `flopay-card-exit ${TRANSITION_MS}ms cubic-bezier(0.4, 0, 0.2, 1) both`\n : undefined;\n // Per-method Elements options for the APM 2nd page. Built lazily by\n // method — the group only mounts while `viewState` is in the apm-*\n // family, so switching APMs (back → choose another) tears down the\n // previous Stripe Elements instance cleanly.\n const apmInlineOptions = expandedApmMethod ? {\n ...paymentElementBaseOptions,\n paymentMethodTypes: [expandedApmMethod],\n } as Parameters<typeof StripeElements>[0]['options'] : null;\n\n // ── Buttons layout ──\n if (layout === 'buttons') {\n const isButtonsView =\n viewState === 'buttons' ||\n viewState === 'expanding' ||\n viewState === 'apm-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 // The buttons panel slides out the same way whether we're going to the\n // card 2nd page or an APM 2nd page — same exit/enter animations so\n // the two drill-ins feel identical.\n const buttonsAnim = (viewState === 'expanding' || viewState === 'apm-expanding')\n ? `flopay-buttons-exit ${TRANSITION_MS}ms cubic-bezier(0.4, 0, 0.2, 1) both`\n : (viewState === 'collapsing' || viewState === 'apm-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\n data-testid=\"flopay-buttons-panel\"\n aria-hidden={!isButtonsView && !buttonsAnim ? true : undefined}\n 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 ? BUTTONS_PANEL_HIDDEN_STYLE : {}),\n ...(buttonsAnim ? { animation: buttonsAnim, pointerEvents: 'none' as const } : {}),\n }}>\n {renderDirectPaypalGateDebug('flopay-direct-paypal-gate-debug')}\n {renderStripeGateDebug('flopay-stripe-gate-debug')}\n {/* PayPal — Direct PayPal JS SDK when configured, otherwise Stripe-rendered PayPal */}\n {shouldRenderDirectPayPal && directPaypal && (\n <>\n {paypalDirectRetry && (\n <div\n data-testid=\"flopay-paypal-direct-retry-notice\"\n style={{\n padding: '8px 10px',\n background: '#fef3c7',\n border: '1px solid #fcd34d',\n borderRadius: 6,\n color: '#78350f',\n fontSize: 13,\n lineHeight: 1.4,\n }}\n >\n Please confirm your PayPal payment to complete checkout.\n </div>\n )}\n <DirectPayPalButton\n // Force a remount when the retry id changes so PayPal's\n // SDK picks up the new createOrder binding (render()\n // options aren't live-updatable). `key` matches the\n // existingOrderId effect-dep update on the child.\n key={paypalDirectRetry?.orderId ?? 'fresh'}\n sessionId={sessionId}\n billingApiUrl={resolvedBillingApiUrl}\n email={resolvedAccount.email}\n clientId={directPaypal.clientId}\n environment={directPaypal.environment}\n currency={currency.toUpperCase()}\n isSubscription={isSubscription}\n onTokenizedBody={dispatchTokenizedBody}\n onComplete={onComplete}\n onErrorChange={updateError}\n onDecline={onDecline}\n onButtonClick={onButtonClick}\n runBeforeButtonClick={runBeforeButtonClick}\n isProcessing={isSubmitting}\n onLoadStateChange={setDirectPaypalReady}\n session={session ?? null}\n existingOrderId={paypalDirectRetry?.orderId}\n debug={debug}\n />\n </>\n )}\n {shouldRenderStripePayPal && (\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 placeholderBorderRadius={(bStyles.cardButton?.borderRadius as string | number | undefined) ?? resolvedBorderRadius}\n />\n </StripeElements>\n )}\n\n {/* Wallets / express methods (Apple Pay / Google Pay / Link / Amazon Pay / Klarna) */}\n {shouldRenderWallets ? (\n <StripeElements stripe={stripeInstance} options={walletOptions}>\n <WalletButtonInner\n sessionId={sessionId}\n email={resolvedAccount.email}\n billingApiUrl={resolvedBillingApiUrl}\n expressMethods={walletExpressMethods}\n onTokenizedBody={dispatchTokenizedBody}\n onErrorChange={updateError}\n onButtonClick={onButtonClick}\n onDecline={onDecline}\n runBeforeButtonClick={runBeforeButtonClick}\n onLoadStateChange={setWalletLoadState}\n placeholderBorderRadius={(bStyles.cardButton?.borderRadius as string | number | undefined) ?? resolvedBorderRadius}\n />\n </StripeElements>\n ) : shouldShowWallets ? (\n <div style={{ height: DEFAULT_BUTTONS_LAYOUT_BUTTON_HEIGHT, borderRadius: (bStyles.cardButton?.borderRadius as string | number | undefined) ?? resolvedBorderRadius, background: '#e5e7eb', animation: 'flopay-pulse 1.5s ease-in-out infinite' }} />\n ) : null}\n\n {/* PaymentElement region — Cash App Pay / Affirm / iDEAL / SEPA … */}\n {shouldRenderPaymentElement && (\n <StripePaymentElementInner\n sessionId={sessionId}\n email={resolvedAccount.email}\n billingName={[resolvedAccount.firstName, resolvedAccount.lastName].filter(Boolean).join(' ').trim() || undefined}\n billingApiUrl={resolvedBillingApiUrl}\n paymentElementMethods={paymentElementMethodsForCurrency}\n stripeInstance={stripeInstance}\n paymentElementBaseOptions={paymentElementBaseOptions}\n onTokenizedBody={dispatchTokenizedBody}\n onErrorChange={updateError}\n onButtonClick={onButtonClick}\n onDecline={onDecline}\n runBeforeButtonClick={runBeforeButtonClick}\n onLoadStateChange={setPaymentElementLoadState}\n isProcessing={isSubmitting}\n submitButtonColor={resolvedPrimaryColor}\n submitButtonBorderRadius={resolvedBorderRadius}\n submitButtonStyle={bStyles.submitButton as React.CSSProperties | undefined}\n // Input-form methods (SEPA / EPS / iDEAL / Bacs) drill\n // into a 2nd-page panel rendered alongside the card\n // form below. `StripePaymentElementInner` itself only\n // renders the tile-button row; the parent owns the\n // navigation state machine.\n onExpandApm={expandToApm}\n expandedApmMethod={expandedApmMethod}\n themeId={theme}\n // The `buttonAppearance` override is only used as a\n // *fallback* — `STRIPE_METHOD_MATRIX[<method>].theme`\n // takes precedence inside the tile, so brand-styled\n // methods (Cash App green, Klarna pink, …) keep their\n // brand colors regardless of the bundle's `cardButton`\n // styling. Methods with no `theme` entry pick up the\n // bundle's neutral tile here.\n buttonAppearance={{\n backgroundColor: bStyles.cardButton?.backgroundColor as string | undefined,\n borderColor: bStyles.cardInputBorder,\n textColor: bStyles.cardButton?.color as string | undefined,\n borderRadius: bStyles.cardButton?.borderRadius as string | number | undefined,\n }}\n />\n )}\n\n {/* Credit / Debit Card button — gated on `showStripe` so the\n PayPal-only flow doesn't expose an unusable card option.\n Themed: `derivePrimaryTileStyle` flips the base from white\n + grey border (classic) to a primary-colored fill that\n mirrors the theme's submit/CTA action. */}\n {showStripe && (\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 // `bStyles.cardButton` first — supplies the bundle's\n // padding / typography / border-radius — then the\n // primary surface overrides on top, so the card button\n // ends up wearing the *submit* button's colours rather\n // than the bundle's neutral white-tile `cardButton`\n // colours. Without this order flip, every non-classic\n // bundle's `cardButton.backgroundColor` was winning\n // over the primary fill we just derived above it.\n ...bStyles.cardButton as React.CSSProperties,\n ...derivePrimaryTileStyle({\n themeBundle,\n resolvedPrimaryColor,\n resolvedBorderRadius,\n submitButtonStyle: bStyles.submitButton as React.CSSProperties | undefined,\n }),\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 position: 'relative',\n opacity: isSubmitting ? 0.6 : 1,\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\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 — gated on `showStripe` (PayPal-only flow hides it). */}\n {showStripe && 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\n {/* APM 2nd page — mirrors the card-form 2nd page exactly:\n same gridArea, same back-button chrome, same enter/exit\n animations. The only differences are the title (method\n display name) and the body (single-method Stripe\n PaymentElement instead of the split-card fields). */}\n {showStripe && isApmView && expandedApmMethod && apmInlineOptions && stripeInstance && (\n <div style={{\n gridArea: '1 / 1',\n ...(apmAnim ? { animation: apmAnim } : {}),\n ...(viewState === 'apm-collapsing' ? { pointerEvents: 'none' as const } : {}),\n }}>\n <div style={{\n backgroundColor: cardBg, borderRadius: containerRadius,\n ...containerOverrides,\n padding: containerPadding,\n }}>\n {/* Header: back button + method-name title — pixel-for-\n pixel the same chrome as the card-form header. */}\n <div style={{\n display: 'flex', alignItems: 'center', padding: '0.75rem 0 0.625rem',\n }}>\n <button\n type=\"button\"\n data-testid=\"flopay-apm-back-button\"\n onClick={collapseFromApm}\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 <div style={{\n flex: 1, textAlign: 'center', fontWeight: 600,\n fontSize: bStyles.titleFontSize ?? '1.05rem',\n color: resolvedTitleColor, paddingRight: 80,\n ...bStyles.title as React.CSSProperties,\n }}>\n {`Pay with ${getStripeMethodDisplayName(expandedApmMethod)}`}\n </div>\n </div>\n\n {/* Per-method Elements group: keyed by method so switching\n APMs unmounts the previous group cleanly. */}\n <StripeElements\n key={expandedApmMethod}\n stripe={stripeInstance}\n options={apmInlineOptions}\n >\n <StripeMethodInlineForm\n method={expandedApmMethod}\n sessionId={sessionId}\n email={resolvedAccount.email}\n billingName={[resolvedAccount.firstName, resolvedAccount.lastName].filter(Boolean).join(' ').trim() || undefined}\n billingApiUrl={resolvedBillingApiUrl}\n onTokenizedBody={dispatchTokenizedBody}\n onErrorChange={updateError}\n onDecline={onDecline}\n onCancel={collapseFromApm}\n runBeforeButtonClick={runBeforeButtonClick}\n onButtonClick={onButtonClick}\n isProcessing={isSubmitting}\n submitButtonColor={resolvedPrimaryColor}\n submitButtonBorderRadius={resolvedBorderRadius}\n submitButtonStyle={bStyles.submitButton as React.CSSProperties | undefined}\n />\n </StripeElements>\n </div>\n </div>\n )}\n </div>\n </form>\n );\n }\n\n // ── Default layout ──\n // When an input-form APM is expanded, render *only* its 2nd-page panel\n // (back button + scoped PaymentElement + Pay button) — the wallet row,\n // APM tiles, divider and card form all step aside so the buyer's focus\n // is on completing the inline form. Hitting \"Go back\" restores the\n // normal layout. Same chrome as the buttons-layout 2nd page so the\n // experience is consistent across both layouts.\n if (isApmView && expandedApmMethod && apmInlineOptions && stripeInstance && showStripe) {\n return (\n <form onSubmit={handleSubmit} className={className} style={{ position: 'relative' }}>\n <FloPayKeyframes />\n {overlayStatus && <ProcessingOverlay status={overlayStatus} errorMessage={displayError} />}\n <div style={{\n ...(apmAnim ? { animation: apmAnim } : {}),\n ...(viewState === 'apm-collapsing' ? { pointerEvents: 'none' as const } : {}),\n }}>\n <div style={{\n backgroundColor: cardBg, borderRadius: containerRadius,\n ...containerOverrides,\n padding: containerPadding,\n }}>\n {/* Back-button chrome — same circle icon + theme back-button\n styling as the card form 2nd page in the buttons layout. */}\n <div style={{\n display: 'flex', alignItems: 'center', padding: '0.75rem 0 0.625rem',\n }}>\n <button\n type=\"button\"\n data-testid=\"flopay-apm-back-button-default\"\n onClick={collapseFromApm}\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 <div style={{\n flex: 1, textAlign: 'center', fontWeight: 600,\n fontSize: bStyles.titleFontSize ?? '1.05rem',\n color: resolvedTitleColor, paddingRight: 80,\n ...bStyles.title as React.CSSProperties,\n }}>\n {`Pay with ${getStripeMethodDisplayName(expandedApmMethod)}`}\n </div>\n </div>\n\n <StripeElements\n key={expandedApmMethod}\n stripe={stripeInstance}\n options={apmInlineOptions}\n >\n <StripeMethodInlineForm\n method={expandedApmMethod}\n sessionId={sessionId}\n email={resolvedAccount.email}\n billingName={[resolvedAccount.firstName, resolvedAccount.lastName].filter(Boolean).join(' ').trim() || undefined}\n billingApiUrl={resolvedBillingApiUrl}\n onTokenizedBody={dispatchTokenizedBody}\n onErrorChange={updateError}\n onDecline={onDecline}\n onCancel={collapseFromApm}\n runBeforeButtonClick={runBeforeButtonClick}\n onButtonClick={onButtonClick}\n isProcessing={isSubmitting}\n submitButtonColor={resolvedPrimaryColor}\n submitButtonBorderRadius={resolvedBorderRadius}\n submitButtonStyle={bStyles.submitButton as React.CSSProperties | undefined}\n />\n </StripeElements>\n </div>\n </div>\n </form>\n );\n }\n\n return (\n <form onSubmit={handleSubmit} className={className} style={{ position: 'relative' }}>\n <FloPayKeyframes />\n {overlayStatus && <ProcessingOverlay status={overlayStatus} errorMessage={displayError} />}\n\n {/* Express-checkout row — flex column with `gap` matches the buttons\n layout, so wallet/PayPal/Stripe-PayPal always sit `0.5rem` apart\n regardless of which combination is rendered. Order matches the\n buttons layout: PayPal first, then wallets. */}\n <div style={{ display: 'flex', flexDirection: 'column', gap: '0.5rem' }}>\n {renderDirectPaypalGateDebug('flopay-direct-paypal-gate-debug-default')}\n {renderStripeGateDebug('flopay-stripe-gate-debug-default')}\n {/* PayPal — Direct PayPal JS SDK when configured, otherwise Stripe-rendered PayPal */}\n {shouldRenderDirectPayPal && directPaypal && (\n <>\n {paypalDirectRetry && (\n <div\n data-testid=\"flopay-paypal-direct-retry-notice-default\"\n style={{\n padding: '8px 10px',\n background: '#fef3c7',\n border: '1px solid #fcd34d',\n borderRadius: 6,\n color: '#78350f',\n fontSize: 13,\n lineHeight: 1.4,\n }}\n >\n Please confirm your PayPal payment to complete checkout.\n </div>\n )}\n <DirectPayPalButton\n // Remount when retry id changes so PayPal SDK picks up the\n // new createOrder binding.\n key={paypalDirectRetry?.orderId ?? 'fresh'}\n sessionId={sessionId}\n billingApiUrl={resolvedBillingApiUrl}\n email={resolvedAccount.email}\n clientId={directPaypal.clientId}\n environment={directPaypal.environment}\n currency={currency.toUpperCase()}\n isSubscription={isSubscription}\n onTokenizedBody={dispatchTokenizedBody}\n onComplete={onComplete}\n onErrorChange={updateError}\n onDecline={onDecline}\n onButtonClick={onButtonClick}\n runBeforeButtonClick={runBeforeButtonClick}\n isProcessing={isSubmitting}\n onLoadStateChange={setDirectPaypalReady}\n session={session ?? null}\n existingOrderId={paypalDirectRetry?.orderId}\n debug={debug}\n />\n </>\n )}\n {shouldRenderStripePayPal && (\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 placeholderBorderRadius={(bStyles.cardButton?.borderRadius as string | number | undefined) ?? resolvedBorderRadius}\n />\n </StripeElements>\n )}\n\n {/* Wallet / express buttons — 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 expressMethods={walletExpressMethods}\n onTokenizedBody={dispatchTokenizedBody}\n onErrorChange={updateError}\n onButtonClick={onButtonClick}\n onDecline={onDecline}\n runBeforeButtonClick={runBeforeButtonClick}\n onLoadStateChange={setWalletLoadState}\n placeholderBorderRadius={(bStyles.cardButton?.borderRadius as string | number | undefined) ?? resolvedBorderRadius}\n />\n </StripeElements>\n )}\n\n {/* PaymentElement region — non-express APMs (Cash App Pay, Klarna, iDEAL, SEPA, …) */}\n {shouldRenderPaymentElement && (\n <StripePaymentElementInner\n sessionId={sessionId}\n email={resolvedAccount.email}\n billingName={[resolvedAccount.firstName, resolvedAccount.lastName].filter(Boolean).join(' ').trim() || undefined}\n billingApiUrl={resolvedBillingApiUrl}\n paymentElementMethods={paymentElementMethodsForCurrency}\n stripeInstance={stripeInstance}\n paymentElementBaseOptions={paymentElementBaseOptions}\n onTokenizedBody={dispatchTokenizedBody}\n onErrorChange={updateError}\n onButtonClick={onButtonClick}\n onDecline={onDecline}\n runBeforeButtonClick={runBeforeButtonClick}\n onLoadStateChange={setPaymentElementLoadState}\n isProcessing={isSubmitting}\n submitButtonColor={resolvedPrimaryColor}\n submitButtonBorderRadius={resolvedBorderRadius}\n submitButtonStyle={bStyles.submitButton as React.CSSProperties | undefined}\n themeId={theme}\n // Route input-form APM clicks (SEPA / EPS / iDEAL / Bacs)\n // through the parent's `viewState` machine — same 2nd-page\n // pattern as the buttons-layout, just without the in/out\n // transition since the default layout doesn't pre-render the\n // panel alongside an animated buttons row.\n onExpandApm={expandToApm}\n expandedApmMethod={expandedApmMethod}\n buttonAppearance={{\n backgroundColor: bStyles.cardButton?.backgroundColor as string | undefined,\n borderColor: bStyles.cardInputBorder,\n textColor: bStyles.cardButton?.color as string | undefined,\n borderRadius: bStyles.cardButton?.borderRadius as string | number | undefined,\n }}\n />\n )}\n </div>\n\n {/* Divider between wallet/PayPal buttons and card fields — only when\n the card form is actually going to render. */}\n {showStripe && (shouldDisplayWalletRow || shouldDisplayPayPalRow || shouldDisplayPaymentElementRow) && (\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 {showStripe && 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 Stripe `FloPay` instance dedicated to the Stripe-rendered\n * PayPal fallback, or `null` if PayPal is disabled for this session. Direct\n * PayPal (`gateways.paypal`) does not use this instance.\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 inputProducts = params.products ?? [\n ...(params.subscriptions ?? []).map((s) => ({\n type: 'subscription' as const,\n code: s.code ?? s.providerPlanId,\n name: s.subscriptionName ?? s.providerPlanName ?? s.code ?? s.providerPlanId ?? null,\n quantity: s.quantity ?? 1,\n totalAmount: s.totalAmount,\n overrideAmount: s.overrideAmount,\n currency: s.currency,\n metadata: s.metadata,\n })),\n ...(params.items ?? []).map((i) => ({\n type: 'item' as const,\n code: i.code ?? i.providerItemId,\n name: i.itemName ?? i.providerItemName ?? i.code ?? i.providerItemId ?? null,\n quantity: i.quantity ?? 1,\n totalAmount: i.totalAmount,\n overrideAmount: i.overrideAmount,\n currency: i.currency,\n metadata: i.metadata,\n })),\n ];\n\n const totalAmount = inputProducts.reduce(\n (sum, p) => sum + ((p.overrideAmount ?? p.totalAmount) ?? 0),\n 0,\n );\n const currency = params.currency\n ?? inputProducts.find((p) => p.currency)?.currency\n ?? 'USD';\n\n return {\n id: '',\n clientSecret: '',\n mode: inputProducts.some((p) => p.type === 'subscription') ? 'subscription' : '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 products: inputProducts.map((p, idx) => ({\n uuid: `synthetic-${p.type}-${idx}`,\n checkoutSessionId: '',\n type: p.type,\n code: p.code,\n name: p.name ?? null,\n quantity: p.quantity ?? 1,\n totalAmount: p.totalAmount,\n overrideAmount: p.overrideAmount ?? null,\n currency: p.currency ?? currency,\n metadata: p.metadata ?? null,\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\nconst FRIENDLY_MESSAGE_OVERRIDES: Array<{ match: RegExp; replacement: string }> = [\n {\n match: /^paypal authorization required\\.?$/i,\n replacement: 'For your additional security, please re-authenticate this payment via PayPal.',\n },\n];\n\nexport function applyFriendlyMessageOverride(message: string | undefined | null): string | undefined {\n if (typeof message !== 'string') return message ?? undefined;\n const trimmed = message.trim();\n if (!trimmed) return message;\n for (const { match, replacement } of FRIENDLY_MESSAGE_OVERRIDES) {\n if (match.test(trimmed)) return replacement;\n }\n return message;\n}\n\nexport function buildFloPayApiError(\n payload: ApiErrorPayload,\n fallbackMessage: string,\n): FloPayError {\n const nestedError = isRecord(payload?.error) ? payload.error : null;\n const rawMessage =\n readString(payload, 'message') ??\n readString(nestedError, 'message') ??\n fallbackMessage;\n const message = applyFriendlyMessageOverride(rawMessage) ?? rawMessage;\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 React, { useEffect, useMemo, useRef, useState } from 'react';\nimport { loadScript } from '@paypal/paypal-js';\nimport type { PayPalNamespace } from '@paypal/paypal-js';\nimport { PaymentAPI } from '@flopay/js';\nimport type {\n CheckoutButtonMethod,\n CheckoutSession,\n DeclineEvent,\n GatewayEnvironment,\n InlineSessionPatch,\n PaymentResult,\n TokenizedBody,\n} from '@flopay/shared';\nimport { FloPayError, normalizeGatewayEnvironment } from '@flopay/shared';\nimport { applyFriendlyMessageOverride, buildDeclineEvent } from './checkout-utils.js';\n\nconst DEFAULT_BUTTON_HEIGHT = 45;\n\n/**\n * Overrides that `SplitCardForm`'s tokenized-body dispatcher uses to apply a\n * `runBeforeButtonClick` patch to the in-flight processPayment call. Kept in\n * sync structurally with `TokenizedBodyOverrides` in `split-card-form.tsx`.\n */\nexport interface DirectPayPalTokenizedOverrides {\n accountPatch?: InlineSessionPatch['account'];\n sessionId?: string;\n}\n\n/**\n * Internal handler signature aligned with `SplitCardForm`'s tokenized-body\n * dispatcher. Direct PayPal completes via the backend's process endpoint and\n * never produces a Stripe PaymentIntent, so we still forward a synthetic\n * `TokenizedBody` describing the captured order, optionally with the\n * session/account patch captured at click-time.\n */\nexport type DirectPayPalTokenizedHandler = (\n body: TokenizedBody,\n overrides?: DirectPayPalTokenizedOverrides,\n) => void;\n\n/** Click-time `runBeforeButtonClick` result, structurally compatible with `SplitCardForm`. */\nexport interface DirectPayPalBeforeButtonClickResult {\n proceed: boolean;\n accountPatch?: InlineSessionPatch['account'];\n sessionId?: string;\n}\n\n/**\n * Click-time gate. Mirrors `RunBeforeButtonClick` in `SplitCardForm`: lets the\n * consumer patch the session/account before PayPal creates the order, and lets\n * them abort the click entirely by returning `proceed: false`.\n */\nexport type DirectPayPalRunBeforeButtonClick = (\n method: CheckoutButtonMethod,\n) => Promise<DirectPayPalBeforeButtonClickResult>;\n\nexport interface DirectPayPalButtonProps {\n /** Checkout session ID. */\n sessionId: string;\n /** Billing API base URL. */\n billingApiUrl: string;\n /** Buyer email. */\n email?: string;\n /** PayPal client identifier (`gateways.paypal.publishableKey`). */\n clientId: string;\n /** Gateway environment, drives the sandbox/live SDK script. */\n environment?: GatewayEnvironment;\n /** ISO 4217 currency code. */\n currency: string;\n /** Whether the session is a subscription (drives intent + flow selection). */\n isSubscription: boolean;\n /**\n * If provided, called with the tokenized body once PayPal capture\n * completes. When omitted, the component processes payment internally.\n */\n onTokenizedBody?: DirectPayPalTokenizedHandler;\n /** Called when the full self-contained payment flow succeeds. */\n onComplete?: (result: PaymentResult) => void;\n /** Called when an error occurs. */\n onErrorChange?: (error: string | null) => void;\n /** Decline emitter (mirrors SplitCardForm semantics). */\n onDecline?: (decline: DeclineEvent) => void;\n /** External processing state. */\n isProcessing?: boolean;\n /** Notify the parent of the loading state for placeholder swapping. */\n onLoadStateChange?: (ready: boolean) => void;\n /** Tracks button-click for analytics. */\n onButtonClick?: (method: CheckoutButtonMethod) => void;\n /**\n * Click-time gate (runs before PayPal creates the order). When provided, the\n * returned patch is applied to the in-flight create-intent and tokenized\n * dispatch so callers using `onBeforeButtonClick` see the same session/email\n * the Stripe-rendered PayPal flow does.\n */\n runBeforeButtonClick?: DirectPayPalRunBeforeButtonClick;\n /** Backing session — used for self-contained accountData population. */\n session?: CheckoutSession | null;\n /**\n * Pre-existing PayPal Order id (or Subscription id when `isSubscription` is\n * true) to bind the button to. When set, the button skips its usual\n * `POST /v1/checkouts/payments/intents` round-trip on click and feeds this\n * id straight into PayPal's create-order / create-subscription callback.\n *\n * Used by `SplitCardForm`'s `paypal_direct_required` retry path: backend\n * creates a fresh PayPal order after a stalled process attempt and returns\n * its id; the SDK re-renders this button bound to that id so the buyer can\n * confirm with one more click without the backend re-creating the order on\n * each retry.\n *\n * Changing this value remounts the PayPal SDK so the new createOrder\n * binding takes effect (PayPal's render() options aren't live-updatable).\n */\n existingOrderId?: string;\n /**\n * When true, renders an on-screen lifecycle tracer panel above the button\n * (mount, loadScript, eligibility, render, errors). Intended for debugging\n * in-app browsers (Facebook IAB, etc.) where remote console access is\n * impractical. Off by default — leave disabled in production.\n */\n debug?: boolean;\n}\n\ninterface CreatePaypalOrderResponseData {\n /** Order ID for one-time payments. */\n id?: string;\n /** Approval URL the buyer is redirected to (in-app browser flow). */\n approveUrl?: string;\n}\n\n/**\n * Direct PayPal renderer powered by the official PayPal JS SDK.\n *\n * Renders inside Facebook / Instagram / Meta in-app browsers where Stripe's\n * PayPal ExpressCheckoutElement breaks. Selection between this and the Stripe-\n * rendered PayPal happens at the caller site based on whether the session\n * advertises `gateways.paypal.publishableKey`.\n */\nexport function DirectPayPalButton({\n sessionId,\n billingApiUrl,\n email,\n clientId,\n environment,\n currency,\n isSubscription,\n onTokenizedBody,\n onComplete,\n onErrorChange,\n onDecline,\n isProcessing = false,\n onLoadStateChange,\n onButtonClick,\n runBeforeButtonClick,\n session,\n existingOrderId,\n debug = false,\n}: DirectPayPalButtonProps): React.ReactElement | null {\n const containerRef = useRef<HTMLDivElement | null>(null);\n const [ready, setReady] = useState(false);\n // `failed` flips to true when PayPal can't load/render at all — SDK script\n // failure, ineligibility, render rejection, or a zoid lifecycle teardown.\n // It hides the loading placeholder (and the whole row) so users don't see\n // a perpetual skeleton when PayPal is unavailable.\n const [failed, setFailed] = useState(false);\n const [submitting, setSubmitting] = useState(false);\n const baseUrl = useMemo(() => billingApiUrl.replace(/\\/+$/, ''), [billingApiUrl]);\n\n // Optional on-screen lifecycle tracer, gated by the `debug` prop. Each\n // lifecycle stage appends a line. Use this for IAB debugging (Facebook,\n // Instagram, TikTok, etc.) where console access is impractical. When\n // `debug` is false the writes are no-ops, so there's no state churn or\n // memory cost in production.\n const [debugLines, setDebugLines] = useState<string[]>([]);\n const appendDebug = (line: string) => {\n if (!debug) return;\n setDebugLines((prev) => [...prev, `${new Date().toISOString().slice(11, 23)} ${line}`]);\n };\n\n // Ref-pin every callback so the render effect below can read the latest\n // handler without listing them as dependencies. Without this, an unstable\n // parent callback (e.g. an inline `onTokenizedBody={(body) => …}`) re-fires\n // the effect on every render, which tears down PayPal's buttons mid-render\n // and surfaces as \"Detected container element removed from DOM\".\n const onTokenizedBodyRef = useRef(onTokenizedBody);\n const onCompleteRef = useRef(onComplete);\n const onErrorChangeRef = useRef(onErrorChange);\n const onDeclineRef = useRef(onDecline);\n const onButtonClickRef = useRef(onButtonClick);\n const onLoadStateChangeRef = useRef(onLoadStateChange);\n const runBeforeButtonClickRef = useRef(runBeforeButtonClick);\n const sessionRef = useRef(session);\n const emailRef = useRef(email);\n // Captures the latest `runBeforeButtonClick` patch so the in-flight\n // create-intent and tokenized dispatch can use the patched sessionId/email\n // even though the PayPal SDK callbacks closed over the original props at\n // mount-time. Cleared on cancel/teardown to avoid stale patches leaking into\n // a later click.\n const beforeClickRef = useRef<{\n sessionId?: string;\n accountPatch?: InlineSessionPatch['account'];\n } | null>(null);\n useEffect(() => { onTokenizedBodyRef.current = onTokenizedBody; }, [onTokenizedBody]);\n useEffect(() => { onCompleteRef.current = onComplete; }, [onComplete]);\n useEffect(() => { onErrorChangeRef.current = onErrorChange; }, [onErrorChange]);\n useEffect(() => { onDeclineRef.current = onDecline; }, [onDecline]);\n useEffect(() => { onButtonClickRef.current = onButtonClick; }, [onButtonClick]);\n useEffect(() => { onLoadStateChangeRef.current = onLoadStateChange; }, [onLoadStateChange]);\n useEffect(() => { runBeforeButtonClickRef.current = runBeforeButtonClick; }, [runBeforeButtonClick]);\n useEffect(() => { sessionRef.current = session; }, [session]);\n useEffect(() => { emailRef.current = email; }, [email]);\n\n useEffect(() => {\n // Parent's `directPaypalReady` drives the divider visibility — keep it\n // false while we're still trying, true once PayPal is interactive, and\n // false again if we've definitively failed.\n onLoadStateChangeRef.current?.(ready && !failed);\n }, [ready, failed]);\n\n // Collapse FloPay's `stage`/`production` aliases down to the gateway-native\n // `sandbox`/`live` pair PayPal's SDK actually understands. Done up-front so\n // every downstream check (the debug trace, the loadScript options, the\n // dataNamespace branch) sees a single canonical value.\n const normalizedEnv = normalizeGatewayEnvironment(environment);\n\n useEffect(() => {\n // FloPay/DirectPayPal-debug\n const maskedClient = clientId ? `${clientId.slice(0, 6)}…(len ${clientId.length})` : '(empty)';\n const ua = typeof navigator !== 'undefined' ? navigator.userAgent : '(no navigator)';\n appendDebug(`mount clientId=${maskedClient} env=${environment ?? '(unset)'}→${normalizedEnv ?? 'live'} ccy=${currency} sub=${isSubscription}`);\n appendDebug(`ua=${ua.slice(0, 80)}${ua.length > 80 ? '…' : ''}`);\n\n if (!clientId) {\n appendDebug('FAIL: clientId empty — gateway misconfigured');\n setFailed(true);\n // Silent on-screen: PayPal row simply doesn't render. Other gateways\n // (card, wallets) stay interactive. See markRenderFailed for the same\n // policy applied to script-load/ineligibility/render failures.\n console.error('[FloPay] DirectPayPal: clientId empty — gateway misconfigured');\n return;\n }\n if (!containerRef.current) {\n appendDebug('FAIL: containerRef not attached');\n return;\n }\n\n let cancelled = false;\n // `activeButtons` is only set AFTER `render()` resolves successfully —\n // calling `buttons.close()` while zoid is still mounting the iframe\n // surfaces as \"zoid destroyed all components\" + a stuck placeholder. The\n // render `.then` handler handles the \"unmounted during render\" case\n // itself (sees `cancelled` and closes its own buttons), so cleanup only\n // needs to handle fully-mounted teardown.\n let activeButtons: { close: () => Promise<void> } | null = null;\n // Tracks whether `render()` has resolved. PayPal's `onError` fires for\n // both render-time failures (SDK script error, ineligibility, iframe\n // mount issues) AND runtime failures after the user clicks (e.g.\n // `createOrder` rejection bubbling up from the backend). Render-time\n // failures should hide the button — runtime failures must not, or the\n // user loses the ability to retry.\n let rendered = false;\n const container = containerRef.current;\n\n // Diagnostics owned by the effect so cleanup can tear them down. The\n // observer + watchdog snapshot the DOM around `buttons.render()` so we\n // can see *why* a render hangs (CAPTCHA challenge swap, zero-size parent,\n // hidden tab) — render() never resolves or rejects in those cases, so\n // the existing trace dead-ends at \"render:start\" with no further signal.\n let containerObserver: MutationObserver | null = null;\n let perfObserver: PerformanceObserver | null = null;\n const watchdogTimers: ReturnType<typeof setTimeout>[] = [];\n const formatDims = (el: Element | null): string => {\n if (!el || typeof el.getBoundingClientRect !== 'function') return '(no rect)';\n const rect = el.getBoundingClientRect();\n return `${Math.round(rect.width)}×${Math.round(rect.height)}`;\n };\n const classifyIframeSrc = (raw: string | null): string => {\n if (!raw) return '(empty)';\n try {\n const url = new URL(raw, typeof window !== 'undefined' ? window.location.href : 'https://localhost');\n const path = url.pathname.toLowerCase();\n if (path.includes('checkcaptcha') || path.includes('captcha')) return `CAPTCHA(${url.host}${path})`;\n if (path.includes('risk') || path.includes('challenge')) return `RISK(${url.host}${path})`;\n if (path.includes('smart/buttons')) return `smart-buttons(${url.host})`;\n return `${url.host}${path}`.slice(0, 100);\n } catch {\n return raw.slice(0, 80);\n }\n };\n // Describe an iframe's loaded content: zoid uses both `src` (network) and\n // `srcdoc` (inline HTML, no network roundtrip). When both are empty the\n // iframe is genuinely blank — which means zoid's content injection never\n // completed and is a strong signal of a postMessage handshake failure.\n const describeIframe = (frame: Element): string => {\n const src = frame.getAttribute('src');\n const srcdoc = frame.getAttribute('srcdoc');\n const name = frame.getAttribute('name');\n const sandbox = frame.getAttribute('sandbox');\n const parts: string[] = [];\n if (src) parts.push(`src=${classifyIframeSrc(src)}`);\n if (srcdoc) parts.push(`srcdoc[${srcdoc.length}ch]`);\n if (!src && !srcdoc) parts.push('src=(empty) srcdoc=(empty)');\n if (name) parts.push(`name=${name.slice(0, 40)}`);\n if (sandbox !== null) parts.push(`sandbox=\"${sandbox.slice(0, 40)}\"`);\n return parts.join(' ');\n };\n // Peek inside an iframe's actual rendered document. Zoid uses\n // `contentDocument.write()` for same-origin frames, which doesn't update\n // src/srcdoc attributes — so the attributes can lie. This is the\n // ground-truth: if body has children, content IS there (and the issue is\n // render() not resolving); if body is empty, zoid never wrote into it\n // (handshake failure). Cross-origin throws, which is itself useful — it\n // means PayPal navigated the frame to its own origin (network worked).\n const inspectFrameContent = (frame: Element): string => {\n if (!(frame instanceof HTMLIFrameElement)) return '';\n try {\n const cd = frame.contentDocument;\n if (!cd) return 'cd=null';\n const bodyChildren = cd.body?.children.length ?? 0;\n const bodyLen = cd.body?.innerHTML.length ?? 0;\n const headLen = cd.head?.innerHTML.length ?? 0;\n return `cd=same-origin readyState=${cd.readyState} body[${bodyChildren}children,${bodyLen}ch] head[${headLen}ch]`;\n } catch (err) {\n return `cd=cross-origin(${(err as Error).message.slice(0, 30)})`;\n }\n };\n // Capture window-scoped errors and promise rejections while the lifecycle\n // is in flight. PayPal's zoid framework swallows postMessage / storage\n // failures into the console rather than rejecting render(), so capturing\n // these is often the only way to see the real cause of a hung render.\n const errorMessages: string[] = [];\n const onWindowError = (ev: ErrorEvent) => {\n const msg = ev.message ?? String(ev.error ?? '(no message)');\n if (msg && (msg.toLowerCase().includes('paypal') || msg.toLowerCase().includes('zoid') || msg.toLowerCase().includes('postrobot') || msg.toLowerCase().includes('storage'))) {\n appendDebug(`window:error ${msg.slice(0, 140)}`);\n errorMessages.push(msg);\n }\n };\n const onUnhandledRejection = (ev: PromiseRejectionEvent) => {\n const reason = ev.reason instanceof Error ? ev.reason.message : String(ev.reason ?? '(no reason)');\n if (reason && (reason.toLowerCase().includes('paypal') || reason.toLowerCase().includes('zoid') || reason.toLowerCase().includes('postrobot') || reason.toLowerCase().includes('storage'))) {\n appendDebug(`window:rejection ${reason.slice(0, 140)}`);\n errorMessages.push(reason);\n }\n };\n if (debug && typeof window !== 'undefined') {\n window.addEventListener('error', onWindowError);\n window.addEventListener('unhandledrejection', onUnhandledRejection);\n }\n // Network telemetry: every paypal.com resource entry gets logged with\n // duration. If we see zero entries, an ad blocker / DNS filter / firewall\n // is intercepting before requests even hit the network. If we see hung\n // duration=0 entries, the request started but never completed (common\n // with privacy extensions that hold but don't reject requests).\n const paypalRequestCount = { value: 0 };\n if (debug && typeof PerformanceObserver !== 'undefined') {\n try {\n perfObserver = new PerformanceObserver((list) => {\n for (const entry of list.getEntries()) {\n if (!entry.name.toLowerCase().includes('paypal')) continue;\n paypalRequestCount.value += 1;\n const dur = Math.round(entry.duration);\n appendDebug(`net ${dur}ms ${entry.name.slice(0, 90)}`);\n }\n });\n perfObserver.observe({ type: 'resource', buffered: true });\n } catch {\n // Older browsers may not support PerformanceObserver with type/buffered\n // syntax — fail silently, the other diagnostics still work.\n }\n }\n const stopDiagnostics = () => {\n containerObserver?.disconnect();\n containerObserver = null;\n perfObserver?.disconnect();\n perfObserver = null;\n while (watchdogTimers.length) clearTimeout(watchdogTimers.pop()!);\n if (debug && typeof window !== 'undefined') {\n window.removeEventListener('error', onWindowError);\n window.removeEventListener('unhandledrejection', onUnhandledRejection);\n }\n };\n\n /**\n * Zoid (PayPal's iframe framework) emits \"zoid destroyed all components\"\n * and similar lifecycle messages through `onError` whenever its\n * components are torn down — page navigation, force reload, React 18\n * StrictMode dev mount/unmount, or a parent unmounting mid-render.\n * Those events aren't payment errors; surfacing them in our error\n * banner misleads users and blocks them from completing checkout.\n */\n const isZoidLifecycleMessage = (message: string | undefined): boolean => {\n if (!message) return false;\n const lower = message.toLowerCase();\n return lower.includes('zoid destroyed')\n || lower.includes('destroyed all components')\n || lower.includes('window closed')\n || lower.includes('detected container element removed');\n };\n\n const forwardError = (message: string) => {\n if (cancelled) return;\n if (isZoidLifecycleMessage(message)) return;\n const friendly = applyFriendlyMessageOverride(message) ?? message;\n onErrorChangeRef.current?.(friendly);\n };\n\n /**\n * Used by load/render-time error paths: hides the placeholder (and the\n * whole row) so users don't stare at a perpetual skeleton when PayPal\n * can't load. Logs to console for diagnostics but never calls\n * `onErrorChange` — pre-render failures (script load 400, ineligibility,\n * render rejection) would otherwise paint a checkout-blocking red banner\n * even though card / wallet / other gateways remain usable. The row\n * silently collapses; the parent's `directPaypalReady` stays false.\n *\n * Zoid lifecycle messages (e.g. \"zoid destroyed all components\") fire\n * during mount/unmount churn — most commonly React StrictMode's\n * mount → cleanup → mount cycle in dev. On iOS Facebook IAB the surviving\n * mount's render rejects with this message even though nothing is wrong,\n * because WKWebView's iframe init races the rapid cycle. Treat these as\n * transient: don't flip `failed = true` (which would permanently hide the\n * button) — the deferred-load guard above prevents the double-load that\n * triggered this in the first place, so a fresh attempt should succeed.\n */\n const markRenderFailed = (message: string) => {\n if (cancelled) return;\n if (isZoidLifecycleMessage(message)) {\n appendDebug(`markRenderFailed:skip-zoid msg=${message.slice(0, 80)}`);\n return;\n }\n setFailed(true);\n console.error('[FloPay] DirectPayPal load/render failure:', message);\n };\n\n // Reset failure state at the start of every effect run so a config\n // change (clientId/environment/sessionId/currency etc.) re-attempts the\n // render cleanly rather than inheriting a sticky failure from the\n // previous configuration.\n setFailed(false);\n\n const dispatchTokenizedBody = async (body: TokenizedBody) => {\n const prepared = beforeClickRef.current;\n const effectiveSessionId = prepared?.sessionId ?? sessionId;\n if (onTokenizedBodyRef.current) {\n onTokenizedBodyRef.current(body, {\n sessionId: effectiveSessionId,\n accountPatch: prepared?.accountPatch,\n });\n return;\n }\n try {\n const currentSession = sessionRef.current;\n const currentEmail = prepared?.accountPatch?.email ?? emailRef.current;\n const effectiveUserId = prepared?.accountPatch?.userId\n ?? currentSession?.customer?.id\n ?? currentSession?.accountData?.userId\n ?? '';\n const api = new PaymentAPI(baseUrl);\n const response = await api.processPayment(\n effectiveUserId,\n {\n sessionId: effectiveSessionId,\n tokenizedData: body,\n accountData: {\n userId: effectiveUserId,\n email: currentEmail ?? currentSession?.customer?.email ?? '',\n firstName: prepared?.accountPatch?.firstName\n ?? currentSession?.customer?.firstName\n ?? currentSession?.accountData?.firstName\n ?? '',\n lastName: prepared?.accountPatch?.lastName\n ?? currentSession?.customer?.lastName\n ?? currentSession?.accountData?.lastName\n ?? '',\n country: prepared?.accountPatch?.country\n ?? currentSession?.customer?.country\n ?? currentSession?.accountData?.country\n ?? undefined,\n zip: prepared?.accountPatch?.zip\n ?? currentSession?.customer?.zip\n ?? currentSession?.accountData?.zip\n ?? undefined,\n },\n },\n );\n\n if (response.ok) {\n onCompleteRef.current?.({ status: 'succeeded', checkoutMethod: 'paypal' });\n return;\n }\n\n const json = (await response.json().catch(() => null)) as Record<string, unknown> | null;\n const rawMessage = (json?.['message'] as string | undefined) ?? 'PayPal payment failed.';\n const message = applyFriendlyMessageOverride(rawMessage) ?? rawMessage;\n forwardError(message);\n onDeclineRef.current?.(buildDeclineEvent('paypal', message, {\n code: json?.['code'] as string | undefined,\n declineCode: json?.['declineCode'] as string | undefined,\n }));\n } catch (err) {\n const rawMessage = err instanceof Error ? err.message : 'PayPal payment failed.';\n const message = applyFriendlyMessageOverride(rawMessage) ?? rawMessage;\n forwardError(message);\n onDeclineRef.current?.(buildDeclineEvent('paypal', message));\n }\n };\n\n const createPaypalIntent = async (fallbackMessage: string): Promise<string> => {\n const prepared = beforeClickRef.current;\n const effectiveSessionId = prepared?.sessionId ?? sessionId;\n const effectiveEmail = prepared?.accountPatch?.email ?? emailRef.current;\n // isPaypal must be string 'true' — backend checks === 'true'.\n const response = 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: 'paypal',\n isPaypal: 'true',\n }),\n });\n const json = (await response.json().catch(() => null)) as\n | { data?: CreatePaypalOrderResponseData; message?: string }\n | null;\n if (!response.ok) {\n throw new Error(json?.message ?? fallbackMessage);\n }\n const id = json?.data?.id;\n if (!id) {\n throw new Error(fallbackMessage);\n }\n return id;\n };\n\n // Defer the PayPal lifecycle by one macrotask so any rapid mount → cleanup\n // → mount cycle (React StrictMode in dev, or a parent that briefly mounts\n // us before late-arriving props like `email` cause it to re-render) has\n // finished before we touch PayPal's SDK. Without this, both the dead and\n // surviving mounts call `loadScript` in the same tick; on iOS Facebook\n // IAB the surviving mount's `render()` then rejects with \"zoid destroyed\n // all components\" because zoid's iframe init races the synchronous\n // teardown. clearTimeout in the cleanup ensures the dead mount never even\n // starts the load.\n appendDebug('loadScript:scheduled (deferred 1 tick)');\n let loadPromise: Promise<PayPalNamespace | null> | null = null;\n const startTimer = setTimeout(() => {\n if (cancelled) {\n appendDebug('loadScript:skipped (cancelled before defer ran)');\n return;\n }\n appendDebug('loadScript:start');\n // PayPal SDK uses `'production'` (not `'live'`) for prod mode, so\n // re-map after our internal normalize step.\n const paypalSdkEnv: 'sandbox' | 'production' | undefined =\n normalizedEnv === 'live' ? 'production' : normalizedEnv;\n loadPromise = loadScript({\n clientId,\n currency,\n // Subscriptions need the `subscription` vault intent; one-time payments\n // use a standard order capture.\n intent: isSubscription ? 'subscription' : 'capture',\n vault: isSubscription ? true : undefined,\n // Tell PayPal which environment the clientId belongs to. Without\n // this, PayPal defaults to live endpoints — and a sandbox clientId\n // sent to live silently stalls in zoid's prerender forever (no\n // error, no rejection).\n ...(paypalSdkEnv ? { environment: paypalSdkEnv } : {}),\n // Namespace the sandbox SDK so it can coexist with a production SDK on\n // the same page without clobbering `window.paypal`.\n ...(paypalSdkEnv === 'sandbox' ? { dataNamespace: 'paypal_sandbox' } : {}),\n });\n loadPromise\n .then((paypal) => {\n appendDebug(`loadScript:resolved cancelled=${cancelled} ns=${!!paypal} buttons=${!!paypal?.Buttons}`);\n if (cancelled || !paypal?.Buttons) {\n if (!cancelled && !paypal?.Buttons) appendDebug('FAIL: namespace missing Buttons factory');\n return;\n }\n\n const handleApprove = async (data: { orderID?: string; subscriptionID?: string }) => {\n try {\n setSubmitting(true);\n onErrorChangeRef.current?.(null);\n const token = data.subscriptionID ?? data.orderID ?? '';\n if (!token) {\n throw new FloPayError(\n 'PayPal did not return an approval token.',\n 'api_error',\n { code: 'paypal_missing_token' },\n );\n }\n await dispatchTokenizedBody({\n id: token,\n isPaypal: true,\n });\n } catch (err) {\n forwardError(err instanceof Error ? err.message : 'PayPal capture failed.');\n } finally {\n setSubmitting(false);\n }\n };\n\n const buttons = paypal.Buttons!({\n style: { layout: 'horizontal', height: DEFAULT_BUTTON_HEIGHT, tagline: false },\n // PayPal's SDK awaits a Promise returned from `onClick` and aborts\n // the create-order/create-subscription step when `actions.reject()`\n // is invoked. Run the consumer's `runBeforeButtonClick` here so\n // inline-session/account patches land before the order is created,\n // matching the Stripe-rendered PayPal flow.\n onClick: async (_data: unknown, actions: { resolve: () => Promise<void>; reject: () => Promise<void> }) => {\n const runner = runBeforeButtonClickRef.current;\n if (runner) {\n try {\n const beforeClick = await runner('paypal');\n if (!beforeClick.proceed) {\n beforeClickRef.current = null;\n await actions.reject();\n return;\n }\n beforeClickRef.current = {\n sessionId: beforeClick.sessionId,\n accountPatch: beforeClick.accountPatch,\n };\n } catch (err) {\n appendDebug(`onClick:runBeforeButtonClick rejected msg=${(err instanceof Error ? err.message : String(err)).slice(0, 120)}`);\n beforeClickRef.current = null;\n await actions.reject();\n return;\n }\n } else {\n beforeClickRef.current = null;\n }\n onButtonClickRef.current?.('paypal');\n await actions.resolve();\n },\n // When the SDK is already holding an order/subscription id from a\n // prior backend round-trip (the `paypal_direct_required` retry\n // path), feed it straight to PayPal instead of creating a new one.\n // Otherwise fall back to the normal create-intent call.\n createOrder: isSubscription\n ? undefined\n : existingOrderId\n ? () => Promise.resolve(existingOrderId)\n : () => createPaypalIntent('Failed to create PayPal order.'),\n createSubscription: isSubscription\n ? existingOrderId\n ? () => Promise.resolve(existingOrderId)\n : () => createPaypalIntent('Failed to create PayPal subscription.')\n : undefined,\n onApprove: handleApprove,\n onCancel: () => {\n beforeClickRef.current = null;\n onDeclineRef.current?.(buildDeclineEvent('paypal', 'PayPal checkout was cancelled.'));\n },\n onError: (err) => {\n const message = err instanceof Error ? err.message : 'PayPal failed to render.';\n appendDebug(`onError rendered=${rendered} msg=${message.slice(0, 120)}`);\n // Post-render: a runtime failure (e.g. backend rejected the\n // create-order/subscription call) — keep the button visible so\n // the user can retry, and surface the error to the consumer.\n if (rendered) {\n forwardError(message);\n onDeclineRef.current?.(buildDeclineEvent('paypal', message));\n return;\n }\n // Pre-render: actual render-time issue or zoid teardown; mark\n // failed so we hide the placeholder. `markRenderFailed` filters\n // zoid lifecycle messages out of the forwarded error so the\n // consumer doesn't see noise.\n markRenderFailed(message);\n },\n } as Parameters<NonNullable<typeof paypal.Buttons>>[0]);\n\n const eligible = buttons.isEligible();\n appendDebug(`isEligible=${eligible}`);\n if (!eligible) {\n setReady(false);\n markRenderFailed(\n 'PayPal buttons are not eligible to render in this context (paypal_ineligible).',\n );\n return;\n }\n\n const typedButtons = buttons as { close: () => Promise<void> };\n\n // Pre-render container snapshot. A 0-width parent (flex column\n // collapse, display:none ancestor, etc.) is a common silent failure:\n // PayPal renders happily into a zero-size box and the user sees\n // nothing. Logging dims here catches that before render starts.\n if (debug) {\n appendDebug(`container:dims ${formatDims(container)} visibility=${typeof document !== 'undefined' ? document.visibilityState : '(no document)'}`);\n }\n\n // MutationObserver: log every PayPal injection AND every attribute\n // change. Zoid creates iframes with empty src/srcdoc first and then\n // sets the content attribute asynchronously — without `attributes:\n // true` we'd never see when (or whether) the content load actually\n // happens. The iframe's title=PayPal first appears as a childList\n // mutation; `src`/`srcdoc` then appears as an attribute mutation.\n if (debug && typeof MutationObserver !== 'undefined') {\n containerObserver = new MutationObserver((mutations) => {\n for (const mutation of mutations) {\n if (mutation.type === 'childList') {\n mutation.addedNodes.forEach((node) => {\n if (!(node instanceof Element)) return;\n const tag = node.tagName.toLowerCase();\n const title = (node.getAttribute('title') ?? '').slice(0, 40);\n const detail = tag === 'iframe' ? ` ${describeIframe(node)}` : '';\n appendDebug(`child+ ${tag}${title ? ` title=\"${title}\"` : ''}${detail} dims=${formatDims(node)}`);\n });\n } else if (mutation.type === 'attributes' && mutation.target instanceof Element) {\n const target = mutation.target;\n if (target.tagName.toLowerCase() !== 'iframe') continue;\n const attr = mutation.attributeName;\n if (attr === 'src' || attr === 'srcdoc') {\n appendDebug(`attr~ iframe ${attr}=${attr === 'srcdoc' ? `[${(target.getAttribute('srcdoc') ?? '').length}ch]` : classifyIframeSrc(target.getAttribute('src'))} dims=${formatDims(target)}`);\n }\n }\n }\n });\n containerObserver.observe(container, {\n childList: true,\n subtree: true,\n attributes: true,\n attributeFilter: ['src', 'srcdoc'],\n });\n }\n\n // Render watchdog. Snapshots the container + iframes at 3s/8s/15s\n // if render() hasn't resolved. Uses describeIframe so we see src,\n // srcdoc length, name (zoid uses iframe names for postMessage\n // routing), and sandbox attribute — enough to distinguish \"iframe\n // shell exists but content never loaded\" (postMessage/storage\n // failure) from \"iframe loaded but render() didn't fire\" (PayPal\n // SDK internal bug or unmounted parent).\n const snapshotContainer = (when: string) => {\n if (cancelled || rendered) return;\n const iframes = container.querySelectorAll('iframe');\n const hasStorageAccess = typeof document !== 'undefined' && 'hasStorageAccess' in document;\n appendDebug(`watchdog:${when} container=${formatDims(container)} children=${container.childElementCount} iframes=${iframes.length} visibility=${typeof document !== 'undefined' ? document.visibilityState : '(no document)'} cookies=${typeof navigator !== 'undefined' ? navigator.cookieEnabled : '?'} hasStorageAccessApi=${hasStorageAccess} paypalNetRequests=${paypalRequestCount.value}`);\n iframes.forEach((frame, i) => {\n const title = (frame.getAttribute('title') ?? '').slice(0, 40);\n appendDebug(` iframe[${i}] ${formatDims(frame)}${title ? ` title=\"${title}\"` : ''} ${describeIframe(frame)}`);\n const content = inspectFrameContent(frame);\n if (content) appendDebug(` ${content}`);\n });\n if (errorMessages.length === 0) {\n appendDebug(` (no PayPal/zoid window errors captured)`);\n }\n };\n if (debug) {\n watchdogTimers.push(setTimeout(() => snapshotContainer('3s'), 3000));\n watchdogTimers.push(setTimeout(() => snapshotContainer('8s'), 8000));\n watchdogTimers.push(setTimeout(() => snapshotContainer('15s'), 15000));\n }\n\n appendDebug('render:start');\n buttons.render(container).then(() => {\n appendDebug(`render:resolved cancelled=${cancelled}`);\n stopDiagnostics();\n if (cancelled) {\n // Component unmounted while render was in flight — render is now\n // complete, so close gracefully here instead of from cleanup\n // (cleanup couldn't see `activeButtons` yet at the time it ran).\n typedButtons.close().catch(() => {});\n return;\n }\n activeButtons = typedButtons;\n rendered = true;\n setReady(true);\n }).catch((err: unknown) => {\n const message = err instanceof Error ? err.message : 'PayPal failed to render.';\n appendDebug(`render:rejected msg=${message.slice(0, 120)}`);\n stopDiagnostics();\n markRenderFailed(message);\n });\n })\n .catch((err: unknown) => {\n const message = err instanceof Error ? err.message : 'PayPal SDK failed to load.';\n appendDebug(`loadScript:rejected msg=${message.slice(0, 120)}`);\n markRenderFailed(message);\n });\n }, 0);\n\n return () => {\n cancelled = true;\n // If the deferred load never fired (e.g. StrictMode's synchronous\n // cleanup), clearTimeout prevents the dead mount from ever calling\n // loadScript. The surviving mount's deferred timer runs next tick and\n // owns the lifecycle alone.\n clearTimeout(startTimer);\n stopDiagnostics();\n // Prefer PayPal's graceful teardown over `container.innerHTML = ''`,\n // which races the SDK's async `render()` and triggers\n // \"Detected container element removed from DOM\".\n if (activeButtons) {\n activeButtons.close().catch(() => {});\n }\n };\n }, [baseUrl, clientId, currency, environment, isSubscription, sessionId, existingOrderId]);\n\n // On-screen lifecycle tracer, only rendered when `debug` is true.\n const debugPanel = debug ? (\n <pre\n data-testid=\"flopay-direct-paypal-debug\"\n style={{\n margin: '0 0 8px 0',\n padding: '6px 8px',\n background: failed ? '#fef2f2' : '#f3f4f6',\n border: `1px solid ${failed ? '#fca5a5' : '#d1d5db'}`,\n borderRadius: 6,\n color: '#111827',\n font: '11px/1.35 ui-monospace, SFMono-Regular, Menlo, monospace',\n whiteSpace: 'pre-wrap',\n wordBreak: 'break-word',\n maxHeight: 220,\n overflowY: 'auto',\n }}\n >\n {`FloPay/DirectPayPal-debug (ready=${ready} failed=${failed})`}\n {debugLines.length === 0 ? '\\n(waiting for first lifecycle event…)' : `\\n${debugLines.join('\\n')}`}\n </pre>\n ) : null;\n\n // If PayPal can't load/render at all, render nothing in production, or only\n // the diagnostic panel when `debug` is on (so the failure mode stays visible\n // on screen).\n if (failed) {\n return debug ? <div>{debugPanel}</div> : null;\n }\n\n return (\n // Single wrapper so the parent flex container sees exactly one flex item\n // (otherwise the fragment's placeholder + container become two siblings\n // and any spacing-sensitive layout has to reason about both). The wrapper\n // intentionally has no margin/padding so the parent owns all spacing.\n <div>\n {debugPanel}\n {/*\n Stacking context: the container must stay in the layout flow with\n non-zero dimensions for PayPal's zoid framework to mount its iframes —\n a `display: none` parent leaves the iframe 0×0 and `render()` never\n resolves. The placeholder absolutely-positions over the container so\n the user sees a skeleton until PayPal's button is interactive.\n */}\n <div style={{ position: 'relative', minHeight: DEFAULT_BUTTON_HEIGHT }}>\n {!ready && (\n <div\n data-testid=\"flopay-direct-paypal-placeholder\"\n style={{\n position: 'absolute',\n inset: 0,\n borderRadius: 8,\n background: '#e5e7eb',\n animation: 'flopay-pulse 1.5s ease-in-out infinite',\n pointerEvents: 'none',\n }}\n />\n )}\n <div\n ref={containerRef}\n data-testid=\"flopay-direct-paypal-container\"\n // `display: flex` makes PayPal's injected `.paypal-buttons` a flex\n // child instead of an inline-block. That kills the baseline descender\n // space that would otherwise read as a phantom margin below the\n // button (looking like a doubled flex `gap` in the parent column).\n // `opacity: 0` (not `display: none`) keeps the container measurable\n // so PayPal can render into it before `ready` flips true.\n style={{\n minHeight: DEFAULT_BUTTON_HEIGHT,\n display: 'flex',\n opacity: ready ? 1 : 0,\n }}\n aria-busy={submitting || isProcessing}\n />\n </div>\n </div>\n );\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 applyFriendlyMessageOverride,\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 const rawMessage = error?.message ?? fallbackMessage;\n const message = applyFriendlyMessageOverride(rawMessage) ?? rawMessage;\n\n return Object.assign(\n new FloPayError(\n message,\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 nestedGateways = nestedRecord.gateways;\n if (nestedGateways && typeof nestedGateways === 'object') {\n const stripeGateway = (nestedGateways as Record<string, unknown>).stripe;\n if (stripeGateway && typeof stripeGateway === 'object') {\n const stripeRecord = stripeGateway as Record<string, unknown>;\n const gatewayCandidates = [\n stripeRecord.stripeClientSecret,\n stripeRecord.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\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.data.stripe?.clientSecret;\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 const friendly = applyFriendlyMessageOverride(err.message);\n if (friendly && friendly !== err.message) {\n return Object.assign(\n new FloPayError(friendly, err.type, {\n code: err.code,\n declineCode: err.declineCode,\n param: err.param,\n statusCode: err.statusCode,\n }),\n { checkoutMethod: (err as SavedPaymentFlowError).checkoutMethod },\n ) as SavedPaymentFlowError;\n }\n return err as SavedPaymentFlowError;\n }\n\n const rawMessage = err instanceof Error ? err.message : 'Payment failed. Please try again.';\n const message = applyFriendlyMessageOverride(rawMessage) ?? rawMessage;\n\n return new FloPayError(message, 'api_error') as SavedPaymentFlowError;\n}\n\n/**\n * Stripe Elements publishable keys resolved from a normalized session. The\n * \"PayPal\" entry here refers to the legacy Stripe-rendered PayPal account\n * (`gateways.stripe`'s dedicated PayPal sub-account), not the new direct\n * PayPal gateway — direct PayPal lives in `gateways.paypal` and is rendered\n * via the official PayPal JS SDK rather than through Stripe Elements.\n *\n * For PayPal-only sessions (`gateways.paypal` set, no `gateways.stripe`),\n * `publishableKey` is `undefined` and the caller should skip Stripe Elements\n * entirely. Only throws when the session advertises no supported gateway at\n * all.\n */\nexport function resolveSavedPaymentPublishableKeys(\n unified: NormalizedCheckoutSession,\n): {\n publishableKey?: string;\n paypalPublishableKey?: string;\n} {\n const publishableKey = unified.data.stripe?.publishableKey;\n const hasDirectPaypal = Boolean(unified.data.paypal?.publishableKey);\n\n if (!publishableKey && !hasDirectPaypal) {\n throw new FloPayError(\n 'Session advertises no supported gateways (expected `gateways.stripe` and/or `gateways.paypal`).',\n 'validation_error',\n );\n }\n\n if (!publishableKey) {\n // Direct-PayPal-only session: no Stripe Elements at all.\n return {};\n }\n\n return {\n publishableKey,\n // Direct-PayPal sessions can still use Stripe's PayPal Element for the\n // saved-PM redirect leg. Prefer the dedicated Stripe-PayPal sub-account\n // publishable key when the backend advertises one; fall back to the\n // primary Stripe publishable key so the resume flow still has a Stripe\n // instance to drive Stripe's PayPal PI.\n paypalPublishableKey: unified.data.stripe?.paypalPublishableKey ?? publishableKey,\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 | null;\n paypalFlopay: FloPay | null;\n}> {\n if (!publishableKey) {\n // PayPal-only session: no Stripe Elements instance to load. The\n // saved-PM Stripe-PayPal resume leg isn't available, but direct PayPal\n // doesn't need it.\n return { flopay: null, paypalFlopay: null };\n }\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 Stripe-rendered PayPal path. Routes\n // confirmation through the PayPal FloPay instance (falls back to the\n // primary Stripe instance when no dedicated PayPal sub-account is\n // configured).\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 ThemeId,\n} from '@flopay/shared';\nimport type {\n ButtonsLayoutStyles,\n ButtonsLayoutTheme,\n CheckoutItem,\n CheckoutProduct,\n CheckoutSubscription,\n} from '@flopay/shared';\nimport { FloPayError, resolveBillingApiUrl, resolveButtonsLayoutTheme, resolveTheme } from '@flopay/shared';\nimport { CardButtonContentSlot } from './card-button-content.js';\nimport { buildDeclineEvent } from './checkout-utils.js';\nimport { FloPayCheckout } from './flopay-checkout.js';\nimport { derivePrimaryTileStyle } from './split-card-form.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 normalizeSavedPaymentError,\n processSavedPaymentForMode,\n} from './saved-payment-flow.js';\n\nconst DEFAULT_BUTTONS_LAYOUT_BUTTON_HEIGHT = 44;\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 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\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 /**\n * @deprecated Ignored. The backend now picks the customer's most recent\n * vaulted payment method via `getLatestByUserId` and rebinds the session's\n * gateway to match it (see `apps/api`'s `createSingle` auto-checkout\n * branch). Passing this prop has no effect — it is retained only to avoid\n * breaking existing integrations.\n */\n paymentMethodId?: string;\n /**\n * @deprecated Ignored. The backend orchestrates gateway routing — clients\n * no longer choose between card and PayPal at the SDK boundary. Passing\n * this prop has no effect.\n */\n checkoutMethod?: CheckoutButtonMethod;\n clientId?: string;\n /**\n * Unified products array (TeamFloPay/backend#760). When supplied,\n * `items`/`subscriptions` are ignored. The SDK folds the legacy fields\n * into this shape internally.\n */\n products?: CheckoutProduct[];\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 /**\n * High-level theme bundle that styles the button (and the fallback\n * `FloPayCheckout` modal that opens when the saved-payment charge needs\n * user interaction). One of: `'classic'`, `'modern-light'`, `'modern-dark'`,\n * `'bold-light'`, `'bold-dark'`, `'glass-light'`, `'glass-dark'`. Explicit\n * `buttonsStyles` still wins for fine-grained overrides.\n */\n theme?: ThemeId;\n /**\n * @deprecated Use `theme` instead. Legacy buttons-layout preset\n * (`'default' | 'minimal' | 'rounded' | 'dark'`). Still honored for\n * back-compat.\n */\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 // Enforce the documented precedence: when `products` is supplied the legacy\n // `items`/`subscriptions` are dropped so the draft can't carry an ambiguous\n // cart. `createAndFetchSession` folds the legacy fields into `products[]`\n // only when `products` is absent (`params.products ?? foldIntoProducts(...)`).\n // Use `!= null` so `products={null}` is treated as absent too, matching the\n // `??` semantics downstream — otherwise the legacy fields would be dropped\n // here but `null ?? foldIntoProducts(undefined, undefined)` would yield `[]`.\n const hasProducts = props.products != null;\n\n return {\n clientId: props.clientId,\n products: props.products,\n items: hasProducts ? undefined : props.items,\n subscriptions: hasProducts ? undefined : 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 // Deprecated — accepted for back-compat and silently ignored. Backend\n // resolves the customer's latest payment method server-side.\n paymentMethodId: _deprecatedPaymentMethodId,\n checkoutMethod: _deprecatedCheckoutMethod,\n clientId,\n products,\n items,\n subscriptions,\n account,\n successUrl,\n cancelUrl,\n couponCodes,\n tagsData,\n utmMetadata,\n billingApiUrl,\n locale,\n theme,\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 products,\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 products,\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\n const isMountedRef = useRef(true);\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 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: { status: 'succeeded' },\n session: completedSession,\n sessionId: completedSession.id || resolvedSessionId,\n autoCompleted: false,\n });\n return;\n }\n\n if (apiResult.autoProcessingError) {\n throw checkoutProcessErrorToFloPayError(\n apiResult.autoProcessingError,\n 'Automatic payment failed. Please try again.',\n {\n checkoutMethod: apiResult.autoProcessingError.checkoutMethod,\n },\n );\n }\n\n if (options?.fromCreateSession && apiResult.autoProcessingAttempted === true) {\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 }\n\n // Existing-session path: backend's `createSingle` auto-checkout did not\n // run, so kick off /process. The SDK no longer ships client-built\n // `tokenizedData` — the backend resolves the customer's latest vaulted\n // payment method server-side (see `apps/api`'s `process` /\n // `processPendingSession` for the orchestration that owns this now).\n const result = await processSavedPaymentForMode({\n billingApiUrl: resolvedBillingUrl,\n sessionId: resolvedSessionId ?? session.id,\n session,\n });\n\n if (result.type !== 'success') {\n // The backend should not be requesting a client-side redirect when it\n // owns gateway routing. Anything other than `success` is treated as a\n // failure and falls through to the standard error path (fallback\n // checkout for recoverable cases).\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 }\n\n await showSuccess({\n result: result.result,\n session,\n sessionId: session.id || resolvedSessionId,\n autoCompleted: false,\n });\n } catch (err) {\n const floPayErr = normalizeSavedPaymentError(err);\n const fallbackSessionId = session.id || resolvedSessionId;\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 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 });\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 // Resolution: `theme` (high-level bundle) takes precedence over the legacy\n // `buttonsTheme` preset; explicit `buttonsStyles` overrides individual fields\n // on top of whichever base was chosen.\n const themeBundle = useMemo(() => resolveTheme(theme), [theme]);\n const bStyles = useMemo<ButtonsLayoutStyles>(() => {\n const base = themeBundle?.buttonsLayout ?? resolveButtonsLayoutTheme(buttonsTheme);\n if (!stylesOverride) return base;\n return {\n ...base,\n ...stylesOverride,\n cardButton: { ...base.cardButton, ...stylesOverride.cardButton },\n };\n }, [themeBundle, 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 // `bStyles.cardButton` first so the bundle's padding / typography\n // / radius / shadow come through, then `derivePrimaryTileStyle`\n // on top so the auto-pay button carries the *submit* button's\n // background and text colours — making it visually identical to\n // the \"Confirm Payment\" / \"Pay with X\" actions it stands in for.\n // Inline `style` consumer override stays at the end so explicit\n // per-button overrides still win.\n ...bStyles.cardButton as React.CSSProperties,\n ...derivePrimaryTileStyle({\n themeBundle,\n resolvedPrimaryColor:\n (themeBundle?.appearance.variables?.colorPrimary as string | undefined) ?? '#4A49FF',\n resolvedBorderRadius:\n (themeBundle?.appearance.variables?.borderRadius as string | undefined) ?? '8px',\n submitButtonStyle: bStyles.submitButton as React.CSSProperties | undefined,\n }),\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 transition: 'border-color 0.2s, box-shadow 0.2s, transform 0.1s',\n position: 'relative',\n opacity: disabled || isProcessing ? 0.6 : 1,\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 locale={locale}\n theme={theme}\n buttonsTheme={buttonsTheme}\n buttonsStyles={stylesOverride}\n initialErrorMessage={fallbackSession.errorMessage}\n cardTitleContent={null}\n onComplete={handleFallbackComplete}\n onError={handleFallbackError}\n onDecline={handleFallbackDecline}\n />\n </div>\n </div>\n )}\n </>\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,IAAAA,gBAAoD;AAGpD,oBAAqC;;;ACHrC,mBAA8B;AAsCvB,IAAM,oBAAgB,4BAAkC;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;AAAA,QACC,QAAQ;AAAA,QACR,cAAc;AAAA;AAAA,IAChB;AAAA,IAED,mBACC;AAAA,MAAC;AAAA;AAAA,QACC,eAAY;AAAA,QACZ,MAAK;AAAA,QACL,cAAW;AAAA,QACX,SAAS,CAAC,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;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;AAAA,cAAC;AAAA;AAAA,gBACC,WAAW,gBAAgB;AAAA,gBAC3B,cAAa;AAAA,gBACb,eAAe;AAAA,gBACf;AAAA,gBACA;AAAA,gBACA;AAAA,gBACA,eAAe;AAAA,gBACf,qBAAqB,gBAAgB;AAAA,gBACrC,kBAAkB;AAAA,gBAClB,YAAY;AAAA,gBACZ,SAAS;AAAA,gBACT,WAAW;AAAA;AAAA,YACb;AAAA;AAAA,QACF;AAAA;AAAA,IACF;AAAA,KAEJ;AAEJ;","names":["import_react","import_react","import_js","import_shared","import_react","import_jsx_runtime","import_react","import_jsx_runtime","import_shared","import_js","import_react","import_react","import_shared","import_react","import_jsx_runtime","import_shared","import_react","import_shared","import_jsx_runtime","import_shared","import_jsx_runtime","SplitCardForm","useStripeRaw","useStripeElements","React","StripeElements","stateValue","message","error","import_js","import_shared","error","import_jsx_runtime","DEFAULT_BUTTONS_LAYOUT_BUTTON_HEIGHT","activeSessionId","React","import_js","import_shared","import_react","import_jsx_runtime","CheckoutForm","error","import_js","import_shared","import_react","import_jsx_runtime","import_react","import_js","import_shared","import_jsx_runtime","DEFAULT_BUTTONS_LAYOUT_BUTTON_HEIGHT","sleep"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../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/direct-paypal-button.tsx","../src/saved-payment-flow.ts","../src/checkout-form.tsx","../src/paypal-button.tsx","../src/automatic-payment-button.tsx"],"sourcesContent":["// Provider\nexport { FloPayProvider } from './provider.js';\nexport type { FloPayProviderProps } from './provider.js';\n\n// FloPayCheckout (recommended — all-in-one checkout)\nexport { FloPayCheckout } from './flopay-checkout.js';\nexport type { FloPayCheckoutProps } from './flopay-checkout.js';\nexport type {\n BeforeButtonClickEvent,\n CheckoutButtonMethod,\n DeclineEvent,\n InlineSessionDraft,\n InlineSessionPatch,\n} from '@flopay/shared';\n\n// Hooks\nexport { useFloPay, usePayPalFloPay, useElements, useCheckout } from './hooks.js';\nexport type { CheckoutState } from './hooks.js';\n\n// Element Components\nexport {\n PaymentElement,\n CardElement,\n CardNumberElement,\n CardExpiryElement,\n CardCvcElement,\n AddressElement,\n} from './elements.js';\nexport type { ElementComponentProps } from './elements.js';\n\n// CheckoutForm\nexport { CheckoutForm } from './checkout-form.js';\nexport type { CheckoutFormProps, CheckoutFormRef } from './checkout-form.js';\n\n// SplitCardForm\nexport { SplitCardForm } from './split-card-form.js';\nexport type { SplitCardFormProps, SplitCardFormRef } from './split-card-form.js';\n\n// PayPalButton (Stripe-rendered fallback)\nexport { PayPalButton } from './paypal-button.js';\nexport type { PayPalButtonProps } from './paypal-button.js';\n\n// DirectPayPalButton (PayPal JS SDK — in-app browser compatible)\nexport { DirectPayPalButton } from './direct-paypal-button.js';\nexport type { DirectPayPalButtonProps } from './direct-paypal-button.js';\n\n// FloPayAutomaticPaymentButton\nexport { FloPayAutomaticPaymentButton } from './automatic-payment-button.js';\nexport type {\n FloPayAutomaticPaymentButtonProps,\n FloPayAutomaticPaymentSuccessEvent,\n} from './automatic-payment-button.js';\n","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 Stripe `FloPay` instance used to drive the Stripe-rendered PayPal\n * fallback. When omitted or `null`, the Stripe-rendered PayPal button is\n * not rendered. Direct PayPal (`gateways.paypal`) does not use this prop.\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 * Stripe FloPay instance used for the Stripe-rendered PayPal fallback. When\n * direct PayPal (`gateways.paypal`) is configured this isn't used for\n * rendering — DirectPayPalButton talks to PayPal directly — but the\n * Stripe-PayPal saved-PM redirect leg still relies on it.\n * `null` or absent means the Stripe-rendered PayPal fallback is unavailable.\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, resolveTheme } 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 { DirectPayPalButton } from './direct-paypal-button.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\ninterface DirectPayPalConfig {\n clientId: string;\n environment?: import('@flopay/shared').GatewayEnvironment;\n}\n\nfunction resolveDirectPaypalConfig(\n unified: NormalizedCheckoutSession | null,\n): DirectPayPalConfig | undefined {\n const clientId = unified?.data.paypal?.publishableKey;\n if (!clientId) return undefined;\n return {\n clientId,\n environment: unified?.data.paypal?.environment,\n };\n}\n\nfunction isPayPalOnlyUnified(unified: NormalizedCheckoutSession | null): boolean {\n if (!unified) return false;\n if (unified.data.stripe?.publishableKey) return false;\n return Boolean(resolveDirectPaypalConfig(unified)?.clientId);\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 * Session-bound checkout token (the `nonce` returned when the session was\n * created). Sent as the `x-checkout-session-token` header when fetching a\n * session by `sessionId`. Required by post-#640 backends, which no longer\n * let the UUID alone authorize a session read; harmless on older backends.\n * Only consulted in the `sessionId` flow — inline `createSession` sessions\n * carry their own freshly-minted nonce server-side.\n */\n nonce?: 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 /**\n * Show the PayPal payment surface (default: `true`). Renderer is chosen\n * from `gateways.paypal` on the session — DirectPayPalButton when present,\n * Stripe-rendered PayPal otherwise.\n */\n showPayPal?: boolean;\n /**\n * Show the Stripe-rendered checkout — card fields, ExpressCheckoutElement,\n * and the PaymentElement accordion (default: `true`). When `false`, only\n * `DirectPayPalButton` can render. Both `showStripe=false` and\n * `showPayPal=false` (with no PayPal gateway configured) triggers a\n * bootstrap-time validation error.\n */\n showStripe?: boolean;\n /**\n * @deprecated Apple Pay availability is now driven by\n * `gateways.stripe.enabledPaymentMethods` on the per-session response from\n * the billing API. Setting this prop emits a one-time deprecation warning\n * and is otherwise ignored once the backend ships the list.\n */\n showApplePay?: boolean;\n /**\n * @deprecated See {@link FloPayCheckoutProps.showApplePay}.\n */\n showGooglePay?: boolean;\n /**\n * Enables on-screen diagnostic panels (PayPal gate decision, DirectPayPalButton\n * lifecycle). Intended for debugging in-app browsers (Facebook, Instagram, etc.)\n * where remote console access is impractical. Off by default.\n */\n debug?: boolean;\n /** Layout mode: 'default' (all visible) or 'buttons' (PayPal/wallets + expandable card form). */\n layout?: 'default' | 'buttons';\n /**\n * High-level theme bundle that styles both the Stripe-side appearance and\n * the FloPay wrapper / submit / inputs. One of: `'classic'` (historic FloPay\n * look, no bundle applied), `'modern-light'`, `'modern-dark'`,\n * `'bold-light'`, `'bold-dark'`, `'glass-light'`, `'glass-dark'`. Explicit\n * `appearance` / `buttonsStyles` props still override their respective\n * halves when supplied.\n */\n theme?: import('@flopay/shared').ThemeId;\n /**\n * @deprecated Use `theme` instead. Legacy buttons-layout preset\n * (`'default' | 'minimal' | 'rounded' | 'dark'`). Still honored for\n * back-compat.\n */\n buttonsTheme?: import('@flopay/shared').ButtonsLayoutTheme;\n /** Style overrides merged on top of the resolved theme bundle / buttonsTheme 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 /**\n * @deprecated No longer rendered — the default-layout security footer was\n * removed alongside the theme-bundle refactor. Retained as an optional\n * prop so existing integrations type-check without changes.\n */\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 `gateways.stripe.publishableKey`. Accepted only\n * for 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 nonce: nonceProp,\n createSession: createSessionParams,\n billingApiUrl,\n appearance: appearanceOverride,\n locale,\n loading: loadingNode,\n error: errorNode,\n onComplete,\n onError,\n onDecline,\n onFullNameChange,\n onCountryChange,\n onZipChange,\n showPayPal = true,\n showStripe = true,\n showApplePay = true,\n showGooglePay = true,\n debug = false,\n layout,\n theme,\n buttonsTheme,\n buttonsStyles,\n cardButtonContent,\n cardBackButtonContent,\n cardTitleContent,\n showSecurityFooter: _showSecurityFooter,\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 // High-level `theme` resolves to a coherent {appearance, buttonsLayout}\n // bundle from `@flopay/shared`'s `THEMES` map. Explicit `appearance` /\n // `buttonsStyles` props still win — see the precedence comment in\n // `SplitCardForm`.\n const themeBundle = useMemo(() => resolveTheme(theme), [theme]);\n const appearance = appearanceOverride ?? themeBundle?.appearance;\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?.publishableKey\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?.publishableKey\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 cur: params?.currency ?? '',\n a: {\n e: params?.account?.email?.trim().toLowerCase() ?? '',\n country: params?.account?.country ?? '',\n },\n successUrl: params?.successUrl,\n cancelUrl: params?.cancelUrl,\n // Unified products[] is the post-#760 wire shape. Must be included or\n // carts that only set `products` (no legacy items/subscriptions) all\n // hash to the same key — the bootstrap effect's `createSessionHash`\n // dep then never changes when products change, the session-id cache\n // hits the wrong session, and the backend's enabledPaymentMethods\n // result for the *previous* cart sticks until a fresh page-load with\n // the session cache cleared.\n p: params?.products?.map(x => `${x.type ?? ''}:${x.code ?? x.providerItemId ?? x.providerPlanId ?? ''}:${x.totalAmount ?? ''}:${x.overrideAmount ?? ''}:${x.quantity ?? 1}`).sort(),\n i: params?.items?.map(x => `${x.code ?? x.providerItemId ?? ''}:${x.totalAmount ?? ''}:${x.overrideAmount ?? ''}:${x.quantity ?? 1}`).sort(),\n s: params?.subscriptions?.map(x => `${x.code ?? 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 // PayPal-only sessions can't run saved-payment auto-checkout:\n // `handleSavedPaymentRedirectResult` requires a Stripe provider for\n // 3DS recovery, and there's no card-on-file to charge. Skip the\n // auto flow and let the render path drop to `DirectPayPalButton`.\n const resolvedPaypalOnly = isPayPalOnlyUnified(resolved.result);\n\n if (\n !cancelled &&\n shouldAutoProcessInlineSession &&\n resolvedSession &&\n !resolvedPaypalOnly\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 if (resolvedPaypalOnly) {\n autoCheckoutAttempted.current = true;\n }\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, nonceProp);\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 // PayPal-only sessions skip auto saved-payment processing — there's\n // no Stripe provider for 3DS recovery, so the render path drops\n // straight to `DirectPayPalButton`.\n const paypalOnly = isPayPalOnlyUnified(result);\n\n if (\n effectiveMode === 'auto' &&\n !autoCheckoutAttempted.current &&\n !hasPayPalRedirectParams &&\n !paypalOnly\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 nonceProp,\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 const directPaypalConfig = resolveDirectPaypalConfig(unified);\n // PayPal-only sessions advertise `gateways.paypal` without `gateways.stripe`.\n // Stripe Elements (and the SplitCardForm card surface that depends on them)\n // can't mount in that case, so we render `DirectPayPalButton` as the sole\n // payment surface and bypass `FloPayProvider` entirely.\n const isPaypalOnlySession = isPayPalOnlyUnified(unified);\n\n // Provider options from session data. Only meaningful when Stripe is\n // available — PayPal-only sessions never mount Stripe Elements.\n const providerOptions = useMemo(() => {\n if (!unified || !session || !unified.data.stripe?.publishableKey) 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 (unified.data.stripe?.clientSecret) {\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 !isPaypalOnlySession &&\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. Wallet/card skeletons are\n // gated on `showStripe` so a PayPal-only checkout doesn't briefly flash\n // Stripe affordances during bootstrap.\n if (layout === 'buttons') {\n // Match the theme's tile border-radius so the loading skeletons line\n // up with the eventual buttons. `bundleRadius` reads from the\n // resolved theme bundle's `cardButton.borderRadius` (e.g. `14px` for\n // modern, `20px` for glass) and falls back to the appearance\n // variable, then `8px` for classic.\n const bundleRadius =\n (themeBundle?.buttonsLayout?.cardButton?.borderRadius as string | number | undefined) ??\n (themeBundle?.appearance.variables?.borderRadius as string | undefined) ??\n 8;\n const skeletonBar = (h: number) => (\n <div style={{\n height: h, borderRadius: bundleRadius, 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 {showStripe && (showApplePay || showGooglePay) && skeletonBar(DEFAULT_BUTTONS_LAYOUT_BUTTON_HEIGHT)}\n {showStripe && 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 role=\"alert\"\n data-testid=\"flopay-load-error\"\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 showStripe={showStripe}\n showApplePay={showApplePay}\n showGooglePay={showGooglePay}\n theme={theme}\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 // PayPal-only session: render DirectPayPalButton as the sole payment\n // surface. Stripe Elements never mount, so we bypass FloPayProvider /\n // SplitCardForm entirely.\n if (isPaypalOnlySession && session && directPaypalConfig) {\n return (\n <>\n <CheckoutContext.Provider value={checkoutValue}>\n <div className={className} style={{ display: 'flex', flexDirection: 'column', gap: '0.5rem' }}>\n {modeError && (\n <div\n role=\"alert\"\n data-testid=\"flopay-error\"\n style={{\n padding: '0.625rem 0.875rem',\n background: '#FEF2F2',\n border: '1px solid #FECACA',\n borderRadius: '8px',\n color: '#991B1B',\n fontSize: '0.85rem',\n fontWeight: 600,\n }}\n >\n {modeError}\n </div>\n )}\n <DirectPayPalButton\n sessionId={activeSessionId}\n nonce={session.clientSecret || undefined}\n billingApiUrl={resolvedBillingUrl}\n email={session.customer?.email}\n clientId={directPaypalConfig.clientId}\n environment={directPaypalConfig.environment}\n currency={(session.currency ?? 'usd').toUpperCase()}\n isSubscription={session.mode === 'subscription'}\n onComplete={onComplete}\n onErrorChange={setModeError}\n onDecline={onDecline}\n onButtonClick={onButtonClick}\n session={session}\n debug={debug}\n />\n </div>\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 nonce={session?.clientSecret || undefined}\n billingApiUrl={resolvedBillingUrl}\n session={session}\n >\n {children}\n </SessionInjector>\n </>\n ) : (\n <SplitCardForm\n sessionId={activeSessionId}\n nonce={session?.clientSecret || undefined}\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 showStripe={showStripe}\n enabledPaymentMethods={unified?.data.stripe?.enabledPaymentMethods}\n showApplePay={showApplePay}\n showGooglePay={showGooglePay}\n layout={layout}\n theme={theme}\n buttonsTheme={buttonsTheme}\n buttonsStyles={buttonsStyles}\n appearance={appearance}\n cardButtonContent={cardButtonContent}\n cardBackButtonContent={cardBackButtonContent}\n cardTitleContent={cardTitleContent}\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 directPaypal={resolveDirectPaypalConfig(unified)}\n isSubscription={session?.mode === 'subscription'}\n session={session}\n debug={debug}\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 nonce,\n billingApiUrl,\n session,\n children,\n}: {\n sessionId: string;\n nonce?: 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.nonce && nonce) injected.nonce = nonce;\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 showStripe = true,\n showApplePay,\n showGooglePay,\n theme,\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 showStripe?: boolean;\n showApplePay: boolean;\n showGooglePay: boolean;\n theme?: import('@flopay/shared').ThemeId;\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 themeBundle = useMemo(() => resolveTheme(theme), [theme]);\n const bStyles = useMemo<ButtonsLayoutStyles>(() => {\n const base = themeBundle?.buttonsLayout ?? 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 }, [themeBundle, buttonsTheme, stylesOverride]);\n\n // Match the theme's tile radius so the interim skeletons line up with the\n // eventual buttons. Same derivation as the FloPayCheckout loading path\n // above — keeps the two skeleton surfaces consistent.\n const skeletonRadius =\n (themeBundle?.buttonsLayout?.cardButton?.borderRadius as string | number | undefined) ??\n (themeBundle?.appearance.variables?.borderRadius as string | undefined) ??\n 8;\n const skeleton = (h: number) => (\n <div style={{\n height: h, borderRadius: skeletonRadius, 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={{\n flex: 1, backgroundColor: inputBg,\n borderTop: 'none', borderRight: 'none',\n borderBottom: `1px solid ${inputBorder}`, borderLeft: `1px solid ${inputBorder}`,\n borderBottomLeftRadius: 8, padding: 12, height: 45,\n }}>\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={{\n flex: 1, backgroundColor: inputBg,\n borderTop: 'none',\n borderRight: `1px solid ${inputBorder}`,\n borderBottom: `1px solid ${inputBorder}`,\n borderLeft: `1px solid ${inputBorder}`,\n borderBottomRightRadius: 8, padding: 12, height: 45,\n }}>\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 {showStripe && (showApplePay || showGooglePay) && skeleton(DEFAULT_BUTTONS_LAYOUT_BUTTON_HEIGHT)}\n {showStripe && (\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 )}\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 PaymentElement,\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 CheckoutSession,\n DeclineEvent,\n GatewayEnvironment,\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 filterStripeMethodsByCurrency,\n filterStripeMethodsByCountry,\n filterStripeMethodsByAmount,\n getStripeMethodDisplayName,\n hasVendoredStripeMethodLogo,\n needsStripeMethodExplicitConfirm,\n resolveStripeMethodBrandVariant,\n partitionStripeMethods,\n stripeExpressMethodToOptionKey,\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';\nimport { DirectPayPalButton } from './direct-paypal-button.js';\n\nimport { FloPayError, resolveTheme } from '@flopay/shared';\n\n/**\n * localStorage key for persisting Stripe-redirect payment state across the\n * round-trip to an external authorization page (PayPal, Cash App Pay, Klarna,\n * iDEAL, …). The legacy `flopay_wallet_resume` key is still read for one\n * minor — payloads written by older SDK builds keep resuming after upgrade.\n */\nconst STRIPE_RESUME_KEY = 'flopay_stripe_resume';\nconst LEGACY_WALLET_RESUME_KEY = 'flopay_wallet_resume';\n// PayPal-direct (ExpressCheckoutElement) uses its own resume effect; this key\n// carries the effective session / nonce / accountPatch across the redirect so\n// the resume handler can /process against the same session PayPal authorized\n// (an inline-session bootstrap inside `runBeforeButtonClick` would otherwise\n// be lost when the page reloads after the PayPal round-trip).\nconst PAYPAL_RESUME_KEY = 'flopay_paypal_resume';\n\ntype MaybePromise<T> = T | Promise<T>;\n\n// ─── Global keyframes (always present — not gated behind overlay render) ────\n\n// PayPal SDK's .paypal-buttons wrapper is `display: inline-block` with a\n// default margin. In a block container it leaves baseline-descender space\n// below, which visually doubles the parent's flex `gap`. Force margin: 0 +\n// vertical-align: top to neutralise both.\nconst FLOPAY_KEYFRAMES = `\n.paypal-buttons { margin: 0 !important; vertical-align: top !important; }\n@keyframes flopay-spin { to { transform: rotate(360deg); } }\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\n/**\n * Shared \"primary button\" base style for the two buyer-action buttons in the\n * buttons-layout (the \"Credit / Debit Card\" button + `FloPayAutomaticPaymentButton`).\n *\n * - `'classic'` / no theme: white background, grey border — historic look\n * that lines up with the wallet ECE row's flat tiles.\n * - Any theme bundle (`modern-*`, `bold-*`, `glass-*`): reads its surface\n * directly off the theme's `submitButton` (the \"Confirm Payment\" CTA at\n * the bottom of the card form) — same `backgroundColor`, `color`,\n * `borderRadius`, `boxShadow` — so the drill-in action is visually\n * indistinguishable from the action it leads to. `colorPrimary` is\n * *only* used as a fallback when a bundle's `submitButton` doesn't pin\n * its own `backgroundColor`.\n */\nexport function derivePrimaryTileStyle(opts: {\n themeBundle: import('@flopay/shared').ThemeBundle | null | undefined;\n resolvedPrimaryColor: string;\n resolvedBorderRadius: string;\n submitButtonStyle?: React.CSSProperties;\n}): React.CSSProperties {\n if (!opts.themeBundle) {\n return {\n backgroundColor: 'white',\n color: '#262833',\n border: '1px solid #d1d5db',\n borderRadius: '8px',\n boxShadow: '0 1px 2px rgba(0,0,0,0.04)',\n };\n }\n const submit = opts.submitButtonStyle ?? {};\n return {\n backgroundColor: (submit.backgroundColor as string | undefined) ?? opts.resolvedPrimaryColor,\n color: (submit.color as string | undefined) ?? 'white',\n border: (submit.border as string | undefined) ?? 'none',\n borderRadius: (submit.borderRadius as string | number | undefined) ?? opts.resolvedBorderRadius,\n boxShadow: submit.boxShadow as string | undefined,\n };\n}\n\n// Buttons-panel hide style used in `layout=\"buttons\"` when the card form is in\n// view. PayPal's Stripe ExpressCheckoutElement (and the direct PayPal SDK)\n// renders its button into a cross-origin iframe whose painted content ignores\n// the parent's `visibility: hidden`. Without `height: 0 + overflow: hidden`\n// the PayPal button stays visually painted on the card-details step even\n// though it is logically hidden. Keeping the panel mounted (rather than\n// unmounting) preserves PayPal/wallet Elements state across the transition.\nconst BUTTONS_PANEL_HIDDEN_STYLE: React.CSSProperties = {\n visibility: 'hidden',\n position: 'absolute',\n pointerEvents: 'none',\n width: '100%',\n height: 0,\n overflow: 'hidden',\n};\n\ntype TokenizedBodyOverrides = {\n accountPatch?: InlineSessionPatch['account'];\n completionPaymentMethodId?: string;\n sessionId?: string;\n nonce?: string;\n};\n\ntype InternalTokenizedBodyHandler = (\n body: TokenizedBody,\n overrides?: TokenizedBodyOverrides,\n) => void;\n\ntype BeforeButtonClickPatchResult = {\n error: FloPayError | null;\n sessionId?: string;\n nonce?: string;\n};\n\ntype BeforeButtonClickResult = {\n proceed: boolean;\n accountPatch?: InlineSessionPatch['account'];\n sessionId?: string;\n nonce?: 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<string>,\n): ExpressCheckoutLoadState {\n const available = event.availablePaymentMethods as Record<string, boolean | undefined> | undefined;\n if (!available) return 'unavailable';\n\n return methods.some((method) => available[method]) ? 'ready' : 'unavailable';\n}\n\nfunction ExpressCheckoutReadySwap({\n state,\n placeholderTestId,\n borderRadius = 8,\n children,\n}: {\n state: ExpressCheckoutLoadState;\n placeholderTestId?: string;\n /**\n * Border radius for the pulse-skeleton placeholder. Defaults to `8` for\n * the classic look; consumers pass the theme's `borderRadius` (or the\n * theme bundle's `cardButton.borderRadius`) so the skeleton matches the\n * eventual button's corners — otherwise the placeholder reads as\n * visually unrelated to the wallet tile that replaces it.\n */\n borderRadius?: string | number;\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,\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 /**\n * Session-bound checkout token returned by session creation\n * (`CheckoutSessionResult.nonce` or `session.clientSecret`). Forwarded as\n * `x-checkout-session-token` on every continuation request — required by\n * post-#640 backends. `FloPayCheckout` plumbs this prop automatically.\n */\n nonce?: 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 the PayPal payment surface above card fields. Defaults to `true`.\n * The renderer is chosen from `session.gateways.paypal`: when that gateway\n * is configured, `DirectPayPalButton` (PayPal JS SDK) takes over and Stripe\n * drops `paypal` from its express row to avoid double-rendering; otherwise\n * PayPal renders inside `ExpressCheckoutElement` (using either a dedicated\n * `gateways.stripe.paypalPublishableKey` sub-account or the main Stripe\n * account when the enabled-methods list includes `paypal`).\n */\n showPayPal?: boolean;\n /**\n * Show the Stripe-rendered checkout (card fields + ExpressCheckoutElement +\n * PaymentElement). Defaults to `true`. When `false`, every Stripe surface\n * is hidden — only `DirectPayPalButton` can render. Setting both\n * `showStripe={false}` and `showPayPal={false}` (with no PayPal gateway\n * configured) throws a bootstrap-time validation error.\n */\n showStripe?: boolean;\n /**\n * Per-session list of Stripe payment method type identifiers (as returned\n * by the billing API on `gateways.stripe.enabledPaymentMethods`). When\n * supplied, drives the contents of the `ExpressCheckoutElement` row and the\n * accordion `PaymentElement` instead of the historic hardcoded\n * Apple/Google/PayPal set. When omitted, the SDK falls back to the legacy\n * `showApplePay`/`showGooglePay`/`showPayPal` toggles.\n */\n enabledPaymentMethods?: string[];\n /**\n * @deprecated The Apple Pay / Google Pay surface is now driven by the\n * `gateways.stripe.enabledPaymentMethods` list returned per-session by the\n * billing API. Pass {@link SplitCardFormProps.enabledPaymentMethods} (or\n * upgrade the backend so `FloPayCheckout` threads it through automatically).\n * Setting this prop emits a one-time deprecation warning and is otherwise\n * ignored when `enabledPaymentMethods` is supplied.\n */\n showApplePay?: boolean;\n /**\n * @deprecated See {@link SplitCardFormProps.showApplePay}.\n */\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 * High-level theme bundle that styles the whole checkout (Stripe-side\n * appearance + FloPay wrapper / submit button / inputs). One of:\n * `'classic'` (historic FloPay look, no bundle applied), `'modern-light'`,\n * `'modern-dark'`, `'bold-light'`, `'bold-dark'`, `'glass-light'`,\n * `'glass-dark'`. Explicit `appearance` / `buttonsStyles` props still\n * override their respective halves when provided.\n */\n theme?: import('@flopay/shared').ThemeId;\n /**\n * @deprecated Use `theme` instead. Legacy buttons-layout preset\n * (`'default' | 'minimal' | 'rounded' | 'dark'`). Still honored for\n * back-compat — the new union accepts the bundle ids too but you should\n * migrate to the `theme` prop.\n */\n buttonsTheme?: import('@flopay/shared').ButtonsLayoutTheme;\n /** Style overrides merged on top of the resolved theme bundle / buttonsTheme preset. */\n buttonsStyles?: import('@flopay/shared').ButtonsLayoutStyles;\n /**\n * Appearance from `FloPayProvider` / `FloPayCheckout`. Threaded through so\n * the React-rendered wrapper, submit button, title, and per-element card\n * field styling can derive colors from `appearance.variables` when no\n * explicit `buttonsStyles` is supplied. Bundle consumers (`THEMES[id]`) get\n * a coherent look without having to forward both halves manually.\n */\n appearance?: import('@flopay/shared').FloPayAppearance;\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 /**\n * @deprecated No longer rendered — the default-layout security footer was\n * removed alongside the theme-bundle refactor. Retained as an optional\n * prop so existing integrations type-check without changes.\n */\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 * Direct PayPal gateway configuration. When provided, PayPal renders via\n * the official PayPal JS SDK (in-app browser compliant) instead of via\n * Stripe's ExpressCheckoutElement. Selection is mutually exclusive:\n * setting this disables the Stripe-rendered PayPal path automatically.\n */\n directPaypal?: {\n clientId: string;\n environment?: GatewayEnvironment;\n };\n /** Whether the active session represents a subscription (drives direct PayPal intent). */\n isSubscription?: boolean;\n /** Backing session — forwarded to direct-PayPal so it can populate accountData. */\n session?: CheckoutSession | null;\n /**\n * Enables on-screen diagnostic panels for the PayPal/wallet gating decision\n * and the `DirectPayPalButton` lifecycle. Intended for debugging in-app\n * browsers where remote console access is impractical. Off by default.\n */\n debug?: 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 nonce,\n email,\n billingApiUrl,\n onTokenizedBody,\n onErrorChange,\n isProcessing = false,\n onButtonClick,\n onDecline,\n runBeforeButtonClick,\n onLoadStateChange,\n placeholderBorderRadius,\n}: {\n sessionId: string;\n nonce?: 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 placeholderBorderRadius?: string | number;\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 nonce?: 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 // Recover the effective session / nonce / accountPatch persisted by\n // `handlePayPalConfirm` before the redirect. Without this, an inline-\n // session bootstrap done inside `runBeforeButtonClick` (which set its\n // own sessionId + nonce) would be lost — the post-reload props expose\n // the freshly re-bootstrapped base session, not the one PayPal\n // authorized — and /process would 401 against the wrong nonce.\n let persistedOverrides: TokenizedBodyOverrides | undefined;\n try {\n const raw = localStorage.getItem(PAYPAL_RESUME_KEY);\n if (raw) {\n const parsed = JSON.parse(raw) as {\n clientSecret?: string;\n sessionId?: string;\n nonce?: string;\n accountPatch?: InlineSessionPatch['account'];\n };\n // Only honor the payload if it matches this PI — a stale entry from\n // an abandoned earlier attempt should not retarget the current resume.\n if (parsed.clientSecret === clientSecret) {\n persistedOverrides = {\n ...(parsed.accountPatch ? { accountPatch: parsed.accountPatch } : {}),\n ...(parsed.sessionId ? { sessionId: parsed.sessionId } : {}),\n ...(parsed.nonce ? { nonce: parsed.nonce } : {}),\n };\n }\n }\n } catch { /* ignore corrupt payload */ }\n try { localStorage.removeItem(PAYPAL_RESUME_KEY); } catch { /* ignore */ }\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 }, persistedOverrides);\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 nonce: beforeClick.nonce,\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 nonce: beforeClick.nonce,\n };\n }\n\n const effectiveSessionId = prepared?.sessionId ?? sessionId;\n const effectiveNonce = prepared?.nonce ?? nonce;\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 intentHeaders: Record<string, string> = { 'Content-Type': 'application/json' };\n if (effectiveNonce) intentHeaders['x-checkout-session-token'] = effectiveNonce;\n const intentResponse = await fetch(`${baseUrl}/v1/checkouts/payments/intents`, {\n method: 'POST',\n headers: intentHeaders,\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 // Persist the resume payload before `confirmPayment` — if the buyer is\n // redirected to PayPal, the page reload on return wipes React state, so\n // the resume effect has to recover `effectiveSessionId`/`effectiveNonce`\n // from storage to /process against the same session PayPal authorized.\n // Keyed by `intentClientSecret` so a stale payload from a prior attempt\n // can't replay against a different PaymentIntent.\n if (typeof window !== 'undefined') {\n try {\n localStorage.setItem(PAYPAL_RESUME_KEY, JSON.stringify({\n clientSecret: intentClientSecret,\n sessionId: effectiveSessionId,\n nonce: effectiveNonce,\n accountPatch: prepared?.accountPatch,\n }));\n } catch { /* localStorage unavailable */ }\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 if (typeof window !== 'undefined') {\n try { localStorage.removeItem(PAYPAL_RESUME_KEY); } catch { /* ignore */ }\n }\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 // Inline-complete path (no redirect happened) — the resume effect won't\n // fire, so drop the persisted payload now to avoid replay on next mount.\n if (typeof window !== 'undefined') {\n try { localStorage.removeItem(PAYPAL_RESUME_KEY); } catch { /* ignore */ }\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 nonce: effectiveNonce,\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, nonce, email, baseUrl, onTokenizedBody, onErrorChange, onDecline, runBeforeButtonClick]);\n\n return (\n <>\n <ExpressCheckoutReadySwap\n state={loadState}\n placeholderTestId=\"flopay-paypal-placeholder\"\n borderRadius={placeholderBorderRadius}\n >\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 nonce,\n email,\n billingApiUrl,\n expressMethods,\n onTokenizedBody,\n onErrorChange,\n onButtonClick,\n onDecline,\n runBeforeButtonClick,\n onLoadStateChange,\n placeholderBorderRadius,\n}: {\n sessionId: string;\n nonce?: string;\n email?: string;\n billingApiUrl: string;\n /**\n * Stripe-wire method identifiers to render in the ExpressCheckoutElement\n * (`apple_pay`, `google_pay`, `link`, `amazon_pay`, `klarna`, `paypal`).\n * Already filtered against {@link STRIPE_EXPRESS_METHODS}; `paypal` is\n * dropped upstream when `DirectPayPalButton` owns the PayPal surface.\n */\n expressMethods: string[];\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 placeholderBorderRadius?: string | number;\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 nonce?: 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. Stripe's\n // `expressPaymentType` covers Apple/Google Pay; the SDK collapses\n // anything else (Link, Amazon Pay, Klarna) onto `google_pay` for the\n // existing analytics enum surface.\n const walletType = (event as unknown as { expressPaymentType?: string }).expressPaymentType;\n let prepared = beforeClickRef.current;\n beforeClickRef.current = null;\n\n const buttonMethod: CheckoutButtonMethod = walletType === 'apple_pay' ? 'apple_pay' : 'google_pay';\n if (!prepared && runBeforeButtonClick) {\n const beforeClick = await runBeforeButtonClick(buttonMethod);\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 nonce: beforeClick.nonce,\n };\n }\n\n const method = buttonMethod;\n const effectiveSessionId = prepared?.sessionId ?? sessionId;\n const effectiveNonce = prepared?.nonce ?? nonce;\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 intentHeaders: Record<string, string> = { 'Content-Type': 'application/json' };\n if (effectiveNonce) intentHeaders['x-checkout-session-token'] = effectiveNonce;\n const intentResponse = await fetch(`${baseUrl}/v1/checkouts/payments/intents`, {\n method: 'POST',\n headers: intentHeaders,\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 nonce: effectiveNonce,\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, nonce, email, baseUrl, onTokenizedBody, onErrorChange, onDecline, runBeforeButtonClick],\n );\n\n // ExpressCheckoutElement's `paymentMethods` map uses camelCase keys; every\n // method not present in `expressMethods` is explicitly set to `'never'` so\n // Stripe collapses it instead of falling back to its own defaults. Only\n // `applePay` and `googlePay` accept `'always'`; `link`, `klarna`, `amazonPay`,\n // and `paypal` are typed as `'auto' | 'never'` by Stripe and throw an\n // IntegrationError at mount if `'always'` is passed.\n const expressMethodMap = useMemo(() => {\n const allKeys = ['applePay', 'googlePay', 'paypal', 'link', 'amazonPay', 'klarna'] as const;\n const alwaysCapable = new Set<string>(['applePay', 'googlePay']);\n const enabledKeys = new Set(expressMethods.map(stripeExpressMethodToOptionKey));\n const out: Record<string, 'always' | 'auto' | 'never'> = {};\n for (const key of allKeys) {\n if (!enabledKeys.has(key)) {\n out[key] = 'never';\n } else {\n out[key] = alwaysCapable.has(key) ? 'always' : 'auto';\n }\n }\n return out;\n }, [expressMethods]);\n const availableMethodKeys = useMemo(\n () => expressMethods.map(stripeExpressMethodToOptionKey),\n [expressMethods],\n );\n\n return (\n <>\n <ExpressCheckoutReadySwap\n state={loadState}\n placeholderTestId=\"flopay-wallet-placeholder\"\n borderRadius={placeholderBorderRadius}\n >\n <ExpressCheckoutElement\n onReady={(event) => {\n setLoadState(resolveExpressCheckoutLoadState(event, availableMethodKeys));\n }}\n onLoadError={(_event) => {\n setLoadState('load_error');\n }}\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 nonce: beforeClick.nonce,\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: expressMethodMap,\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// ─── Stripe PaymentElement (non-express APMs: Cash App Pay / Klarna / Affirm / iDEAL / SEPA …) ─\n\n/**\n * PaymentElement region — rendered as one button per enabled APM, styled to\n * match the wallet ECE row above it. Each button's behaviour is determined\n * by {@link needsStripeMethodExplicitConfirm} in the shared method matrix:\n *\n * - **Auto-confirm methods** (Cash App, Affirm, …): clicking the button\n * swaps it for a loading spinner, and the SDK goes straight to\n * `stripe.confirmPayment({ payment_method_data: { type, billing_details } })`\n * with no PaymentElement involvement. Stripe takes over with its popup /\n * redirect; on cancel the spinner reverts back to the button.\n *\n * - **Input-form methods** (SEPA Debit, EPS, iDEAL, …): clicking the\n * button collapses the row to just that method and mounts an inline\n * PaymentElement scoped to `paymentMethodTypes: [method]` in a separate\n * Elements group. The inline form shows the method's required input\n * (IBAN, bank picker, …) plus a \"Pay with X\" button. A back link\n * restores the full button row.\n *\n * Each expanded form mounts its own {@link StripeElements} group rather\n * than sharing a parent group across methods, because `paymentMethodTypes`\n * cannot be mutated on an existing Elements group (`elements.update()`\n * explicitly rejects it). The trade-off is a ~500ms `/v1/elements/sessions`\n * call on first expansion of each method — acceptable cost for the focused\n * per-method UX.\n */\n\n/**\n * Reusable method-tile button — same 44px contract as the wallet ECE row.\n * Lifted out so both the unselected list and the expanded-method header\n * reuse the same shape and theming. The pressed state (`submitting`)\n * replaces the label with a spinner so the buyer sees feedback during the\n * `POST /payments/intents` → `stripe.confirmPayment` round-trip on\n * auto-confirm methods.\n */\nfunction StripeMethodButton({\n method,\n themeId,\n submitting = false,\n disabled = false,\n highlighted = false,\n hasNextStep = false,\n onClick,\n backgroundColor,\n borderColor,\n textColor,\n borderRadius,\n fontFamily,\n}: {\n method: string;\n /**\n * Active FloPay theme id — drives which `STRIPE_METHOD_MATRIX[method]\n * .theme.{light,dark}` variant the button picks up its brand colors\n * (and eventually logo) from. `null`/`undefined`/`classic` falls back\n * to the matrix's `light` variant; any `*-dark` theme picks the `dark`\n * variant.\n */\n themeId?: import('@flopay/shared').ThemeId | null;\n submitting?: boolean;\n disabled?: boolean;\n highlighted?: boolean;\n /**\n * Render a right-chevron at the trailing edge of the button label,\n * signalling that clicking the tile drills into a second page (the\n * inline form for input-requiring APMs like SEPA Debit / EPS / iDEAL).\n * Auto-confirm methods (Cash App, Affirm) leave this off — their click\n * goes straight to Stripe's authorization UI with no intermediate page.\n */\n hasNextStep?: boolean;\n onClick: () => void;\n backgroundColor?: string;\n borderColor?: string;\n textColor?: string;\n borderRadius?: string | number;\n fontFamily?: string;\n}) {\n // Resolution order:\n // 1. Brand variant pulled from `STRIPE_METHOD_MATRIX[method].theme`\n // keyed by mode — gives Cash App green, Klarna pink, etc., out of\n // the box. Brand wins over the surrounding theme bundle's neutral\n // `cardButton` styling because the *method's* identity is more\n // specific than the *layout's* tile design — and the parent always\n // passes the theme bundle's `cardButton` colors through the prop\n // channel, so otherwise no branded button would ever surface.\n // 2. Inline `buttonAppearance` prop — bundle-level overrides for\n // methods without a brand variant in the matrix.\n // 3. Defaults — white + grey border, matching the legacy tile.\n const brand = resolveStripeMethodBrandVariant(method, themeId);\n const resolvedBackground = brand?.backgroundColor ?? backgroundColor ?? '#ffffff';\n const resolvedBorder = brand?.borderColor ?? borderColor ?? '#d1d5db';\n const resolvedTextColor = brand?.textColor ?? textColor ?? '#262833';\n return (\n <button\n type=\"button\"\n data-testid={`flopay-stripe-method-button-${method}`}\n data-method={method}\n onClick={() => { if (!submitting && !disabled) onClick(); }}\n disabled={submitting || disabled}\n aria-busy={submitting || undefined}\n style={{\n position: 'relative',\n width: '100%',\n boxSizing: 'border-box',\n height: DEFAULT_BUTTONS_LAYOUT_BUTTON_HEIGHT,\n padding: '0 1rem',\n backgroundColor: resolvedBackground,\n color: resolvedTextColor,\n border: `1px solid ${resolvedBorder}`,\n borderRadius: borderRadius ?? 8,\n fontSize: '0.95rem',\n fontWeight: 600,\n fontFamily,\n cursor: submitting || disabled ? 'not-allowed' : 'pointer',\n opacity: disabled && !submitting ? 0.55 : 1,\n // Submitting state pulses the whole button background, mirroring\n // the wallet ECE's `flopay-pulse` skeleton. This keeps the loading\n // affordance consistent between embedded wallets (Apple Pay,\n // Google Pay) and these custom APM tile buttons — same animation\n // curve, same duration, only the surface colour changes (grey for\n // the wallet skeleton vs. brand colour for an in-flight tile).\n animation: submitting ? 'flopay-pulse 1.5s ease-in-out infinite' : undefined,\n display: 'flex',\n alignItems: 'center',\n // Always center the logo+name group. The drill-in chevron (input\n // methods) is absolutely positioned at the right edge below so it\n // doesn't pull the label off-center.\n justifyContent: 'center',\n gap: 8,\n transition: 'transform 0.1s, opacity 140ms ease-out, border-color 140ms ease-out',\n boxShadow: highlighted ? '0 0 0 2px rgba(74, 73, 255, 0.15)' : undefined,\n }}\n >\n {submitting ? (\n // Pulse-skeleton parity with the wallet ECE: no spinner, just the\n // status text on top of the pulsing background. Keeps the loading\n // affordance shape-equivalent across both kinds of tile.\n <span style={{ margin: '0 auto' }}>\n {`Connecting to ${getStripeMethodDisplayName(method)}…`}\n </span>\n ) : (\n <>\n {/* Group: logo + name sit adjacent (8px gap) so the brand mark\n reads as part of the same label, not as a separately\n left-justified icon. The group is always centered (the button's\n `justifyContent: 'center'`); the drill-in chevron is absolutely\n positioned at the right edge so it never pulls the label\n off-center. */}\n <span\n style={{\n display: 'inline-flex',\n alignItems: 'center',\n // Real vendored logos are self-contained brand cards, so they\n // get an 8px gap from the label. The generated placeholder\n // monogram reads as part of the label (the tile's first letter),\n // so it sits flush (0px) against the name.\n gap: hasVendoredStripeMethodLogo(method) ? 8 : 0,\n }}\n >\n {brand?.logoSvg && (\n <span\n aria-hidden=\"true\"\n style={{\n // 3:2 box matching the vendored datatrans logos' 120×80\n // viewBox. Each logo ships with its own white rounded-rect\n // background baked in, so the mark stays legible on any\n // brand-coloured tile without an extra chip wrapper here.\n width: 30,\n height: 20,\n flexShrink: 0,\n display: 'inline-flex',\n borderRadius: 3,\n overflow: 'hidden',\n }}\n // Logo markup originates from the matrix (`StripeMethodEntry\n // .theme.{light,dark}.logoSvg`); we trust it here because the\n // matrix is owned by the SDK, not user input.\n dangerouslySetInnerHTML={{ __html: brand.logoSvg }}\n />\n )}\n <span>{getStripeMethodDisplayName(method)}</span>\n </span>\n {hasNextStep && (\n <svg\n width=\"14\"\n height=\"14\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke={resolvedTextColor}\n strokeWidth=\"2.5\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n style={{\n position: 'absolute',\n right: '1rem',\n top: '50%',\n transform: 'translateY(-50%)',\n flexShrink: 0,\n opacity: 0.7,\n }}\n aria-hidden=\"true\"\n >\n <path d=\"M9 18l6-6-6-6\" />\n </svg>\n )}\n </>\n )}\n </button>\n );\n}\n\n/**\n * Inline form rendered beneath the selected method button for APMs that\n * need data collection. Mounts a single-method PaymentElement (Stripe's\n * accordion with one item, default-expanded) plus the \"Pay with X\" submit\n * button. Lives inside its own `<StripeElements>` group keyed by method, so\n * switching between methods unmounts the previous group cleanly.\n */\nfunction StripeMethodInlineForm({\n method,\n sessionId,\n nonce,\n email,\n billingName,\n billingApiUrl,\n onTokenizedBody,\n onErrorChange,\n onDecline,\n onCancel,\n runBeforeButtonClick,\n onButtonClick,\n isProcessing,\n submitButtonColor,\n submitButtonBorderRadius,\n submitButtonStyle,\n}: {\n method: string;\n sessionId: string;\n nonce?: string;\n email?: string;\n billingName?: string;\n billingApiUrl: string;\n onTokenizedBody: InternalTokenizedBodyHandler;\n onErrorChange?: (error: string | null) => void;\n onDecline?: (decline: DeclineEvent) => void;\n onCancel: () => void;\n runBeforeButtonClick?: RunBeforeButtonClick;\n onButtonClick?: (method: CheckoutButtonMethod) => void;\n isProcessing?: boolean;\n submitButtonColor: string;\n submitButtonBorderRadius: string | number;\n submitButtonStyle?: React.CSSProperties;\n}) {\n const stripe = useStripeRaw();\n const elements = useStripeElements();\n const [submitting, setSubmitting] = useState(false);\n const submittingRef = useRef(false);\n const [isMethodComplete, setIsMethodComplete] = useState(false);\n const [loadState, setLoadState] = useState<'loading' | 'ready' | 'load_error'>('loading');\n const baseUrl = billingApiUrl.replace(/\\/+$/, '');\n\n const handlePay = useCallback(async () => {\n if (!stripe || !elements || isProcessing || submittingRef.current || !isMethodComplete) return;\n submittingRef.current = true;\n setSubmitting(true);\n\n const beforeClick = runBeforeButtonClick\n ? await runBeforeButtonClick('card')\n : { proceed: true } as BeforeButtonClickResult;\n if (!beforeClick.proceed) {\n submittingRef.current = false;\n setSubmitting(false);\n return;\n }\n onButtonClick?.('card');\n\n const effectiveSessionId = beforeClick.sessionId ?? sessionId;\n const effectiveNonce = beforeClick.nonce ?? nonce;\n const effectiveEmail = beforeClick.accountPatch?.email ?? email;\n\n try {\n onErrorChange?.(null);\n\n const submitRes = await elements.submit();\n if (submitRes.error) {\n onErrorChange?.(submitRes.error.message ?? 'Payment failed.');\n return;\n }\n\n const pmRes = await stripe.createPaymentMethod({ elements });\n if (pmRes.error || !pmRes.paymentMethod) {\n onErrorChange?.(pmRes.error?.message ?? 'Failed to create payment method.');\n return;\n }\n const paymentMethod = pmRes.paymentMethod;\n\n if (!effectiveSessionId || !effectiveEmail) {\n throw new Error('Missing sessionId or email for payment.');\n }\n\n // Send the resolved wire type so the backend scopes the PI to just\n // this method (`payment_method_types: [<type>]`) — avoids the\n // `apple_pay invalid` PI-creation reject path on accounts without\n // domain verification.\n const intentHeaders: Record<string, string> = { 'Content-Type': 'application/json' };\n if (effectiveNonce) intentHeaders['x-checkout-session-token'] = effectiveNonce;\n const intentResponse = await fetch(`${baseUrl}/v1/checkouts/payments/intents`, {\n method: 'POST',\n headers: intentHeaders,\n body: JSON.stringify({\n sessionId: effectiveSessionId,\n email: effectiveEmail,\n paymentMethodType: paymentMethod.type || method,\n isPaypal: false,\n }),\n });\n if (!intentResponse.ok) {\n const intentError = await buildFloPayApiErrorFromResponse(intentResponse, 'Failed to create payment intent');\n onErrorChange?.(intentError.message);\n onDecline?.(buildDeclineEvent('card', intentError));\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 // Persist the resume payload before confirmPayment — same contract as\n // the legacy region, picked up by the resume handler on redirect return.\n // `clientSecret` / `nonce` / `accountPatch` mirror the PayPal recovery\n // payload: when a `runBeforeButtonClick` bootstrap created a fresh\n // session, the post-redirect re-bootstrap exposes a different base\n // session via props, so /process must use the persisted (authorized)\n // sessionId + nonce — not the fresh prop pair — to avoid a 401.\n if (typeof window !== 'undefined') {\n try {\n localStorage.setItem(STRIPE_RESUME_KEY, JSON.stringify({\n clientSecret: intentClientSecret,\n sessionId: effectiveSessionId,\n nonce: effectiveNonce,\n accountPatch: beforeClick.accountPatch,\n paymentMethodId: paymentMethod.id,\n paymentMethodType: paymentMethod.type ?? method,\n gateway: 'stripe',\n }));\n } catch { /* localStorage unavailable */ }\n }\n\n const { error: confirmError, paymentIntent } = await stripe.confirmPayment({\n clientSecret: intentClientSecret,\n confirmParams: {\n return_url: window.location.href,\n payment_method: paymentMethod.id,\n } as { return_url: string; payment_method?: string },\n redirect: 'if_required',\n });\n\n if (confirmError) {\n if (typeof window !== 'undefined') {\n try { localStorage.removeItem(STRIPE_RESUME_KEY); } catch { /* ignore */ }\n }\n const message = confirmError.message ?? 'Payment failed.';\n onErrorChange?.(message);\n onDecline?.(buildDeclineEvent('card', message, { code: confirmError.code }));\n return;\n }\n\n const SUCCESSFUL_PI_STATUSES = new Set(['succeeded', 'requires_capture', 'processing']);\n const piStatus = paymentIntent?.status;\n if (!piStatus || !SUCCESSFUL_PI_STATUSES.has(piStatus)) {\n if (typeof window !== 'undefined') {\n try { localStorage.removeItem(STRIPE_RESUME_KEY); } catch { /* ignore */ }\n }\n const message = piStatus === 'canceled'\n ? 'Payment was canceled.'\n : 'Payment was not completed. Please try again.';\n onErrorChange?.(message);\n onDecline?.(buildDeclineEvent('card', message, { code: piStatus ?? 'missing_payment_intent' }));\n return;\n }\n\n if (typeof window !== 'undefined') {\n try { localStorage.removeItem(STRIPE_RESUME_KEY); } catch { /* ignore */ }\n }\n const confirmedPmId = typeof paymentIntent?.payment_method === 'string'\n ? paymentIntent.payment_method\n : paymentIntent?.payment_method?.id;\n\n onTokenizedBody({\n id: confirmedPmId ?? paymentMethod.id,\n type: 'card',\n threeDSecureActionResultTokenId: paymentIntent?.id,\n gateway: 'stripe',\n paymentMethodType: paymentMethod.type ?? method,\n }, {\n accountPatch: beforeClick.accountPatch,\n sessionId: effectiveSessionId,\n nonce: effectiveNonce,\n });\n } catch (err) {\n onErrorChange?.(err instanceof Error ? err.message : 'Payment failed. Please try again.');\n } finally {\n submittingRef.current = false;\n setSubmitting(false);\n }\n }, [stripe, elements, isProcessing, isMethodComplete, runBeforeButtonClick, onButtonClick,\n sessionId, nonce, email, baseUrl, method, onTokenizedBody, onErrorChange, onDecline]);\n\n // The back/cancel control is rendered by the parent (\"Go back\" button at\n // the top of the 2nd-page panel that mirrors the card form's 2nd page),\n // so `onCancel` is intentionally unused here — kept on the prop signature\n // so other call sites that still embed the form inline can wire their\n // own back link if needed.\n void onCancel;\n\n return (\n <div data-testid={`flopay-stripe-method-form-${method}`} style={{ display: 'flex', flexDirection: 'column' }}>\n <PaymentElement\n onReady={() => setLoadState('ready')}\n onLoadError={() => setLoadState('load_error')}\n onChange={(event) => {\n const evRecord = event as unknown as { complete?: boolean };\n setIsMethodComplete(!!evRecord.complete);\n }}\n // Single-method group: only this method's accordion item renders,\n // default-expanded so the inline form (IBAN / bank picker) is\n // immediately visible.\n options={{\n layout: { type: 'accordion', defaultCollapsed: false, radios: 'never' },\n defaultValues: {\n billingDetails: {\n name: billingName && billingName.trim().length >= 3\n ? billingName.trim()\n : 'FloPay Customer',\n ...(email ? { email } : {}),\n },\n },\n } as unknown as Parameters<typeof PaymentElement>[0]['options']}\n />\n\n <button\n type=\"button\"\n data-testid={`flopay-stripe-method-pay-${method}`}\n onClick={() => { void handlePay(); }}\n disabled={!isMethodComplete || submitting || isProcessing || loadState !== 'ready'}\n style={{\n width: '100%',\n marginTop: '0.75rem',\n padding: '0.875rem',\n backgroundColor: submitButtonColor,\n color: 'white',\n border: 'none',\n borderRadius: submitButtonBorderRadius,\n fontSize: '1rem',\n fontWeight: 600,\n cursor: (!isMethodComplete || submitting || isProcessing || loadState !== 'ready') ? 'not-allowed' : 'pointer',\n opacity: (!isMethodComplete || submitting || isProcessing || loadState !== 'ready') ? 0.5 : 1,\n transition: 'opacity 120ms ease-out',\n ...(submitButtonStyle ?? {}),\n }}\n >\n {submitting ? 'Processing…' : `Pay with ${getStripeMethodDisplayName(method)}`}\n </button>\n </div>\n );\n}\nfunction StripePaymentElementInner({\n sessionId,\n nonce,\n email,\n billingName,\n billingApiUrl,\n paymentElementMethods,\n stripeInstance,\n paymentElementBaseOptions,\n onTokenizedBody,\n onErrorChange,\n onButtonClick,\n onDecline,\n runBeforeButtonClick,\n onLoadStateChange,\n isProcessing = false,\n submitButtonColor = '#4A49FF',\n submitButtonBorderRadius = 8,\n submitButtonStyle,\n buttonAppearance,\n themeId,\n onExpandApm,\n expandedApmMethod,\n}: {\n sessionId: string;\n nonce?: string;\n email?: string;\n /**\n * Buyer's full name, prefilled into the inline PaymentElement's billing\n * details so `elements.submit()` for methods that mandate a name (SEPA,\n * Bancontact, Klarna, …) doesn't reject with `invalid_name_<method>`.\n * Falls back to `'FloPay Customer'` only if the session has no buyer\n * name at all.\n */\n billingName?: string;\n billingApiUrl: string;\n paymentElementMethods: string[];\n /**\n * Raw Stripe instance from the parent `FloPayProvider`. The component\n * uses it directly for `confirmPayment` on auto-confirm methods (no\n * Elements group needed) and as the `stripe` prop on each expanded\n * method's inline `<StripeElements>` group.\n */\n stripeInstance: Stripe | null;\n /**\n * Shared Elements options (mode/amount/currency/appearance) without\n * `paymentMethodTypes`. Each expanded method spreads this and adds its\n * own `paymentMethodTypes: [method]` to scope its inline form.\n */\n paymentElementBaseOptions: Record<string, unknown>;\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: 'loading' | 'ready' | 'load_error') => void;\n isProcessing?: boolean;\n submitButtonColor?: string;\n submitButtonBorderRadius?: string | number;\n submitButtonStyle?: React.CSSProperties;\n /**\n * Theme overrides applied to each method tile button. Defaults to the\n * historic white-with-grey-border styling that matches the legacy\n * \"Credit / Debit Card\" button in the buttons-layout flow.\n */\n buttonAppearance?: {\n backgroundColor?: string;\n borderColor?: string;\n textColor?: string;\n borderRadius?: string | number;\n fontFamily?: string;\n };\n /**\n * Active FloPay theme id — passed through to each tile so it can look up\n * its per-mode brand styling from `STRIPE_METHOD_MATRIX[method].theme`.\n * `null`/`undefined`/`classic` resolves to the matrix's `light` variant;\n * any `*-dark` theme resolves to the `dark` variant.\n */\n themeId?: import('@flopay/shared').ThemeId | null;\n /**\n * Called when the buyer clicks a tile for a method that requires inline\n * data collection (SEPA Debit IBAN, EPS bank picker, …). The parent\n * decides how to present the expanded form — typically by transitioning\n * to a second page (mirroring the card-form 2nd page in buttons layout).\n * Auto-confirm methods (Cash App, Affirm) don't call this; they handle\n * the click locally with a button spinner + direct `confirmPayment`.\n */\n onExpandApm?: (method: string) => void;\n /**\n * The method whose 2nd-page form is currently visible (parent-managed).\n * Used to disable the *other* tile buttons during the drill-in so the\n * buyer either submits or backs out before switching methods.\n */\n expandedApmMethod?: string | null;\n}) {\n const baseUrl = billingApiUrl.replace(/\\/+$/, '');\n // Which method is showing its expanded inline form (input methods only).\n const [expandedMethod, setExpandedMethod] = useState<string | null>(null);\n // Which method is mid-`confirmPayment` (auto-confirm methods only). The\n // tile button replaces its label with a spinner while this is set.\n const [submittingMethod, setSubmittingMethod] = useState<string | null>(null);\n const submittingRef = useRef(false);\n\n // The legacy `StripePaymentElementInner` mounted one big PaymentElement,\n // so the `load_state` signal came from the element's `ready`/`loaderror`\n // events. The custom-button version has no upfront PaymentElement —\n // signal ready as soon as we have a Stripe instance and at least one\n // method to render, so the parent's gate (`shouldDisplayPaymentElementRow`)\n // can stop showing the loading skeleton.\n useEffect(() => {\n if (paymentElementMethods.length > 0 && stripeInstance) {\n onLoadStateChange?.('ready');\n } else if (!stripeInstance) {\n onLoadStateChange?.('loading');\n }\n }, [paymentElementMethods.length, stripeInstance, onLoadStateChange]);\n\n // ─── Auto-confirm flow (Cash App / Affirm / …) ─────────────────────────\n // No PaymentElement: the method has no inline data to collect, so we go\n // POST /intents → stripe.confirmPayment with `payment_method_data.type`\n // and let Stripe handle tokenization + popup/redirect inside its own UI.\n // Saves a `/v1/elements/sessions` round-trip per click compared to the\n // PaymentElement-driven path used for input methods.\n const handleAutoConfirm = useCallback(async (method: string) => {\n if (!stripeInstance) return;\n if (submittingRef.current || isProcessing) return;\n submittingRef.current = true;\n setSubmittingMethod(method);\n\n const beforeClick = runBeforeButtonClick\n ? await runBeforeButtonClick('card')\n : { proceed: true } as BeforeButtonClickResult;\n if (!beforeClick.proceed) {\n submittingRef.current = false;\n setSubmittingMethod(null);\n return;\n }\n onButtonClick?.('card');\n\n const effectiveSessionId = beforeClick.sessionId ?? sessionId;\n const effectiveNonce = beforeClick.nonce ?? nonce;\n const effectiveEmail = beforeClick.accountPatch?.email ?? email;\n\n try {\n onErrorChange?.(null);\n\n if (!effectiveSessionId || !effectiveEmail) {\n throw new Error('Missing sessionId or email for payment.');\n }\n\n const intentHeaders: Record<string, string> = { 'Content-Type': 'application/json' };\n if (effectiveNonce) intentHeaders['x-checkout-session-token'] = effectiveNonce;\n const intentResponse = await fetch(`${baseUrl}/v1/checkouts/payments/intents`, {\n method: 'POST',\n headers: intentHeaders,\n body: JSON.stringify({\n sessionId: effectiveSessionId,\n email: effectiveEmail,\n // Wire type, not pm_xxx — backend scopes `payment_method_types`\n // to this single method so unrelated account-wide methods\n // (apple_pay without domain verification, …) don't poison PI\n // creation.\n paymentMethodType: method,\n isPaypal: false,\n }),\n });\n if (!intentResponse.ok) {\n const intentError = await buildFloPayApiErrorFromResponse(intentResponse, 'Failed to create payment intent');\n onErrorChange?.(intentError.message);\n onDecline?.(buildDeclineEvent('card', intentError));\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 // Persist the resume payload before confirmPayment in case Stripe\n // redirects (Cash App Pay does on some platforms; Affirm always\n // does). The parent's resume handler picks this up on return.\n // `clientSecret` / `nonce` / `accountPatch` mirror the PayPal recovery\n // payload: when a `runBeforeButtonClick` bootstrap created a fresh\n // session, the post-redirect re-bootstrap exposes a different base\n // session via props, so /process must use the persisted (authorized)\n // sessionId + nonce — not the fresh prop pair — to avoid a 401.\n if (typeof window !== 'undefined') {\n try {\n localStorage.setItem(STRIPE_RESUME_KEY, JSON.stringify({\n clientSecret: intentClientSecret,\n sessionId: effectiveSessionId,\n nonce: effectiveNonce,\n accountPatch: beforeClick.accountPatch,\n paymentMethodType: method,\n gateway: 'stripe',\n }));\n } catch { /* localStorage unavailable in private mode */ }\n }\n\n const { error: confirmError, paymentIntent } = await stripeInstance.confirmPayment({\n clientSecret: intentClientSecret,\n confirmParams: {\n return_url: window.location.href,\n // Inline the method data — no Elements / PaymentElement\n // required. Stripe creates the PaymentMethod during confirm\n // and proceeds to its popup/redirect UI.\n payment_method_data: {\n type: method,\n billing_details: {\n name: billingName && billingName.trim().length >= 3 ? billingName.trim() : 'FloPay Customer',\n ...(effectiveEmail ? { email: effectiveEmail } : {}),\n },\n },\n } as never,\n redirect: 'if_required',\n });\n\n if (confirmError) {\n if (typeof window !== 'undefined') {\n try { localStorage.removeItem(STRIPE_RESUME_KEY); } catch { /* ignore */ }\n }\n const message = confirmError.message ?? 'Payment failed.';\n onErrorChange?.(message);\n onDecline?.(buildDeclineEvent('card', message, { code: confirmError.code }));\n return;\n }\n\n // `redirect: 'if_required'` returns *without* `confirmError` even\n // when the buyer closed an inline confirmation UI without\n // approving — `paymentIntent.status` is the authoritative signal.\n const SUCCESSFUL_PI_STATUSES = new Set(['succeeded', 'requires_capture', 'processing']);\n const piStatus = paymentIntent?.status;\n if (!piStatus || !SUCCESSFUL_PI_STATUSES.has(piStatus)) {\n if (typeof window !== 'undefined') {\n try { localStorage.removeItem(STRIPE_RESUME_KEY); } catch { /* ignore */ }\n }\n const message = piStatus === 'canceled'\n ? 'Payment was canceled.'\n : 'Payment was not completed. Please try again.';\n onErrorChange?.(message);\n onDecline?.(buildDeclineEvent('card', message, { code: piStatus ?? 'missing_payment_intent' }));\n return;\n }\n\n if (typeof window !== 'undefined') {\n try { localStorage.removeItem(STRIPE_RESUME_KEY); } catch { /* ignore */ }\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 gateway: 'stripe',\n paymentMethodType: method,\n }, {\n accountPatch: beforeClick.accountPatch,\n sessionId: effectiveSessionId,\n nonce: effectiveNonce,\n });\n } catch (err) {\n onErrorChange?.(err instanceof Error ? err.message : 'Payment failed. Please try again.');\n } finally {\n submittingRef.current = false;\n setSubmittingMethod(null);\n }\n }, [stripeInstance, isProcessing, runBeforeButtonClick, onButtonClick, sessionId, nonce, email,\n baseUrl, billingName, onTokenizedBody, onErrorChange, onDecline]);\n\n // Fallback expansion state for callers that *don't* provide `onExpandApm`\n // (e.g. the default-layout site, which has no concept of a 2nd page).\n // When the parent owns the navigation (buttons layout), we never touch\n // this and read from `expandedApmMethod` instead.\n const [localExpandedMethod, setLocalExpandedMethod] = useState<string | null>(null);\n const activeExpandedMethod = onExpandApm ? (expandedApmMethod ?? null) : localExpandedMethod;\n\n const handleMethodClick = useCallback((method: string) => {\n if (submittingRef.current || isProcessing) return;\n // While one method is expanded, the other tile buttons are disabled —\n // the buyer has to submit or back out before switching.\n if (activeExpandedMethod && activeExpandedMethod !== method) return;\n\n if (needsStripeMethodExplicitConfirm(method)) {\n if (onExpandApm) {\n // Parent (buttons layout) drives the `viewState` machine and\n // mounts the 2nd-page form there.\n onExpandApm(method);\n } else {\n // Default-layout fallback — expand the form inline beneath the\n // tile button. Same Elements-group-per-method scoping, just\n // without the page transition.\n setLocalExpandedMethod(method);\n }\n } else {\n void handleAutoConfirm(method);\n }\n }, [activeExpandedMethod, isProcessing, handleAutoConfirm, onExpandApm]);\n\n // Per-method Elements options for the local (default-layout) inline form.\n // Mirrors the buttons-layout's `apmInlineOptions` derivation in the\n // parent component.\n const localInlineElementsOptions = useMemo(() => {\n if (!localExpandedMethod) return null;\n return {\n ...paymentElementBaseOptions,\n paymentMethodTypes: [localExpandedMethod],\n } as Parameters<typeof StripeElements>[0]['options'];\n }, [localExpandedMethod, paymentElementBaseOptions]);\n\n return (\n <div\n data-testid=\"flopay-stripe-payment-element-region\"\n style={{ display: 'flex', flexDirection: 'column', gap: '0.5rem' }}\n >\n {paymentElementMethods.map((method) => {\n const isExpanded = expandedApmMethod === method;\n const isSubmittingThis = submittingMethod === method;\n const otherInProgress =\n (submittingMethod !== null && submittingMethod !== method) ||\n (expandedApmMethod !== null && expandedApmMethod !== undefined && expandedApmMethod !== method);\n\n return (\n <React.Fragment key={method}>\n <StripeMethodButton\n method={method}\n themeId={themeId}\n submitting={isSubmittingThis}\n disabled={otherInProgress}\n highlighted={isExpanded}\n // Tile buttons for input methods drill into a 2nd page; the\n // trailing chevron echoes the \"Credit / Debit Card\" button so\n // the affordance reads the same across both kinds of tiles.\n hasNextStep={needsStripeMethodExplicitConfirm(method)}\n onClick={() => handleMethodClick(method)}\n backgroundColor={buttonAppearance?.backgroundColor}\n borderColor={buttonAppearance?.borderColor}\n textColor={buttonAppearance?.textColor}\n borderRadius={buttonAppearance?.borderRadius}\n fontFamily={buttonAppearance?.fontFamily}\n />\n {/* Default-layout fallback: when the parent hasn't wired a 2nd\n page (`onExpandApm`), expand the form inline beneath the\n tile button. Buttons layout never hits this branch — it\n renders the form on its own gridArea-1/1 panel instead. */}\n {!onExpandApm && localExpandedMethod === method && localInlineElementsOptions && stripeInstance && (\n <StripeElements\n key={method}\n stripe={stripeInstance}\n options={localInlineElementsOptions}\n >\n <StripeMethodInlineForm\n method={method}\n sessionId={sessionId}\n email={email}\n billingName={billingName}\n billingApiUrl={billingApiUrl}\n onTokenizedBody={onTokenizedBody}\n onErrorChange={onErrorChange}\n onDecline={onDecline}\n onCancel={() => setLocalExpandedMethod(null)}\n runBeforeButtonClick={runBeforeButtonClick}\n onButtonClick={onButtonClick}\n isProcessing={isProcessing}\n submitButtonColor={submitButtonColor}\n submitButtonBorderRadius={submitButtonBorderRadius}\n submitButtonStyle={submitButtonStyle}\n />\n </StripeElements>\n )}\n </React.Fragment>\n );\n })}\n </div>\n );\n}\n\n// ─── Main form ──────────────────────────────────────────────────────────────\n\nfunction SplitCardFormInner({\n sessionId,\n nonce,\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 showStripe = true,\n enabledPaymentMethods,\n showApplePay = true,\n showGooglePay = true,\n layout = 'default',\n theme,\n buttonsTheme,\n buttonsStyles: buttonsStylesOverride,\n appearance: appearanceOverride,\n cardButtonContent,\n cardBackButtonContent,\n cardTitleContent,\n showSecurityFooter: _showSecurityFooter,\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 directPaypal,\n isSubscription = false,\n session,\n debug = 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 ↔ APM transition state machine. The `apm-*` branches\n // mirror the `card` branches one-for-one so the inline-form APM 2nd\n // page (SEPA / EPS / iDEAL / …) animates in and out the same way as the\n // card form's 2nd page, with the same back-button + title chrome.\n type ViewState =\n | 'buttons'\n | 'expanding'\n | 'card'\n | 'collapsing'\n | 'apm-expanding'\n | 'apm-form'\n | 'apm-collapsing';\n const [viewState, setViewState] = useState<ViewState>(initialCardOpen ? 'card' : 'buttons');\n const [expandedApmMethod, setExpandedApmMethod] = useState<string | null>(null);\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 const expandToApm = useCallback((method: string) => {\n setExpandedApmMethod(method);\n setViewState('apm-expanding');\n setTimeout(() => setViewState('apm-form'), TRANSITION_MS);\n }, []);\n\n const collapseFromApm = useCallback(() => {\n setViewState('apm-collapsing');\n setTimeout(() => {\n setViewState('buttons');\n setExpandedApmMethod(null);\n }, 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 // `paypal_direct_required` retry surface. Set when /process returns the\n // discriminator with a fresh PayPal Order/Subscription id — re-binds the\n // direct PayPal button to that id so the buyer can confirm with one more\n // click. Cleared on success or when the buyer dismisses. `attempts` caps\n // the loop at 2 retries so a backend stuck throwing the same exception\n // can't trap the buyer forever.\n const [paypalDirectRetry, setPaypalDirectRetry] = useState<{\n orderId: string;\n attempts: number;\n } | null>(null);\n // Ref-mirror so the processPaymentInternal callback can read current\n // attempt count without recreating on every retry-state change (which\n // would invalidate downstream effects depending on the callback).\n const paypalDirectRetryRef = useRef(paypalDirectRetry);\n useEffect(() => { paypalDirectRetryRef.current = paypalDirectRetry; }, [paypalDirectRetry]);\n\n const resolvedBillingApiUrl = billingApiUrl || contextBillingUrl;\n const displayError = externalError ?? error;\n\n // Resolution order for the wrapper / button styles:\n // 1. `theme` bundle (high-level — pulls a coherent ButtonsLayoutStyles from THEMES)\n // 2. Legacy `buttonsTheme` preset (for back-compat — only applied when `theme` is absent)\n // 3. Explicit `buttonsStyles` override (per-field merge on top of either base)\n // Resolution order for the Stripe-side `appearance`:\n // 1. Explicit `appearance` prop (wins outright)\n // 2. `theme` bundle's appearance (when `appearance` is not supplied)\n const themeBundle = useMemo(() => resolveTheme(theme), [theme]);\n const bStyles = useMemo<ButtonsLayoutStyles>(() => {\n const base = themeBundle?.buttonsLayout ?? 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 }, [themeBundle, buttonsTheme, buttonsStylesOverride]);\n const appearance = appearanceOverride ?? themeBundle?.appearance;\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 Stripe-rendered PayPal Elements provider.\n // When direct PayPal is configured (`directPaypal`) or no PayPal FloPay\n // instance is available, the Stripe-rendered PayPal path is suppressed.\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 // `FloPayAppearance` is a superset of Stripe's `Appearance` type (it adds\n // `variables.fontSizeBase` etc.) — the Stripe public typings reject the\n // wider shape, but the runtime accepts every extra field. Cast through\n // `Record<string, unknown>` so the spread below stays type-safe at the\n // option-construction site without `any`.\n const stripeAppearanceProp = appearance\n ? { appearance: appearance as unknown as Record<string, unknown> }\n : null;\n\n // PaymentElement-specific appearance: target Stripe's `.AccordionItem` and\n // `.AccordionItemContents` so each method card visually matches the 44px\n // wallet ECE buttons above it. Stripe accepts `padding` / `borderRadius` /\n // border styling in `rules`; `height` is not a supported property, so we\n // pin via padding (10px top/bottom × ~24px line-height ≈ 44px total).\n //\n // Stripe's default `spacedAccordionItems` rendering paints a subtle drop\n // shadow under each method card. The wallet ECE row above this region uses\n // flat buttons with no shadow, so we explicitly null the shadow here for\n // visual parity — without this, Cash App Pay sat noticeably \"above\" the\n // wallet buttons stacked just above it. Consumer overrides still win via\n // the `baseRules` spread.\n const paymentElementAppearance = useMemo(() => {\n const base = (appearance ?? {}) as Record<string, unknown>;\n const baseRules = (base.rules as Record<string, Record<string, string>> | undefined) ?? {};\n return {\n ...base,\n rules: {\n ...baseRules,\n '.AccordionItem': {\n padding: '10px 14px',\n boxShadow: 'none',\n ...(baseRules['.AccordionItem'] ?? {}),\n },\n '.AccordionItemContents': {\n padding: '6px 14px 12px',\n boxShadow: 'none',\n ...(baseRules['.AccordionItemContents'] ?? {}),\n },\n },\n };\n }, [appearance]);\n\n // Wallet (Apple/Google Pay) Elements options — uses paymentMethodCreation: 'manual'\n // to match the main card Elements, allowing explicit createPaymentMethod() calls.\n // `appearance` is forwarded so the ExpressCheckoutElement iframe inherits the\n // shared theme variables (e.g. `borderRadius`) instead of falling back to\n // Stripe's defaults.\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 ...stripeAppearanceProp,\n }), [amountInCents, currency, stripeAppearanceProp]);\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 ...stripeAppearanceProp,\n }), [amountInCents, currency, stripeAppearanceProp]);\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 // ── Method partitioning ──\n //\n // Backend now ships `enabledPaymentMethods` per-session (e.g. ['apple_pay',\n // 'cashapp', 'google_pay', 'link', 'sepa_debit']). We partition it into:\n // - `expressMethods`: the subset supported by `ExpressCheckoutElement`\n // (filtered against STRIPE_EXPRESS_METHODS).\n // - `paymentElementMethods`: everything else (Cash App Pay, Affirm, iDEAL,\n // SEPA debit, …) — rendered in the accordion PaymentElement region.\n //\n // PayPal is dropped from the express set when `DirectPayPalButton` owns the\n // PayPal surface (controlled by `gateways.paypal` upstream → `directPaypal`\n // prop here), so the SDK doesn't double-render.\n //\n // Legacy fallback: when the billing API hasn't been upgraded to ship\n // `enabledPaymentMethods`, fall back to the historic\n // `showApplePay`/`showGooglePay` toggle behaviour so existing integrations\n // keep working unchanged.\n const directPaypalConfigured = !!directPaypal?.clientId;\n // `hasEnabledMethodsPayload` distinguishes \"backend shipped the field\" from\n // \"backend shipped the field with at least one entry\". A provided-but-empty\n // array means the new gateway-driven path is in effect with no enabled\n // methods — it must NOT fall back to legacy `showApplePay`/`showGooglePay`\n // behaviour, and PayPal must stay suppressed unless `'paypal'` is in the\n // list (or `directPaypal` is configured separately).\n const hasEnabledMethodsPayload = Array.isArray(enabledPaymentMethods);\n const hasEnabledMethods = hasEnabledMethodsPayload && enabledPaymentMethods.length > 0;\n const paypalEnabled = hasEnabledMethodsPayload && enabledPaymentMethods.includes('paypal');\n const { expressMethods, paymentElementMethods } = useMemo(\n () => partitionStripeMethods(enabledPaymentMethods, {\n excludePaypal: directPaypalConfigured,\n }),\n [enabledPaymentMethods, directPaypalConfigured],\n );\n // Get raw Stripe instance early so we can decide whether PayPal renders\n // separately. `paypalStripeInstance` lives on the dedicated PayPal sub-\n // account when `gateways.stripe.paypalPublishableKey` is set; otherwise\n // PayPal can ride along inside the main wallet ECE.\n const paypalRenderedSeparately = directPaypalConfigured || !!paypalFlopay;\n // Drop PayPal from the main wallet ECE only when something else is going\n // to render it (DirectPayPal or the dedicated PayPal sub-account\n // PayPalButtonInner). When neither is configured, PayPal stays in the\n // express set so Stripe still shows the button on supported envs.\n const expressMethodsForWalletRow = useMemo(\n () => paypalRenderedSeparately\n ? expressMethods.filter((m) => m !== 'paypal')\n : expressMethods,\n [expressMethods, paypalRenderedSeparately],\n );\n const legacyExpressMethods = useMemo(() => {\n const out: string[] = [];\n if (showApplePay) out.push('apple_pay');\n if (showGooglePay) out.push('google_pay');\n return out;\n }, [showApplePay, showGooglePay]);\n // Final list driving WalletButtonInner. New path wins when the backend\n // ships the field; legacy props are used as the fallback only.\n // `hasEnabledMethodsPayload` (not `hasEnabledMethods`) gates the new-vs-legacy\n // switch: a provided-but-empty `enabledPaymentMethods=[]` means \"no methods\n // enabled\" under the new path, not \"fall back to legacy props\".\n const walletExpressMethods = hasEnabledMethodsPayload ? expressMethodsForWalletRow : legacyExpressMethods;\n const showWallets = showStripe && walletExpressMethods.length > 0;\n\n // Drop methods that don't support the session currency, the buyer's\n // country, or whose per-currency amount range excludes the session amount —\n // before we hand the list to Stripe. The `/v1/elements/sessions` endpoint\n // hard-400's when `paymentMethodTypes` contains a single method that\n // violates currency *or* amount, and the failed mount silently blanks out\n // the whole accordion as an empty `<div class=\"\">` shell. The triggers:\n //\n // - `bancontact` / `eps` / `giropay` on a USD cart — wrong currency.\n // - `affirm` on a sub-$35 USD cart — below Affirm's $35.00 minimum\n // (Stripe returns `amount_too_small` on the elements/sessions call).\n //\n // Country gating is the additional axis Stripe applies from the buyer's\n // locale: a Dutch buyer on a EUR cart sees iDEAL + SEPA but not Bancontact\n // (BE-only) or EPS (AT-only). We mirror that here off the session customer\n // country so the tile row matches what Stripe would ultimately accept.\n // A missing country leaves the country filter as a pass-through.\n const paymentElementMethodsForCurrency = useMemo(\n () => filterStripeMethodsByAmount(\n filterStripeMethodsByCountry(\n filterStripeMethodsByCurrency(paymentElementMethods, currency),\n countryProp,\n ),\n currency,\n amountInCents,\n ),\n [paymentElementMethods, currency, countryProp, amountInCents],\n );\n\n // PaymentElement Elements options — same `paymentMethodCreation: 'manual'`\n // mode as the card Elements so `createPaymentMethod({ elements })` works.\n // `paymentMethodTypes` is filtered to the non-express portion of the\n // backend-supplied enabled list (and to the methods Stripe accepts for the\n // session currency *and* amount) so the accordion never double-renders the\n // big buttons the wallet row already shows, and never includes a method\n // Stripe will reject.\n //\n // `captureMethod` is intentionally omitted (defaults to `automatic`): most\n // PaymentElement APMs (Cash App Pay, Affirm, Klarna, iDEAL, SEPA debit,\n // Bancontact, EPS, Giropay, …) do not support `manual` capture, and Stripe\n // rejects the entire Elements mount with a 400 on\n // `/v1/elements?type=deferred_intent` (\"Frame not initialized\"). The\n // accordion ends up rendered as an empty `<div class=\"\">` shell. Letting\n // capture default keeps the deferred-intent options accepted for the full\n // set of APMs we partition into this region.\n //\n // `appearance` is forwarded so the PaymentElement iframe picks up the same\n // theme variables (colours, border radius, font family) as the card row.\n // Without this, Stripe falls back to its grey defaults and the accordion\n // looks visually unrelated to the rest of the FloPay surface.\n // Base options for every per-method `<StripeElements>` group mounted by\n // `StripePaymentElementInner` (one per expanded inline form). The child\n // spreads this and tacks on `paymentMethodTypes: [<method>]` per group.\n // The per-method split is what lets each expanded form scope its\n // accordion to a single method without an `elements.update({\n // paymentMethodTypes })` call (which Stripe refuses).\n const paymentElementBaseOptions = useMemo(() => ({\n mode: 'payment' as const,\n amount: amountInCents,\n currency: currency.toLowerCase(),\n paymentMethodCreation: 'manual' as const,\n appearance: paymentElementAppearance,\n }), [amountInCents, currency, paymentElementAppearance]);\n\n // Stripe's PayPal ExpressCheckoutElement breaks inside known in-app browsers\n // and the existing flow gated it on `inAppBrowserDetected`. With the\n // gateway-driven model the renderer decision moves to `gateways.paypal`\n // (DirectPayPalButton when present, Stripe-rendered PayPal otherwise). When\n // backend ships `enabledPaymentMethods`, the in-app-browser gate is no\n // longer consulted — gateway configuration alone drives renderer choice.\n // Legacy backends keep the historic UA-based gate.\n const [paypalLoadState, setPaypalLoadState] = useState<ExpressCheckoutLoadState>('loading');\n const [walletLoadState, setWalletLoadState] = useState<ExpressCheckoutLoadState>('loading');\n const [paymentElementLoadState, setPaymentElementLoadState] = useState<'loading' | 'ready' | 'load_error'>('loading');\n const [directPaypalReady, setDirectPaypalReady] = useState(false);\n const [inAppBrowserDetected, setInAppBrowserDetected] = useState<boolean>();\n useEffect(() => {\n setInAppBrowserDetected(isInAppBrowser());\n }, []);\n // When the backend ships `enabledPaymentMethods`, the presence/absence of\n // `'paypal'` in that list decides PayPal visibility — a non-empty list that\n // omits `'paypal'` must suppress PayPal even if `paypalFlopay` is configured.\n // Only fall back to the legacy in-app-browser gate when no payload was sent\n // at all. `directPaypal` overrides both paths.\n const shouldShowPayPal = showPayPal\n && (directPaypalConfigured\n || (hasEnabledMethodsPayload\n ? paypalEnabled\n : inAppBrowserDetected === false));\n const shouldShowWallets = showStripe && showWallets;\n const shouldRenderDirectPayPal = shouldShowPayPal && directPaypalConfigured;\n const shouldRenderStripePayPal = shouldShowPayPal && !directPaypalConfigured && !!paypalStripeInstance;\n const shouldRenderWallets = shouldShowWallets && !!stripeInstance;\n // Suppress the entire PaymentElement region when the currency filter empties\n // the list — Stripe Elements won't mount with `paymentMethodTypes: []` and\n // we'd otherwise paint a blank divider row.\n const shouldRenderPaymentElement = showStripe\n && hasEnabledMethods\n && paymentElementMethodsForCurrency.length > 0\n && !!stripeInstance;\n const shouldDisplayPayPalRow = shouldRenderDirectPayPal\n ? directPaypalReady\n : shouldRenderStripePayPal && isExpressCheckoutRowVisible(paypalLoadState);\n const shouldDisplayWalletRow = shouldRenderWallets && isExpressCheckoutRowVisible(walletLoadState);\n const shouldDisplayPaymentElementRow = shouldRenderPaymentElement && paymentElementLoadState !== 'load_error';\n\n // ── Boot-time validation: nothing to render ──\n //\n // Both `showStripe` and `showPayPal` were turned off (or off + no PayPal\n // gateway present) — there's no payment surface to render. Surface this\n // as `onError` rather than silently rendering an empty form so the bug is\n // caught during integration.\n const validationFiredRef = useRef(false);\n useEffect(() => {\n if (validationFiredRef.current) return;\n if (!showStripe && !showPayPal) {\n validationFiredRef.current = true;\n const err = new FloPayError(\n 'FloPay: both `showStripe` and `showPayPal` are false — nothing to render.',\n 'validation_error',\n );\n onError?.(err);\n updateError(err.message);\n } else if (!showStripe && showPayPal && !directPaypalConfigured && !paypalStripeInstance) {\n validationFiredRef.current = true;\n const err = new FloPayError(\n 'FloPay: `showStripe` is false and no PayPal gateway is configured for this session — nothing to render.',\n 'validation_error',\n );\n onError?.(err);\n updateError(err.message);\n }\n }, [showStripe, showPayPal, directPaypalConfigured, paypalStripeInstance, onError, updateError]);\n\n // ── Deprecation warnings ──\n //\n // Emitted once per mount when consumers pass the legacy\n // `showApplePay`/`showGooglePay`/`directPaypal` props alongside the new\n // `enabledPaymentMethods` surface. The legacy props are *not* fed into the\n // new path (`enabledPaymentMethods` wins outright), so silently honouring\n // them would surprise consumers; the warning makes the migration visible.\n const deprecationLoggedRef = useRef(false);\n useEffect(() => {\n if (deprecationLoggedRef.current) return;\n if (!hasEnabledMethods) return;\n const stale: string[] = [];\n if (showApplePay !== true) stale.push('showApplePay');\n if (showGooglePay !== true) stale.push('showGooglePay');\n if (stale.length === 0) return;\n deprecationLoggedRef.current = true;\n // eslint-disable-next-line no-console\n console.warn(\n `[FloPay] ${stale.join(' / ')} ${stale.length === 1 ? 'is' : 'are'} deprecated: ` +\n 'the Apple Pay / Google Pay surface is now driven by ' +\n '`gateways.stripe.enabledPaymentMethods` on the session response. ' +\n 'Remove the legacy prop(s) to silence this warning.',\n );\n }, [hasEnabledMethods, showApplePay, showGooglePay]);\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, nonce });\n }\n\n return checkout.applyInlineSessionPatch(patch)\n .then((result) => ({\n error: null,\n sessionId: result.sessionId || sessionId,\n // A freshly bootstrapped session carries its own nonce on\n // `session.clientSecret`. Pair it with the new sessionId so\n // downstream continuation calls don't send the new id with the\n // prior session-bound token.\n nonce: result.session?.clientSecret || nonce,\n }))\n .catch((err) => {\n const floPayErr = normalizeBeforeButtonClickError(method, err);\n updateError(floPayErr.message);\n onError?.(floPayErr);\n return { error: floPayErr, sessionId, nonce };\n });\n },\n [checkout.applyInlineSessionPatch, nonce, 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 nonce: patchResult.nonce,\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 // Keep the nonce paired with the (possibly overridden) sessionId.\n // `runBeforeButtonClick`/`applyInlineSessionPatch` can bootstrap a\n // fresh session and hand back its nonce; using the stale\n // component-level nonce here would send the new id with the prior\n // session-bound token and 401 on the continuation route.\n const effectiveNonce = overrides?.nonce ?? nonce;\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 nonce: effectiveNonce,\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 // Clear any pending paypal_direct_required retry — process\n // succeeded, so the re-bound retry button is no longer needed.\n setPaypalDirectRetry(null);\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 // Preserve the session/nonce/account overrides resolved\n // above so the retry talks to the same (possibly\n // freshly bootstrapped) session as the original attempt.\n accountPatch: overrides?.accountPatch,\n sessionId: effectiveSessionId,\n nonce: effectiveNonce,\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 // Direct PayPal retry — backend created a fresh PayPal order\n // (typically after a failed inline-session reuse) and wants the SDK\n // to relaunch the PayPal popup against that order id. Re-binds the\n // existing DirectPayPalButton via `paypalDirectRetry` state; the\n // buyer clicks the same button again, PayPal opens with the new\n // order, and onApprove fires another /process call. Bounded to 2\n // retries so a misconfigured backend can't trap the buyer.\n if (json?.type === 'paypal_direct_required') {\n const orderId = json['orderId'] as string | undefined;\n if (!orderId) {\n setOverlayStatus('error');\n updateError('PayPal retry required but no order id provided.');\n return;\n }\n const prevAttempts = paypalDirectRetryRef.current?.attempts ?? 0;\n if (prevAttempts >= 2) {\n setOverlayStatus('error');\n updateError('PayPal payment could not be completed after multiple attempts.');\n emitDecline('paypal', 'paypal_direct_required retry limit exceeded');\n return;\n }\n setPaypalDirectRetry({ orderId, attempts: prevAttempts + 1 });\n // Hide the processing overlay so the buyer can see and act on the\n // re-bound PayPal button. Don't emitDecline — this isn't a decline.\n setOverlayStatus(null);\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, nonce, 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 // ── Stripe resume (Cash App Pay / Klarna / iDEAL / Bancontact / …) ──\n //\n // Method-agnostic handler for the buyer returning from any Stripe\n // redirect-based payment method. The PaymentElement region writes its\n // tokenization state to `STRIPE_RESUME_KEY` (or the legacy\n // `flopay_wallet_resume` for back-compat with old SDK builds) *before*\n // calling `confirmPayment`, then we verify the PI status on return.\n //\n // Two gates before we hand off to /process — both required to avoid the\n // class of bugs where the SDK marches to /success on an uncharged PI:\n //\n // 1. **URL params must be present.** Stripe redirects buyers back with\n // `payment_intent` / `payment_intent_client_secret` / `redirect_status`\n // on the query string. If those are missing — the buyer hit back, the\n // auth tab was closed, or this is just a normal `/theme` mount — we\n // do nothing, even if `STRIPE_RESUME_KEY` is still in localStorage.\n //\n // 2. **Stripe-side PI status must be successful.** We `retrievePaymentIntent`\n // and only dispatch when the actual status is one of\n // `succeeded` / `requires_capture` / `processing`. A `redirect_status`\n // of `failed`, a buyer who closed the popup without approving (PI stuck\n // at `requires_action`), or a canceled PI all route to `onDecline`.\n //\n // PayPal-direct uses its own resume effect (`PayPalButtonInner`); this\n // handler intentionally excludes the PayPal Stripe sub-account flow to\n // avoid double-dispatch.\n const stripeResumeAttemptedRef = useRef(false);\n useEffect(() => {\n if (typeof window === 'undefined' || stripeResumeAttemptedRef.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 // No `payment_intent` URL param = buyer didn't actually return from a\n // Stripe redirect. Skip even if `STRIPE_RESUME_KEY` is in localStorage:\n // that key is set *before* confirmPayment, so it lives in localStorage\n // between click and authorization. A page reload, navigation, or close\n // of the auth tab would otherwise replay it as a phantom success.\n if (!paymentIntentId || !clientSecret) return;\n\n const readPayload = (key: string) => {\n const raw = localStorage.getItem(key);\n if (!raw) return null;\n try {\n return JSON.parse(raw) as {\n clientSecret?: string;\n sessionId?: string;\n nonce?: string;\n accountPatch?: InlineSessionPatch['account'];\n paymentIntentId?: string;\n paymentMethodId?: string;\n paymentMethodType?: string;\n gateway?: string;\n tokenType?: string;\n tokenId?: string;\n status?: string;\n } | null;\n } catch {\n localStorage.removeItem(key);\n return null;\n }\n };\n\n const payload =\n readPayload(STRIPE_RESUME_KEY) ?? readPayload(LEGACY_WALLET_RESUME_KEY);\n\n // Recover the effective session / nonce / accountPatch persisted by the\n // APM confirm sites before the redirect. Without this, an inline-session\n // bootstrap done inside `runBeforeButtonClick` (which set its own\n // sessionId + nonce) is lost — the post-reload props expose the freshly\n // re-bootstrapped base session — and /process would 401 against the\n // wrong nonce. Mirrors the PayPal resume contract at ~L609-635.\n //\n // Gate on `clientSecret` matching this PI so a stale entry from an\n // abandoned earlier attempt can't retarget the current resume. Legacy\n // payloads (no `clientSecret`) keep the original session-match guard so\n // an old SDK build's writer cannot dispatch against the wrong session.\n let persistedOverrides: TokenizedBodyOverrides | undefined;\n if (payload?.clientSecret) {\n if (payload.clientSecret !== clientSecret) return;\n persistedOverrides = {\n ...(payload.accountPatch ? { accountPatch: payload.accountPatch } : {}),\n ...(payload.sessionId ? { sessionId: payload.sessionId } : {}),\n ...(payload.nonce ? { nonce: payload.nonce } : {}),\n };\n } else if (payload?.sessionId && payload.sessionId !== sessionId) {\n return;\n }\n\n stripeResumeAttemptedRef.current = true;\n localStorage.removeItem(STRIPE_RESUME_KEY);\n localStorage.removeItem(LEGACY_WALLET_RESUME_KEY);\n\n // Strip Stripe's redirect params synchronously before any async work, so\n // a remount that races our async retrieval can't re-enter this effect\n // for the same PI.\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 const paymentMethodType =\n payload?.paymentMethodType ?? payload?.tokenType ?? 'card';\n const declineMethod: CheckoutButtonMethod = 'card';\n\n (async () => {\n const rawProvider = flopay?.getRawProvider() as Stripe | null | undefined;\n if (!rawProvider) {\n const message = 'Payment is not available — please refresh and try again.';\n updateError(message);\n emitDecline(declineMethod, message);\n return;\n }\n\n if (redirectStatus === 'failed') {\n const message = 'Payment was declined. Please try again.';\n updateError(message);\n emitDecline(declineMethod, message);\n return;\n }\n\n const { paymentIntent, error } = await rawProvider.retrievePaymentIntent(clientSecret);\n if (error) {\n const message = error.message ?? 'Failed to retrieve payment status.';\n updateError(message);\n emitDecline(declineMethod, message, { code: error.code });\n return;\n }\n\n const piStatus = paymentIntent?.status;\n const successful = piStatus === 'succeeded' || piStatus === 'requires_capture' || piStatus === 'processing';\n if (!paymentIntent || !successful) {\n const message = piStatus === 'canceled'\n ? 'Payment was canceled.'\n : 'Payment was not completed. Please try again.';\n updateError(message);\n emitDecline(declineMethod, message, { code: piStatus ?? 'missing_payment_intent' });\n return;\n }\n\n const resolvedPmId = typeof paymentIntent.payment_method === 'string'\n ? paymentIntent.payment_method\n : paymentIntent.payment_method?.id;\n\n dispatchTokenizedBody({\n id: resolvedPmId ?? payload?.paymentMethodId ?? payload?.tokenId ?? paymentIntent.id,\n type: 'card',\n threeDSecureActionResultTokenId: paymentIntent.id,\n gateway: (payload?.gateway as 'stripe' | 'paypal' | undefined) ?? 'stripe',\n paymentMethodType,\n }, persistedOverrides);\n })();\n }, [sessionId, dispatchTokenizedBody, flopay, updateError, emitDecline]);\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 intentHeaders: Record<string, string> = { 'Content-Type': 'application/json' };\n if (nonce) intentHeaders['x-checkout-session-token'] = nonce;\n const intentResponse = await fetch(`${baseUrl}/v1/checkouts/payments/intents`, {\n method: 'POST',\n headers: intentHeaders,\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, nonce, 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 // Three-tier fallback for visual styling:\n // 1. `bStyles` (resolved from `buttonsTheme` + `buttonsStyles` override) —\n // the explicit, coherent bundle. Wins when present.\n // 2. `appearance.variables` from FloPayProvider — covers consumers who\n // pass only the Stripe-side appearance and still expect the React\n // wrapper / submit / inputs to recolor.\n // 3. Hardcoded layout defaults — back-compat for callers passing neither.\n // This is what makes `<FloPayCheckout appearance={THEMES['glass-dark'].appearance} />`\n // produce a visible recolor even before the demo forwards the buttonsLayout half.\n const appearanceVars = appearance?.variables;\n // `appearance.colorBackground` is, in Stripe terms, the *input* surface — not\n // the outer FloPay wrapper. Treat the SDK's default white as \"consumer did\n // not theme the wrapper\" so the historic `#EDEDFF` FloPay tint stays put on\n // the classic preset. Themed bundles supply non-white backgrounds and still\n // flow through to the wrapper as expected.\n const SDK_DEFAULT_WHITES = new Set(['#FFFFFF', '#ffffff', '#fff', '#FFF', 'white']);\n const appearanceColorBg = appearanceVars?.colorBackground;\n const themedWrapperBg =\n appearanceColorBg && !SDK_DEFAULT_WHITES.has(appearanceColorBg) ? appearanceColorBg : undefined;\n const resolvedBorder = bStyles.cardInputBorder ?? (isButtons ? '#e5e7eb' : '#A4A4FF');\n const cardBg =\n (bStyles.cardFormContainer?.backgroundColor as string)\n ?? themedWrapperBg\n ?? (isButtons ? 'white' : '#EDEDFF');\n const cardInputBg =\n bStyles.cardInputBackground\n ?? appearanceVars?.colorBackground\n ?? 'white';\n const hideBackButtonLabel = isEmptySlotContent(cardBackButtonContent);\n const hideTitle = isEmptySlotContent(cardTitleContent);\n const nameInputOverrides = bStyles.nameInput;\n const resolvedInputFontSize = bStyles.cardInputFontSize\n ?? toCssSize(nameInputOverrides?.fontSize)\n ?? appearanceVars?.fontSizeBase\n ?? '16px';\n const resolvedInputFontFamily = typeof nameInputOverrides?.fontFamily === 'string'\n ? nameInputOverrides.fontFamily\n : (appearanceVars?.fontFamily ?? 'Poppins, sans-serif');\n const resolvedInputFontWeight = toCssWeight(nameInputOverrides?.fontWeight) ?? 400;\n const resolvedInputColor = bStyles.cardInputColor\n ?? (typeof nameInputOverrides?.color === 'string' ? nameInputOverrides.color : undefined)\n ?? appearanceVars?.colorText\n ?? '#262833';\n const resolvedPlaceholderColor = bStyles.cardInputPlaceholderColor ?? '#9ca3af';\n const resolvedBorderRadius = appearanceVars?.borderRadius ?? '8px';\n // `colorPrimary` drives the submit button background when no buttonsStyles\n // override is supplied. Default keeps the historic FloPay indigo.\n const resolvedPrimaryColor = appearanceVars?.colorPrimary ?? '#4A49FF';\n const resolvedTitleColor = appearanceVars?.colorText ?? '#262833';\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 containerOverrides = (bStyles.cardFormContainer ?? {}) as React.CSSProperties;\n const containerPadding = containerOverrides.padding ?? (isButtons ? '0' : '1rem');\n const containerRadius = containerOverrides.borderRadius ?? resolvedBorderRadius;\n const cardFormBlock = (\n <div style={{\n backgroundColor: cardBg, borderRadius: containerRadius,\n ...containerOverrides,\n padding: containerPadding,\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={{\n textAlign: 'center', fontWeight: 600, fontSize: '1.1rem', padding: '0.5rem 0',\n color: resolvedTitleColor,\n ...(bStyles.title as React.CSSProperties | undefined),\n }}>\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,\n // Longhand only — mixing `border` shorthand with per-side\n // overrides triggers React's \"shorthand vs longhand\" warning\n // because render order isn't deterministic.\n borderTop: 'none', borderRight: 'none',\n borderBottom: `1px solid ${resolvedBorder}`,\n borderLeft: `1px solid ${resolvedBorder}`,\n borderBottomLeftRadius: '8px', padding: '10px',\n }}>\n <CardExpiryElement options={stripeElementStyle} />\n </div>\n <div style={{\n flex: 1, backgroundColor: cardInputBg,\n borderTop: 'none',\n borderRight: `1px solid ${resolvedBorder}`,\n borderBottom: `1px solid ${resolvedBorder}`,\n borderLeft: `1px solid ${resolvedBorder}`,\n 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,\n borderTop: `1px solid ${resolvedBorder}`,\n borderRight: `1px solid ${resolvedBorder}`,\n borderBottom: `1px solid ${resolvedBorder}`,\n borderLeft: `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,\n borderTop: `1px solid ${resolvedBorder}`,\n borderRight: `1px solid ${resolvedBorder}`,\n borderBottom: `1px solid ${resolvedBorder}`,\n borderLeft: `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 ...(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: resolvedPrimaryColor, color: 'white', border: 'none',\n borderRadius: resolvedBorderRadius,\n fontSize: bStyles.submitButtonFontSize ?? '1rem',\n fontWeight: 600,\n cursor: !formReady || isSubmitting ? 'not-allowed' : 'pointer',\n opacity: !formReady || isSubmitting ? 0.5 : 1,\n ...(bStyles.submitButton as React.CSSProperties),\n }}\n >\n {isSubmitting ? 'PROCESSING...' : submitLabel}\n </button>\n )}\n </div>\n );\n\n // ── Parent-side debug panels ──\n //\n // Surface the parent-gate decisions for each gateway on-screen so the most\n // common misconfigurations (session missing `gateways.paypal.publishableKey`,\n // Stripe filtering by currency, empty `enabledPaymentMethods`, …) are\n // visible without opening DevTools. When the gateway is disabled via its\n // `show*` prop we still emit a single-line marker so the absence is\n // obvious — silent omission used to look identical to a debug-off SDK.\n const gateDebugStyle: React.CSSProperties = {\n margin: 0,\n padding: '6px 8px',\n background: '#eef2ff',\n border: '1px solid #c7d2fe',\n borderRadius: 6,\n color: '#111827',\n font: '11px/1.35 ui-monospace, SFMono-Regular, Menlo, monospace',\n whiteSpace: 'pre-wrap',\n wordBreak: 'break-word',\n };\n // Reflect the session-response gateways. The DirectPayPal renderer is named\n // after the PayPal JS SDK path, so its \"enabled\" condition is the presence\n // of `gateways.paypal` upstream — surfaced here as `directPaypal.clientId`.\n // Likewise the Stripe parent gate is \"enabled\" when `gateways.stripe.publishable\\\n // Key` was wired up into a Stripe instance. Without either, the matching\n // renderer cannot run on this session regardless of the `show*` toggles, so\n // the panel collapses to the single \"not enabled\" marker.\n const renderDirectPaypalGateDebug = (testId: string) => {\n if (!debug) return null;\n if (!showPayPal || !directPaypalConfigured) {\n return (\n <pre data-testid={testId} style={gateDebugStyle}>\n {'FloPay/DirectPayPal-debug - not enabled'}\n </pre>\n );\n }\n return (\n <pre data-testid={testId} style={gateDebugStyle}>{[\n 'FloPay/DirectPayPal-debug (parent gate)',\n ` showPayPal=${showPayPal}`,\n ` directPaypalConfigured=${directPaypalConfigured}`,\n ` inAppBrowserDetected=${String(inAppBrowserDetected)}`,\n ` shouldRenderDirectPayPal=${shouldRenderDirectPayPal}`,\n ` shouldRenderStripePayPal=${shouldRenderStripePayPal}`,\n ` hasPaypalStripeInstance=${!!paypalStripeInstance}`,\n ].join('\\n')}</pre>\n );\n };\n const renderStripeGateDebug = (testId: string) => {\n if (!debug) return null;\n if (!showStripe || !stripeInstance) {\n return (\n <pre data-testid={testId} style={gateDebugStyle}>\n {'FloPay/Stripe-debug - not enabled'}\n </pre>\n );\n }\n return (\n <pre data-testid={testId} style={gateDebugStyle}>{[\n 'FloPay/Stripe-debug (parent gate)',\n ` showStripe=${showStripe}`,\n ` currency=${currency}`,\n ` amountInCents=${amountInCents}`,\n ` enabledPaymentMethods: ${JSON.stringify(enabledPaymentMethods ?? [])}`,\n ` enabledPaymentMethodsProvided=${hasEnabledMethodsPayload}`,\n ` hasEnabledMethods=${hasEnabledMethods}`,\n ` expressMethods: ${JSON.stringify(expressMethods)}`,\n ` walletExpressMethods: ${JSON.stringify(walletExpressMethods)}`,\n ` paymentElementMethods: ${JSON.stringify(paymentElementMethods)}`,\n ` paymentElementMethodsForCurrency: ${JSON.stringify(paymentElementMethodsForCurrency)}`,\n ` hasStripeInstance=${!!stripeInstance}`,\n ` shouldRenderWallets=${shouldRenderWallets}`,\n ` shouldRenderPaymentElement=${shouldRenderPaymentElement}`,\n ].join('\\n')}</pre>\n );\n };\n\n // ── APM 2nd-page derivations (shared by both layouts) ──\n // Lifted out of the layout branches so the default-layout (card form\n // visible inline) can also use the 2nd-page drill-in for input-form\n // APMs — without this, default-layout clicks on SEPA / EPS / iDEAL\n // were stuck on the local inline-expansion fallback path.\n const isApmView = viewState === 'apm-expanding' || viewState === 'apm-form' || viewState === 'apm-collapsing';\n const apmAnim = viewState === 'apm-expanding'\n ? `flopay-card-enter ${TRANSITION_MS}ms cubic-bezier(0, 0, 0.2, 1) both`\n : viewState === 'apm-collapsing'\n ? `flopay-card-exit ${TRANSITION_MS}ms cubic-bezier(0.4, 0, 0.2, 1) both`\n : undefined;\n // Per-method Elements options for the APM 2nd page. Built lazily by\n // method — the group only mounts while `viewState` is in the apm-*\n // family, so switching APMs (back → choose another) tears down the\n // previous Stripe Elements instance cleanly.\n const apmInlineOptions = expandedApmMethod ? {\n ...paymentElementBaseOptions,\n paymentMethodTypes: [expandedApmMethod],\n } as Parameters<typeof StripeElements>[0]['options'] : null;\n\n // ── Buttons layout ──\n if (layout === 'buttons') {\n const isButtonsView =\n viewState === 'buttons' ||\n viewState === 'expanding' ||\n viewState === 'apm-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 // The buttons panel slides out the same way whether we're going to the\n // card 2nd page or an APM 2nd page — same exit/enter animations so\n // the two drill-ins feel identical.\n const buttonsAnim = (viewState === 'expanding' || viewState === 'apm-expanding')\n ? `flopay-buttons-exit ${TRANSITION_MS}ms cubic-bezier(0.4, 0, 0.2, 1) both`\n : (viewState === 'collapsing' || viewState === 'apm-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\n data-testid=\"flopay-buttons-panel\"\n aria-hidden={!isButtonsView && !buttonsAnim ? true : undefined}\n 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 ? BUTTONS_PANEL_HIDDEN_STYLE : {}),\n ...(buttonsAnim ? { animation: buttonsAnim, pointerEvents: 'none' as const } : {}),\n }}>\n {renderDirectPaypalGateDebug('flopay-direct-paypal-gate-debug')}\n {renderStripeGateDebug('flopay-stripe-gate-debug')}\n {/* PayPal — Direct PayPal JS SDK when configured, otherwise Stripe-rendered PayPal */}\n {shouldRenderDirectPayPal && directPaypal && (\n <>\n {paypalDirectRetry && (\n <div\n data-testid=\"flopay-paypal-direct-retry-notice\"\n style={{\n padding: '8px 10px',\n background: '#fef3c7',\n border: '1px solid #fcd34d',\n borderRadius: 6,\n color: '#78350f',\n fontSize: 13,\n lineHeight: 1.4,\n }}\n >\n Please confirm your PayPal payment to complete checkout.\n </div>\n )}\n <DirectPayPalButton\n // Force a remount when the retry id changes so PayPal's\n // SDK picks up the new createOrder binding (render()\n // options aren't live-updatable). `key` matches the\n // existingOrderId effect-dep update on the child.\n key={paypalDirectRetry?.orderId ?? 'fresh'}\n sessionId={sessionId}\n nonce={nonce}\n billingApiUrl={resolvedBillingApiUrl}\n email={resolvedAccount.email}\n clientId={directPaypal.clientId}\n environment={directPaypal.environment}\n currency={currency.toUpperCase()}\n isSubscription={isSubscription}\n onTokenizedBody={dispatchTokenizedBody}\n onComplete={onComplete}\n onErrorChange={updateError}\n onDecline={onDecline}\n onButtonClick={onButtonClick}\n runBeforeButtonClick={runBeforeButtonClick}\n isProcessing={isSubmitting}\n onLoadStateChange={setDirectPaypalReady}\n session={session ?? null}\n existingOrderId={paypalDirectRetry?.orderId}\n debug={debug}\n />\n </>\n )}\n {shouldRenderStripePayPal && (\n <StripeElements stripe={paypalStripeInstance} options={paypalOptions}>\n <PayPalButtonInner\n sessionId={sessionId}\n nonce={nonce}\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 placeholderBorderRadius={(bStyles.cardButton?.borderRadius as string | number | undefined) ?? resolvedBorderRadius}\n />\n </StripeElements>\n )}\n\n {/* Wallets / express methods (Apple Pay / Google Pay / Link / Amazon Pay / Klarna) */}\n {shouldRenderWallets ? (\n <StripeElements stripe={stripeInstance} options={walletOptions}>\n <WalletButtonInner\n sessionId={sessionId}\n nonce={nonce}\n email={resolvedAccount.email}\n billingApiUrl={resolvedBillingApiUrl}\n expressMethods={walletExpressMethods}\n onTokenizedBody={dispatchTokenizedBody}\n onErrorChange={updateError}\n onButtonClick={onButtonClick}\n onDecline={onDecline}\n runBeforeButtonClick={runBeforeButtonClick}\n onLoadStateChange={setWalletLoadState}\n placeholderBorderRadius={(bStyles.cardButton?.borderRadius as string | number | undefined) ?? resolvedBorderRadius}\n />\n </StripeElements>\n ) : shouldShowWallets ? (\n <div style={{ height: DEFAULT_BUTTONS_LAYOUT_BUTTON_HEIGHT, borderRadius: (bStyles.cardButton?.borderRadius as string | number | undefined) ?? resolvedBorderRadius, background: '#e5e7eb', animation: 'flopay-pulse 1.5s ease-in-out infinite' }} />\n ) : null}\n\n {/* PaymentElement region — Cash App Pay / Affirm / iDEAL / SEPA … */}\n {shouldRenderPaymentElement && (\n <StripePaymentElementInner\n sessionId={sessionId}\n nonce={nonce}\n email={resolvedAccount.email}\n billingName={[resolvedAccount.firstName, resolvedAccount.lastName].filter(Boolean).join(' ').trim() || undefined}\n billingApiUrl={resolvedBillingApiUrl}\n paymentElementMethods={paymentElementMethodsForCurrency}\n stripeInstance={stripeInstance}\n paymentElementBaseOptions={paymentElementBaseOptions}\n onTokenizedBody={dispatchTokenizedBody}\n onErrorChange={updateError}\n onButtonClick={onButtonClick}\n onDecline={onDecline}\n runBeforeButtonClick={runBeforeButtonClick}\n onLoadStateChange={setPaymentElementLoadState}\n isProcessing={isSubmitting}\n submitButtonColor={resolvedPrimaryColor}\n submitButtonBorderRadius={resolvedBorderRadius}\n submitButtonStyle={bStyles.submitButton as React.CSSProperties | undefined}\n // Input-form methods (SEPA / EPS / iDEAL / Bacs) drill\n // into a 2nd-page panel rendered alongside the card\n // form below. `StripePaymentElementInner` itself only\n // renders the tile-button row; the parent owns the\n // navigation state machine.\n onExpandApm={expandToApm}\n expandedApmMethod={expandedApmMethod}\n themeId={theme}\n // The `buttonAppearance` override is only used as a\n // *fallback* — `STRIPE_METHOD_MATRIX[<method>].theme`\n // takes precedence inside the tile, so brand-styled\n // methods (Cash App green, Klarna pink, …) keep their\n // brand colors regardless of the bundle's `cardButton`\n // styling. Methods with no `theme` entry pick up the\n // bundle's neutral tile here.\n buttonAppearance={{\n backgroundColor: bStyles.cardButton?.backgroundColor as string | undefined,\n borderColor: bStyles.cardInputBorder,\n textColor: bStyles.cardButton?.color as string | undefined,\n borderRadius: bStyles.cardButton?.borderRadius as string | number | undefined,\n }}\n />\n )}\n\n {/* Credit / Debit Card button — gated on `showStripe` so the\n PayPal-only flow doesn't expose an unusable card option.\n Themed: `derivePrimaryTileStyle` flips the base from white\n + grey border (classic) to a primary-colored fill that\n mirrors the theme's submit/CTA action. */}\n {showStripe && (\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 // `bStyles.cardButton` first — supplies the bundle's\n // padding / typography / border-radius — then the\n // primary surface overrides on top, so the card button\n // ends up wearing the *submit* button's colours rather\n // than the bundle's neutral white-tile `cardButton`\n // colours. Without this order flip, every non-classic\n // bundle's `cardButton.backgroundColor` was winning\n // over the primary fill we just derived above it.\n ...bStyles.cardButton as React.CSSProperties,\n ...derivePrimaryTileStyle({\n themeBundle,\n resolvedPrimaryColor,\n resolvedBorderRadius,\n submitButtonStyle: bStyles.submitButton as React.CSSProperties | undefined,\n }),\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 position: 'relative',\n opacity: isSubmitting ? 0.6 : 1,\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\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 — gated on `showStripe` (PayPal-only flow hides it). */}\n {showStripe && 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\n {/* APM 2nd page — mirrors the card-form 2nd page exactly:\n same gridArea, same back-button chrome, same enter/exit\n animations. The only differences are the title (method\n display name) and the body (single-method Stripe\n PaymentElement instead of the split-card fields). */}\n {showStripe && isApmView && expandedApmMethod && apmInlineOptions && stripeInstance && (\n <div style={{\n gridArea: '1 / 1',\n ...(apmAnim ? { animation: apmAnim } : {}),\n ...(viewState === 'apm-collapsing' ? { pointerEvents: 'none' as const } : {}),\n }}>\n <div style={{\n backgroundColor: cardBg, borderRadius: containerRadius,\n ...containerOverrides,\n padding: containerPadding,\n }}>\n {/* Header: back button + method-name title — pixel-for-\n pixel the same chrome as the card-form header. */}\n <div style={{\n display: 'flex', alignItems: 'center', padding: '0.75rem 0 0.625rem',\n }}>\n <button\n type=\"button\"\n data-testid=\"flopay-apm-back-button\"\n onClick={collapseFromApm}\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 <div style={{\n flex: 1, textAlign: 'center', fontWeight: 600,\n fontSize: bStyles.titleFontSize ?? '1.05rem',\n color: resolvedTitleColor, paddingRight: 80,\n ...bStyles.title as React.CSSProperties,\n }}>\n {`Pay with ${getStripeMethodDisplayName(expandedApmMethod)}`}\n </div>\n </div>\n\n {/* Per-method Elements group: keyed by method so switching\n APMs unmounts the previous group cleanly. */}\n <StripeElements\n key={expandedApmMethod}\n stripe={stripeInstance}\n options={apmInlineOptions}\n >\n <StripeMethodInlineForm\n method={expandedApmMethod}\n sessionId={sessionId}\n nonce={nonce}\n email={resolvedAccount.email}\n billingName={[resolvedAccount.firstName, resolvedAccount.lastName].filter(Boolean).join(' ').trim() || undefined}\n billingApiUrl={resolvedBillingApiUrl}\n onTokenizedBody={dispatchTokenizedBody}\n onErrorChange={updateError}\n onDecline={onDecline}\n onCancel={collapseFromApm}\n runBeforeButtonClick={runBeforeButtonClick}\n onButtonClick={onButtonClick}\n isProcessing={isSubmitting}\n submitButtonColor={resolvedPrimaryColor}\n submitButtonBorderRadius={resolvedBorderRadius}\n submitButtonStyle={bStyles.submitButton as React.CSSProperties | undefined}\n />\n </StripeElements>\n </div>\n </div>\n )}\n </div>\n </form>\n );\n }\n\n // ── Default layout ──\n // When an input-form APM is expanded, render *only* its 2nd-page panel\n // (back button + scoped PaymentElement + Pay button) — the wallet row,\n // APM tiles, divider and card form all step aside so the buyer's focus\n // is on completing the inline form. Hitting \"Go back\" restores the\n // normal layout. Same chrome as the buttons-layout 2nd page so the\n // experience is consistent across both layouts.\n if (isApmView && expandedApmMethod && apmInlineOptions && stripeInstance && showStripe) {\n return (\n <form onSubmit={handleSubmit} className={className} style={{ position: 'relative' }}>\n <FloPayKeyframes />\n {overlayStatus && <ProcessingOverlay status={overlayStatus} errorMessage={displayError} />}\n <div style={{\n ...(apmAnim ? { animation: apmAnim } : {}),\n ...(viewState === 'apm-collapsing' ? { pointerEvents: 'none' as const } : {}),\n }}>\n <div style={{\n backgroundColor: cardBg, borderRadius: containerRadius,\n ...containerOverrides,\n padding: containerPadding,\n }}>\n {/* Back-button chrome — same circle icon + theme back-button\n styling as the card form 2nd page in the buttons layout. */}\n <div style={{\n display: 'flex', alignItems: 'center', padding: '0.75rem 0 0.625rem',\n }}>\n <button\n type=\"button\"\n data-testid=\"flopay-apm-back-button-default\"\n onClick={collapseFromApm}\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 <div style={{\n flex: 1, textAlign: 'center', fontWeight: 600,\n fontSize: bStyles.titleFontSize ?? '1.05rem',\n color: resolvedTitleColor, paddingRight: 80,\n ...bStyles.title as React.CSSProperties,\n }}>\n {`Pay with ${getStripeMethodDisplayName(expandedApmMethod)}`}\n </div>\n </div>\n\n <StripeElements\n key={expandedApmMethod}\n stripe={stripeInstance}\n options={apmInlineOptions}\n >\n <StripeMethodInlineForm\n method={expandedApmMethod}\n sessionId={sessionId}\n nonce={nonce}\n email={resolvedAccount.email}\n billingName={[resolvedAccount.firstName, resolvedAccount.lastName].filter(Boolean).join(' ').trim() || undefined}\n billingApiUrl={resolvedBillingApiUrl}\n onTokenizedBody={dispatchTokenizedBody}\n onErrorChange={updateError}\n onDecline={onDecline}\n onCancel={collapseFromApm}\n runBeforeButtonClick={runBeforeButtonClick}\n onButtonClick={onButtonClick}\n isProcessing={isSubmitting}\n submitButtonColor={resolvedPrimaryColor}\n submitButtonBorderRadius={resolvedBorderRadius}\n submitButtonStyle={bStyles.submitButton as React.CSSProperties | undefined}\n />\n </StripeElements>\n </div>\n </div>\n </form>\n );\n }\n\n return (\n <form onSubmit={handleSubmit} className={className} style={{ position: 'relative' }}>\n <FloPayKeyframes />\n {overlayStatus && <ProcessingOverlay status={overlayStatus} errorMessage={displayError} />}\n\n {/* Express-checkout row — flex column with `gap` matches the buttons\n layout, so wallet/PayPal/Stripe-PayPal always sit `0.5rem` apart\n regardless of which combination is rendered. Order matches the\n buttons layout: PayPal first, then wallets. */}\n <div style={{ display: 'flex', flexDirection: 'column', gap: '0.5rem' }}>\n {renderDirectPaypalGateDebug('flopay-direct-paypal-gate-debug-default')}\n {renderStripeGateDebug('flopay-stripe-gate-debug-default')}\n {/* PayPal — Direct PayPal JS SDK when configured, otherwise Stripe-rendered PayPal */}\n {shouldRenderDirectPayPal && directPaypal && (\n <>\n {paypalDirectRetry && (\n <div\n data-testid=\"flopay-paypal-direct-retry-notice-default\"\n style={{\n padding: '8px 10px',\n background: '#fef3c7',\n border: '1px solid #fcd34d',\n borderRadius: 6,\n color: '#78350f',\n fontSize: 13,\n lineHeight: 1.4,\n }}\n >\n Please confirm your PayPal payment to complete checkout.\n </div>\n )}\n <DirectPayPalButton\n // Remount when retry id changes so PayPal SDK picks up the\n // new createOrder binding.\n key={paypalDirectRetry?.orderId ?? 'fresh'}\n sessionId={sessionId}\n nonce={nonce}\n billingApiUrl={resolvedBillingApiUrl}\n email={resolvedAccount.email}\n clientId={directPaypal.clientId}\n environment={directPaypal.environment}\n currency={currency.toUpperCase()}\n isSubscription={isSubscription}\n onTokenizedBody={dispatchTokenizedBody}\n onComplete={onComplete}\n onErrorChange={updateError}\n onDecline={onDecline}\n onButtonClick={onButtonClick}\n runBeforeButtonClick={runBeforeButtonClick}\n isProcessing={isSubmitting}\n onLoadStateChange={setDirectPaypalReady}\n session={session ?? null}\n existingOrderId={paypalDirectRetry?.orderId}\n debug={debug}\n />\n </>\n )}\n {shouldRenderStripePayPal && (\n <StripeElements stripe={paypalStripeInstance} options={paypalOptions}>\n <PayPalButtonInner\n sessionId={sessionId}\n nonce={nonce}\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 placeholderBorderRadius={(bStyles.cardButton?.borderRadius as string | number | undefined) ?? resolvedBorderRadius}\n />\n </StripeElements>\n )}\n\n {/* Wallet / express buttons — own Stripe Elements instance */}\n {shouldRenderWallets && (\n <StripeElements stripe={stripeInstance} options={walletOptions}>\n <WalletButtonInner\n sessionId={sessionId}\n nonce={nonce}\n email={resolvedAccount.email}\n billingApiUrl={resolvedBillingApiUrl}\n expressMethods={walletExpressMethods}\n onTokenizedBody={dispatchTokenizedBody}\n onErrorChange={updateError}\n onButtonClick={onButtonClick}\n onDecline={onDecline}\n runBeforeButtonClick={runBeforeButtonClick}\n onLoadStateChange={setWalletLoadState}\n placeholderBorderRadius={(bStyles.cardButton?.borderRadius as string | number | undefined) ?? resolvedBorderRadius}\n />\n </StripeElements>\n )}\n\n {/* PaymentElement region — non-express APMs (Cash App Pay, Klarna, iDEAL, SEPA, …) */}\n {shouldRenderPaymentElement && (\n <StripePaymentElementInner\n sessionId={sessionId}\n nonce={nonce}\n email={resolvedAccount.email}\n billingName={[resolvedAccount.firstName, resolvedAccount.lastName].filter(Boolean).join(' ').trim() || undefined}\n billingApiUrl={resolvedBillingApiUrl}\n paymentElementMethods={paymentElementMethodsForCurrency}\n stripeInstance={stripeInstance}\n paymentElementBaseOptions={paymentElementBaseOptions}\n onTokenizedBody={dispatchTokenizedBody}\n onErrorChange={updateError}\n onButtonClick={onButtonClick}\n onDecline={onDecline}\n runBeforeButtonClick={runBeforeButtonClick}\n onLoadStateChange={setPaymentElementLoadState}\n isProcessing={isSubmitting}\n submitButtonColor={resolvedPrimaryColor}\n submitButtonBorderRadius={resolvedBorderRadius}\n submitButtonStyle={bStyles.submitButton as React.CSSProperties | undefined}\n themeId={theme}\n // Route input-form APM clicks (SEPA / EPS / iDEAL / Bacs)\n // through the parent's `viewState` machine — same 2nd-page\n // pattern as the buttons-layout, just without the in/out\n // transition since the default layout doesn't pre-render the\n // panel alongside an animated buttons row.\n onExpandApm={expandToApm}\n expandedApmMethod={expandedApmMethod}\n buttonAppearance={{\n backgroundColor: bStyles.cardButton?.backgroundColor as string | undefined,\n borderColor: bStyles.cardInputBorder,\n textColor: bStyles.cardButton?.color as string | undefined,\n borderRadius: bStyles.cardButton?.borderRadius as string | number | undefined,\n }}\n />\n )}\n </div>\n\n {/* Divider between wallet/PayPal buttons and card fields — only when\n the card form is actually going to render. */}\n {showStripe && (shouldDisplayWalletRow || shouldDisplayPayPalRow || shouldDisplayPaymentElementRow) && (\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 {showStripe && 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 Stripe `FloPay` instance dedicated to the Stripe-rendered\n * PayPal fallback, or `null` if PayPal is disabled for this session. Direct\n * PayPal (`gateways.paypal`) does not use this instance.\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 inputProducts = params.products ?? [\n ...(params.subscriptions ?? []).map((s) => ({\n type: 'subscription' as const,\n code: s.code ?? s.providerPlanId,\n name: s.subscriptionName ?? s.providerPlanName ?? s.code ?? s.providerPlanId ?? null,\n quantity: s.quantity ?? 1,\n totalAmount: s.totalAmount,\n overrideAmount: s.overrideAmount,\n currency: s.currency,\n metadata: s.metadata,\n })),\n ...(params.items ?? []).map((i) => ({\n type: 'item' as const,\n code: i.code ?? i.providerItemId,\n name: i.itemName ?? i.providerItemName ?? i.code ?? i.providerItemId ?? null,\n quantity: i.quantity ?? 1,\n totalAmount: i.totalAmount,\n overrideAmount: i.overrideAmount,\n currency: i.currency,\n metadata: i.metadata,\n })),\n ];\n\n const totalAmount = inputProducts.reduce(\n (sum, p) => sum + ((p.overrideAmount ?? p.totalAmount) ?? 0),\n 0,\n );\n const currency = params.currency\n ?? inputProducts.find((p) => p.currency)?.currency\n ?? 'USD';\n\n return {\n id: '',\n clientSecret: '',\n mode: inputProducts.some((p) => p.type === 'subscription') ? 'subscription' : '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 products: inputProducts.map((p, idx) => ({\n uuid: `synthetic-${p.type}-${idx}`,\n checkoutSessionId: '',\n type: p.type,\n code: p.code,\n name: p.name ?? null,\n quantity: p.quantity ?? 1,\n totalAmount: p.totalAmount,\n overrideAmount: p.overrideAmount ?? null,\n currency: p.currency ?? currency,\n metadata: p.metadata ?? null,\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\nconst FRIENDLY_MESSAGE_OVERRIDES: Array<{ match: RegExp; replacement: string }> = [\n {\n match: /^paypal authorization required\\.?$/i,\n replacement: 'For your additional security, please re-authenticate this payment via PayPal.',\n },\n];\n\nexport function applyFriendlyMessageOverride(message: string | undefined | null): string | undefined {\n if (typeof message !== 'string') return message ?? undefined;\n const trimmed = message.trim();\n if (!trimmed) return message;\n for (const { match, replacement } of FRIENDLY_MESSAGE_OVERRIDES) {\n if (match.test(trimmed)) return replacement;\n }\n return message;\n}\n\nexport function buildFloPayApiError(\n payload: ApiErrorPayload,\n fallbackMessage: string,\n): FloPayError {\n const nestedError = isRecord(payload?.error) ? payload.error : null;\n const rawMessage =\n readString(payload, 'message') ??\n readString(nestedError, 'message') ??\n fallbackMessage;\n const message = applyFriendlyMessageOverride(rawMessage) ?? rawMessage;\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 React, { useEffect, useMemo, useRef, useState } from 'react';\nimport { loadScript } from '@paypal/paypal-js';\nimport type { PayPalNamespace } from '@paypal/paypal-js';\nimport { PaymentAPI } from '@flopay/js';\nimport type {\n CheckoutButtonMethod,\n CheckoutSession,\n DeclineEvent,\n GatewayEnvironment,\n InlineSessionPatch,\n PaymentResult,\n TokenizedBody,\n} from '@flopay/shared';\nimport { FloPayError, normalizeGatewayEnvironment } from '@flopay/shared';\nimport { applyFriendlyMessageOverride, buildDeclineEvent } from './checkout-utils.js';\n\nconst DEFAULT_BUTTON_HEIGHT = 45;\n\n/**\n * Overrides that `SplitCardForm`'s tokenized-body dispatcher uses to apply a\n * `runBeforeButtonClick` patch to the in-flight processPayment call. Kept in\n * sync structurally with `TokenizedBodyOverrides` in `split-card-form.tsx`.\n */\nexport interface DirectPayPalTokenizedOverrides {\n accountPatch?: InlineSessionPatch['account'];\n sessionId?: string;\n}\n\n/**\n * Internal handler signature aligned with `SplitCardForm`'s tokenized-body\n * dispatcher. Direct PayPal completes via the backend's process endpoint and\n * never produces a Stripe PaymentIntent, so we still forward a synthetic\n * `TokenizedBody` describing the captured order, optionally with the\n * session/account patch captured at click-time.\n */\nexport type DirectPayPalTokenizedHandler = (\n body: TokenizedBody,\n overrides?: DirectPayPalTokenizedOverrides,\n) => void;\n\n/** Click-time `runBeforeButtonClick` result, structurally compatible with `SplitCardForm`. */\nexport interface DirectPayPalBeforeButtonClickResult {\n proceed: boolean;\n accountPatch?: InlineSessionPatch['account'];\n sessionId?: string;\n}\n\n/**\n * Click-time gate. Mirrors `RunBeforeButtonClick` in `SplitCardForm`: lets the\n * consumer patch the session/account before PayPal creates the order, and lets\n * them abort the click entirely by returning `proceed: false`.\n */\nexport type DirectPayPalRunBeforeButtonClick = (\n method: CheckoutButtonMethod,\n) => Promise<DirectPayPalBeforeButtonClickResult>;\n\nexport interface DirectPayPalButtonProps {\n /** Checkout session ID. */\n sessionId: string;\n /**\n * Session-bound checkout token returned by session creation. Forwarded as\n * `x-checkout-session-token` on every continuation request — required by\n * post-#640 backends. `FloPayCheckout` plumbs this prop automatically.\n */\n nonce?: string;\n /** Billing API base URL. */\n billingApiUrl: string;\n /** Buyer email. */\n email?: string;\n /** PayPal client identifier (`gateways.paypal.publishableKey`). */\n clientId: string;\n /** Gateway environment, drives the sandbox/live SDK script. */\n environment?: GatewayEnvironment;\n /** ISO 4217 currency code. */\n currency: string;\n /** Whether the session is a subscription (drives intent + flow selection). */\n isSubscription: boolean;\n /**\n * If provided, called with the tokenized body once PayPal capture\n * completes. When omitted, the component processes payment internally.\n */\n onTokenizedBody?: DirectPayPalTokenizedHandler;\n /** Called when the full self-contained payment flow succeeds. */\n onComplete?: (result: PaymentResult) => void;\n /** Called when an error occurs. */\n onErrorChange?: (error: string | null) => void;\n /** Decline emitter (mirrors SplitCardForm semantics). */\n onDecline?: (decline: DeclineEvent) => void;\n /** External processing state. */\n isProcessing?: boolean;\n /** Notify the parent of the loading state for placeholder swapping. */\n onLoadStateChange?: (ready: boolean) => void;\n /** Tracks button-click for analytics. */\n onButtonClick?: (method: CheckoutButtonMethod) => void;\n /**\n * Click-time gate (runs before PayPal creates the order). When provided, the\n * returned patch is applied to the in-flight create-intent and tokenized\n * dispatch so callers using `onBeforeButtonClick` see the same session/email\n * the Stripe-rendered PayPal flow does.\n */\n runBeforeButtonClick?: DirectPayPalRunBeforeButtonClick;\n /** Backing session — used for self-contained accountData population. */\n session?: CheckoutSession | null;\n /**\n * Pre-existing PayPal Order id (or Subscription id when `isSubscription` is\n * true) to bind the button to. When set, the button skips its usual\n * `POST /v1/checkouts/payments/intents` round-trip on click and feeds this\n * id straight into PayPal's create-order / create-subscription callback.\n *\n * Used by `SplitCardForm`'s `paypal_direct_required` retry path: backend\n * creates a fresh PayPal order after a stalled process attempt and returns\n * its id; the SDK re-renders this button bound to that id so the buyer can\n * confirm with one more click without the backend re-creating the order on\n * each retry.\n *\n * Changing this value remounts the PayPal SDK so the new createOrder\n * binding takes effect (PayPal's render() options aren't live-updatable).\n */\n existingOrderId?: string;\n /**\n * When true, renders an on-screen lifecycle tracer panel above the button\n * (mount, loadScript, eligibility, render, errors). Intended for debugging\n * in-app browsers (Facebook IAB, etc.) where remote console access is\n * impractical. Off by default — leave disabled in production.\n */\n debug?: boolean;\n}\n\ninterface CreatePaypalOrderResponseData {\n /** Order ID for one-time payments. */\n id?: string;\n /** Approval URL the buyer is redirected to (in-app browser flow). */\n approveUrl?: string;\n}\n\n/**\n * Direct PayPal renderer powered by the official PayPal JS SDK.\n *\n * Renders inside Facebook / Instagram / Meta in-app browsers where Stripe's\n * PayPal ExpressCheckoutElement breaks. Selection between this and the Stripe-\n * rendered PayPal happens at the caller site based on whether the session\n * advertises `gateways.paypal.publishableKey`.\n */\nexport function DirectPayPalButton({\n sessionId,\n nonce,\n billingApiUrl,\n email,\n clientId,\n environment,\n currency,\n isSubscription,\n onTokenizedBody,\n onComplete,\n onErrorChange,\n onDecline,\n isProcessing = false,\n onLoadStateChange,\n onButtonClick,\n runBeforeButtonClick,\n session,\n existingOrderId,\n debug = false,\n}: DirectPayPalButtonProps): React.ReactElement | null {\n const containerRef = useRef<HTMLDivElement | null>(null);\n const [ready, setReady] = useState(false);\n // `failed` flips to true when PayPal can't load/render at all — SDK script\n // failure, ineligibility, render rejection, or a zoid lifecycle teardown.\n // It hides the loading placeholder (and the whole row) so users don't see\n // a perpetual skeleton when PayPal is unavailable.\n const [failed, setFailed] = useState(false);\n const [submitting, setSubmitting] = useState(false);\n const baseUrl = useMemo(() => billingApiUrl.replace(/\\/+$/, ''), [billingApiUrl]);\n\n // Optional on-screen lifecycle tracer, gated by the `debug` prop. Each\n // lifecycle stage appends a line. Use this for IAB debugging (Facebook,\n // Instagram, TikTok, etc.) where console access is impractical. When\n // `debug` is false the writes are no-ops, so there's no state churn or\n // memory cost in production.\n const [debugLines, setDebugLines] = useState<string[]>([]);\n const appendDebug = (line: string) => {\n if (!debug) return;\n setDebugLines((prev) => [...prev, `${new Date().toISOString().slice(11, 23)} ${line}`]);\n };\n\n // Ref-pin every callback so the render effect below can read the latest\n // handler without listing them as dependencies. Without this, an unstable\n // parent callback (e.g. an inline `onTokenizedBody={(body) => …}`) re-fires\n // the effect on every render, which tears down PayPal's buttons mid-render\n // and surfaces as \"Detected container element removed from DOM\".\n const onTokenizedBodyRef = useRef(onTokenizedBody);\n const onCompleteRef = useRef(onComplete);\n const onErrorChangeRef = useRef(onErrorChange);\n const onDeclineRef = useRef(onDecline);\n const onButtonClickRef = useRef(onButtonClick);\n const onLoadStateChangeRef = useRef(onLoadStateChange);\n const runBeforeButtonClickRef = useRef(runBeforeButtonClick);\n const sessionRef = useRef(session);\n const emailRef = useRef(email);\n const nonceRef = useRef(nonce);\n // Captures the latest `runBeforeButtonClick` patch so the in-flight\n // create-intent and tokenized dispatch can use the patched sessionId/email\n // even though the PayPal SDK callbacks closed over the original props at\n // mount-time. Cleared on cancel/teardown to avoid stale patches leaking into\n // a later click.\n const beforeClickRef = useRef<{\n sessionId?: string;\n accountPatch?: InlineSessionPatch['account'];\n } | null>(null);\n useEffect(() => { onTokenizedBodyRef.current = onTokenizedBody; }, [onTokenizedBody]);\n useEffect(() => { onCompleteRef.current = onComplete; }, [onComplete]);\n useEffect(() => { onErrorChangeRef.current = onErrorChange; }, [onErrorChange]);\n useEffect(() => { onDeclineRef.current = onDecline; }, [onDecline]);\n useEffect(() => { onButtonClickRef.current = onButtonClick; }, [onButtonClick]);\n useEffect(() => { onLoadStateChangeRef.current = onLoadStateChange; }, [onLoadStateChange]);\n useEffect(() => { runBeforeButtonClickRef.current = runBeforeButtonClick; }, [runBeforeButtonClick]);\n useEffect(() => { sessionRef.current = session; }, [session]);\n useEffect(() => { emailRef.current = email; }, [email]);\n useEffect(() => { nonceRef.current = nonce; }, [nonce]);\n\n useEffect(() => {\n // Parent's `directPaypalReady` drives the divider visibility — keep it\n // false while we're still trying, true once PayPal is interactive, and\n // false again if we've definitively failed.\n onLoadStateChangeRef.current?.(ready && !failed);\n }, [ready, failed]);\n\n // Collapse FloPay's `stage`/`production` aliases down to the gateway-native\n // `sandbox`/`live` pair PayPal's SDK actually understands. Done up-front so\n // every downstream check (the debug trace, the loadScript options, the\n // dataNamespace branch) sees a single canonical value.\n const normalizedEnv = normalizeGatewayEnvironment(environment);\n\n useEffect(() => {\n // FloPay/DirectPayPal-debug\n const maskedClient = clientId ? `${clientId.slice(0, 6)}…(len ${clientId.length})` : '(empty)';\n const ua = typeof navigator !== 'undefined' ? navigator.userAgent : '(no navigator)';\n appendDebug(`mount clientId=${maskedClient} env=${environment ?? '(unset)'}→${normalizedEnv ?? 'live'} ccy=${currency} sub=${isSubscription}`);\n appendDebug(`ua=${ua.slice(0, 80)}${ua.length > 80 ? '…' : ''}`);\n\n if (!clientId) {\n appendDebug('FAIL: clientId empty — gateway misconfigured');\n setFailed(true);\n // Silent on-screen: PayPal row simply doesn't render. Other gateways\n // (card, wallets) stay interactive. See markRenderFailed for the same\n // policy applied to script-load/ineligibility/render failures.\n console.error('[FloPay] DirectPayPal: clientId empty — gateway misconfigured');\n return;\n }\n if (!containerRef.current) {\n appendDebug('FAIL: containerRef not attached');\n return;\n }\n\n let cancelled = false;\n // `activeButtons` is only set AFTER `render()` resolves successfully —\n // calling `buttons.close()` while zoid is still mounting the iframe\n // surfaces as \"zoid destroyed all components\" + a stuck placeholder. The\n // render `.then` handler handles the \"unmounted during render\" case\n // itself (sees `cancelled` and closes its own buttons), so cleanup only\n // needs to handle fully-mounted teardown.\n let activeButtons: { close: () => Promise<void> } | null = null;\n // Tracks whether `render()` has resolved. PayPal's `onError` fires for\n // both render-time failures (SDK script error, ineligibility, iframe\n // mount issues) AND runtime failures after the user clicks (e.g.\n // `createOrder` rejection bubbling up from the backend). Render-time\n // failures should hide the button — runtime failures must not, or the\n // user loses the ability to retry.\n let rendered = false;\n const container = containerRef.current;\n\n // Diagnostics owned by the effect so cleanup can tear them down. The\n // observer + watchdog snapshot the DOM around `buttons.render()` so we\n // can see *why* a render hangs (CAPTCHA challenge swap, zero-size parent,\n // hidden tab) — render() never resolves or rejects in those cases, so\n // the existing trace dead-ends at \"render:start\" with no further signal.\n let containerObserver: MutationObserver | null = null;\n let perfObserver: PerformanceObserver | null = null;\n const watchdogTimers: ReturnType<typeof setTimeout>[] = [];\n const formatDims = (el: Element | null): string => {\n if (!el || typeof el.getBoundingClientRect !== 'function') return '(no rect)';\n const rect = el.getBoundingClientRect();\n return `${Math.round(rect.width)}×${Math.round(rect.height)}`;\n };\n const classifyIframeSrc = (raw: string | null): string => {\n if (!raw) return '(empty)';\n try {\n const url = new URL(raw, typeof window !== 'undefined' ? window.location.href : 'https://localhost');\n const path = url.pathname.toLowerCase();\n if (path.includes('checkcaptcha') || path.includes('captcha')) return `CAPTCHA(${url.host}${path})`;\n if (path.includes('risk') || path.includes('challenge')) return `RISK(${url.host}${path})`;\n if (path.includes('smart/buttons')) return `smart-buttons(${url.host})`;\n return `${url.host}${path}`.slice(0, 100);\n } catch {\n return raw.slice(0, 80);\n }\n };\n // Describe an iframe's loaded content: zoid uses both `src` (network) and\n // `srcdoc` (inline HTML, no network roundtrip). When both are empty the\n // iframe is genuinely blank — which means zoid's content injection never\n // completed and is a strong signal of a postMessage handshake failure.\n const describeIframe = (frame: Element): string => {\n const src = frame.getAttribute('src');\n const srcdoc = frame.getAttribute('srcdoc');\n const name = frame.getAttribute('name');\n const sandbox = frame.getAttribute('sandbox');\n const parts: string[] = [];\n if (src) parts.push(`src=${classifyIframeSrc(src)}`);\n if (srcdoc) parts.push(`srcdoc[${srcdoc.length}ch]`);\n if (!src && !srcdoc) parts.push('src=(empty) srcdoc=(empty)');\n if (name) parts.push(`name=${name.slice(0, 40)}`);\n if (sandbox !== null) parts.push(`sandbox=\"${sandbox.slice(0, 40)}\"`);\n return parts.join(' ');\n };\n // Peek inside an iframe's actual rendered document. Zoid uses\n // `contentDocument.write()` for same-origin frames, which doesn't update\n // src/srcdoc attributes — so the attributes can lie. This is the\n // ground-truth: if body has children, content IS there (and the issue is\n // render() not resolving); if body is empty, zoid never wrote into it\n // (handshake failure). Cross-origin throws, which is itself useful — it\n // means PayPal navigated the frame to its own origin (network worked).\n const inspectFrameContent = (frame: Element): string => {\n if (!(frame instanceof HTMLIFrameElement)) return '';\n try {\n const cd = frame.contentDocument;\n if (!cd) return 'cd=null';\n const bodyChildren = cd.body?.children.length ?? 0;\n const bodyLen = cd.body?.innerHTML.length ?? 0;\n const headLen = cd.head?.innerHTML.length ?? 0;\n return `cd=same-origin readyState=${cd.readyState} body[${bodyChildren}children,${bodyLen}ch] head[${headLen}ch]`;\n } catch (err) {\n return `cd=cross-origin(${(err as Error).message.slice(0, 30)})`;\n }\n };\n // Capture window-scoped errors and promise rejections while the lifecycle\n // is in flight. PayPal's zoid framework swallows postMessage / storage\n // failures into the console rather than rejecting render(), so capturing\n // these is often the only way to see the real cause of a hung render.\n const errorMessages: string[] = [];\n const onWindowError = (ev: ErrorEvent) => {\n const msg = ev.message ?? String(ev.error ?? '(no message)');\n if (msg && (msg.toLowerCase().includes('paypal') || msg.toLowerCase().includes('zoid') || msg.toLowerCase().includes('postrobot') || msg.toLowerCase().includes('storage'))) {\n appendDebug(`window:error ${msg.slice(0, 140)}`);\n errorMessages.push(msg);\n }\n };\n const onUnhandledRejection = (ev: PromiseRejectionEvent) => {\n const reason = ev.reason instanceof Error ? ev.reason.message : String(ev.reason ?? '(no reason)');\n if (reason && (reason.toLowerCase().includes('paypal') || reason.toLowerCase().includes('zoid') || reason.toLowerCase().includes('postrobot') || reason.toLowerCase().includes('storage'))) {\n appendDebug(`window:rejection ${reason.slice(0, 140)}`);\n errorMessages.push(reason);\n }\n };\n if (debug && typeof window !== 'undefined') {\n window.addEventListener('error', onWindowError);\n window.addEventListener('unhandledrejection', onUnhandledRejection);\n }\n // Network telemetry: every paypal.com resource entry gets logged with\n // duration. If we see zero entries, an ad blocker / DNS filter / firewall\n // is intercepting before requests even hit the network. If we see hung\n // duration=0 entries, the request started but never completed (common\n // with privacy extensions that hold but don't reject requests).\n const paypalRequestCount = { value: 0 };\n if (debug && typeof PerformanceObserver !== 'undefined') {\n try {\n perfObserver = new PerformanceObserver((list) => {\n for (const entry of list.getEntries()) {\n if (!entry.name.toLowerCase().includes('paypal')) continue;\n paypalRequestCount.value += 1;\n const dur = Math.round(entry.duration);\n appendDebug(`net ${dur}ms ${entry.name.slice(0, 90)}`);\n }\n });\n perfObserver.observe({ type: 'resource', buffered: true });\n } catch {\n // Older browsers may not support PerformanceObserver with type/buffered\n // syntax — fail silently, the other diagnostics still work.\n }\n }\n const stopDiagnostics = () => {\n containerObserver?.disconnect();\n containerObserver = null;\n perfObserver?.disconnect();\n perfObserver = null;\n while (watchdogTimers.length) clearTimeout(watchdogTimers.pop()!);\n if (debug && typeof window !== 'undefined') {\n window.removeEventListener('error', onWindowError);\n window.removeEventListener('unhandledrejection', onUnhandledRejection);\n }\n };\n\n /**\n * Zoid (PayPal's iframe framework) emits \"zoid destroyed all components\"\n * and similar lifecycle messages through `onError` whenever its\n * components are torn down — page navigation, force reload, React 18\n * StrictMode dev mount/unmount, or a parent unmounting mid-render.\n * Those events aren't payment errors; surfacing them in our error\n * banner misleads users and blocks them from completing checkout.\n */\n const isZoidLifecycleMessage = (message: string | undefined): boolean => {\n if (!message) return false;\n const lower = message.toLowerCase();\n return lower.includes('zoid destroyed')\n || lower.includes('destroyed all components')\n || lower.includes('window closed')\n || lower.includes('detected container element removed');\n };\n\n const forwardError = (message: string) => {\n if (cancelled) return;\n if (isZoidLifecycleMessage(message)) return;\n const friendly = applyFriendlyMessageOverride(message) ?? message;\n onErrorChangeRef.current?.(friendly);\n };\n\n /**\n * Used by load/render-time error paths: hides the placeholder (and the\n * whole row) so users don't stare at a perpetual skeleton when PayPal\n * can't load. Logs to console for diagnostics but never calls\n * `onErrorChange` — pre-render failures (script load 400, ineligibility,\n * render rejection) would otherwise paint a checkout-blocking red banner\n * even though card / wallet / other gateways remain usable. The row\n * silently collapses; the parent's `directPaypalReady` stays false.\n *\n * Zoid lifecycle messages (e.g. \"zoid destroyed all components\") fire\n * during mount/unmount churn — most commonly React StrictMode's\n * mount → cleanup → mount cycle in dev. On iOS Facebook IAB the surviving\n * mount's render rejects with this message even though nothing is wrong,\n * because WKWebView's iframe init races the rapid cycle. Treat these as\n * transient: don't flip `failed = true` (which would permanently hide the\n * button) — the deferred-load guard above prevents the double-load that\n * triggered this in the first place, so a fresh attempt should succeed.\n */\n const markRenderFailed = (message: string) => {\n if (cancelled) return;\n if (isZoidLifecycleMessage(message)) {\n appendDebug(`markRenderFailed:skip-zoid msg=${message.slice(0, 80)}`);\n return;\n }\n setFailed(true);\n console.error('[FloPay] DirectPayPal load/render failure:', message);\n };\n\n // Reset failure state at the start of every effect run so a config\n // change (clientId/environment/sessionId/currency etc.) re-attempts the\n // render cleanly rather than inheriting a sticky failure from the\n // previous configuration.\n setFailed(false);\n\n const dispatchTokenizedBody = async (body: TokenizedBody) => {\n const prepared = beforeClickRef.current;\n const effectiveSessionId = prepared?.sessionId ?? sessionId;\n if (onTokenizedBodyRef.current) {\n onTokenizedBodyRef.current(body, {\n sessionId: effectiveSessionId,\n accountPatch: prepared?.accountPatch,\n });\n return;\n }\n try {\n const currentSession = sessionRef.current;\n const currentEmail = prepared?.accountPatch?.email ?? emailRef.current;\n const effectiveUserId = prepared?.accountPatch?.userId\n ?? currentSession?.customer?.id\n ?? currentSession?.accountData?.userId\n ?? '';\n const api = new PaymentAPI(baseUrl);\n const response = await api.processPayment(\n effectiveUserId,\n {\n sessionId: effectiveSessionId,\n nonce: nonceRef.current,\n tokenizedData: body,\n accountData: {\n userId: effectiveUserId,\n email: currentEmail ?? currentSession?.customer?.email ?? '',\n firstName: prepared?.accountPatch?.firstName\n ?? currentSession?.customer?.firstName\n ?? currentSession?.accountData?.firstName\n ?? '',\n lastName: prepared?.accountPatch?.lastName\n ?? currentSession?.customer?.lastName\n ?? currentSession?.accountData?.lastName\n ?? '',\n country: prepared?.accountPatch?.country\n ?? currentSession?.customer?.country\n ?? currentSession?.accountData?.country\n ?? undefined,\n zip: prepared?.accountPatch?.zip\n ?? currentSession?.customer?.zip\n ?? currentSession?.accountData?.zip\n ?? undefined,\n },\n },\n );\n\n if (response.ok) {\n onCompleteRef.current?.({ status: 'succeeded', checkoutMethod: 'paypal' });\n return;\n }\n\n const json = (await response.json().catch(() => null)) as Record<string, unknown> | null;\n const rawMessage = (json?.['message'] as string | undefined) ?? 'PayPal payment failed.';\n const message = applyFriendlyMessageOverride(rawMessage) ?? rawMessage;\n forwardError(message);\n onDeclineRef.current?.(buildDeclineEvent('paypal', message, {\n code: json?.['code'] as string | undefined,\n declineCode: json?.['declineCode'] as string | undefined,\n }));\n } catch (err) {\n const rawMessage = err instanceof Error ? err.message : 'PayPal payment failed.';\n const message = applyFriendlyMessageOverride(rawMessage) ?? rawMessage;\n forwardError(message);\n onDeclineRef.current?.(buildDeclineEvent('paypal', message));\n }\n };\n\n const createPaypalIntent = async (fallbackMessage: string): Promise<string> => {\n const prepared = beforeClickRef.current;\n const effectiveSessionId = prepared?.sessionId ?? sessionId;\n const effectiveEmail = prepared?.accountPatch?.email ?? emailRef.current;\n // isPaypal must be string 'true' — backend checks === 'true'.\n const intentHeaders: Record<string, string> = { 'Content-Type': 'application/json' };\n const currentNonce = nonceRef.current;\n if (currentNonce) intentHeaders['x-checkout-session-token'] = currentNonce;\n const response = await fetch(`${baseUrl}/v1/checkouts/payments/intents`, {\n method: 'POST',\n headers: intentHeaders,\n body: JSON.stringify({\n sessionId: effectiveSessionId,\n email: effectiveEmail,\n paymentMethodType: 'paypal',\n isPaypal: 'true',\n }),\n });\n const json = (await response.json().catch(() => null)) as\n | { data?: CreatePaypalOrderResponseData; message?: string }\n | null;\n if (!response.ok) {\n throw new Error(json?.message ?? fallbackMessage);\n }\n const id = json?.data?.id;\n if (!id) {\n throw new Error(fallbackMessage);\n }\n return id;\n };\n\n // Defer the PayPal lifecycle by one macrotask so any rapid mount → cleanup\n // → mount cycle (React StrictMode in dev, or a parent that briefly mounts\n // us before late-arriving props like `email` cause it to re-render) has\n // finished before we touch PayPal's SDK. Without this, both the dead and\n // surviving mounts call `loadScript` in the same tick; on iOS Facebook\n // IAB the surviving mount's `render()` then rejects with \"zoid destroyed\n // all components\" because zoid's iframe init races the synchronous\n // teardown. clearTimeout in the cleanup ensures the dead mount never even\n // starts the load.\n appendDebug('loadScript:scheduled (deferred 1 tick)');\n let loadPromise: Promise<PayPalNamespace | null> | null = null;\n const startTimer = setTimeout(() => {\n if (cancelled) {\n appendDebug('loadScript:skipped (cancelled before defer ran)');\n return;\n }\n appendDebug('loadScript:start');\n // PayPal SDK uses `'production'` (not `'live'`) for prod mode, so\n // re-map after our internal normalize step.\n const paypalSdkEnv: 'sandbox' | 'production' | undefined =\n normalizedEnv === 'live' ? 'production' : normalizedEnv;\n loadPromise = loadScript({\n clientId,\n currency,\n // Subscriptions need the `subscription` vault intent; one-time payments\n // use a standard order capture.\n intent: isSubscription ? 'subscription' : 'capture',\n vault: isSubscription ? true : undefined,\n // Tell PayPal which environment the clientId belongs to. Without\n // this, PayPal defaults to live endpoints — and a sandbox clientId\n // sent to live silently stalls in zoid's prerender forever (no\n // error, no rejection).\n ...(paypalSdkEnv ? { environment: paypalSdkEnv } : {}),\n // Namespace the sandbox SDK so it can coexist with a production SDK on\n // the same page without clobbering `window.paypal`.\n ...(paypalSdkEnv === 'sandbox' ? { dataNamespace: 'paypal_sandbox' } : {}),\n });\n loadPromise\n .then((paypal) => {\n appendDebug(`loadScript:resolved cancelled=${cancelled} ns=${!!paypal} buttons=${!!paypal?.Buttons}`);\n if (cancelled || !paypal?.Buttons) {\n if (!cancelled && !paypal?.Buttons) appendDebug('FAIL: namespace missing Buttons factory');\n return;\n }\n\n const handleApprove = async (data: { orderID?: string; subscriptionID?: string }) => {\n try {\n setSubmitting(true);\n onErrorChangeRef.current?.(null);\n const token = data.subscriptionID ?? data.orderID ?? '';\n if (!token) {\n throw new FloPayError(\n 'PayPal did not return an approval token.',\n 'api_error',\n { code: 'paypal_missing_token' },\n );\n }\n await dispatchTokenizedBody({\n id: token,\n isPaypal: true,\n });\n } catch (err) {\n forwardError(err instanceof Error ? err.message : 'PayPal capture failed.');\n } finally {\n setSubmitting(false);\n }\n };\n\n const buttons = paypal.Buttons!({\n style: { layout: 'horizontal', height: DEFAULT_BUTTON_HEIGHT, tagline: false },\n // PayPal's SDK awaits a Promise returned from `onClick` and aborts\n // the create-order/create-subscription step when `actions.reject()`\n // is invoked. Run the consumer's `runBeforeButtonClick` here so\n // inline-session/account patches land before the order is created,\n // matching the Stripe-rendered PayPal flow.\n onClick: async (_data: unknown, actions: { resolve: () => Promise<void>; reject: () => Promise<void> }) => {\n const runner = runBeforeButtonClickRef.current;\n if (runner) {\n try {\n const beforeClick = await runner('paypal');\n if (!beforeClick.proceed) {\n beforeClickRef.current = null;\n await actions.reject();\n return;\n }\n beforeClickRef.current = {\n sessionId: beforeClick.sessionId,\n accountPatch: beforeClick.accountPatch,\n };\n } catch (err) {\n appendDebug(`onClick:runBeforeButtonClick rejected msg=${(err instanceof Error ? err.message : String(err)).slice(0, 120)}`);\n beforeClickRef.current = null;\n await actions.reject();\n return;\n }\n } else {\n beforeClickRef.current = null;\n }\n onButtonClickRef.current?.('paypal');\n await actions.resolve();\n },\n // When the SDK is already holding an order/subscription id from a\n // prior backend round-trip (the `paypal_direct_required` retry\n // path), feed it straight to PayPal instead of creating a new one.\n // Otherwise fall back to the normal create-intent call.\n createOrder: isSubscription\n ? undefined\n : existingOrderId\n ? () => Promise.resolve(existingOrderId)\n : () => createPaypalIntent('Failed to create PayPal order.'),\n createSubscription: isSubscription\n ? existingOrderId\n ? () => Promise.resolve(existingOrderId)\n : () => createPaypalIntent('Failed to create PayPal subscription.')\n : undefined,\n onApprove: handleApprove,\n onCancel: () => {\n beforeClickRef.current = null;\n onDeclineRef.current?.(buildDeclineEvent('paypal', 'PayPal checkout was cancelled.'));\n },\n onError: (err) => {\n const message = err instanceof Error ? err.message : 'PayPal failed to render.';\n appendDebug(`onError rendered=${rendered} msg=${message.slice(0, 120)}`);\n // Post-render: a runtime failure (e.g. backend rejected the\n // create-order/subscription call) — keep the button visible so\n // the user can retry, and surface the error to the consumer.\n if (rendered) {\n forwardError(message);\n onDeclineRef.current?.(buildDeclineEvent('paypal', message));\n return;\n }\n // Pre-render: actual render-time issue or zoid teardown; mark\n // failed so we hide the placeholder. `markRenderFailed` filters\n // zoid lifecycle messages out of the forwarded error so the\n // consumer doesn't see noise.\n markRenderFailed(message);\n },\n } as Parameters<NonNullable<typeof paypal.Buttons>>[0]);\n\n const eligible = buttons.isEligible();\n appendDebug(`isEligible=${eligible}`);\n if (!eligible) {\n setReady(false);\n markRenderFailed(\n 'PayPal buttons are not eligible to render in this context (paypal_ineligible).',\n );\n return;\n }\n\n const typedButtons = buttons as { close: () => Promise<void> };\n\n // Pre-render container snapshot. A 0-width parent (flex column\n // collapse, display:none ancestor, etc.) is a common silent failure:\n // PayPal renders happily into a zero-size box and the user sees\n // nothing. Logging dims here catches that before render starts.\n if (debug) {\n appendDebug(`container:dims ${formatDims(container)} visibility=${typeof document !== 'undefined' ? document.visibilityState : '(no document)'}`);\n }\n\n // MutationObserver: log every PayPal injection AND every attribute\n // change. Zoid creates iframes with empty src/srcdoc first and then\n // sets the content attribute asynchronously — without `attributes:\n // true` we'd never see when (or whether) the content load actually\n // happens. The iframe's title=PayPal first appears as a childList\n // mutation; `src`/`srcdoc` then appears as an attribute mutation.\n if (debug && typeof MutationObserver !== 'undefined') {\n containerObserver = new MutationObserver((mutations) => {\n for (const mutation of mutations) {\n if (mutation.type === 'childList') {\n mutation.addedNodes.forEach((node) => {\n if (!(node instanceof Element)) return;\n const tag = node.tagName.toLowerCase();\n const title = (node.getAttribute('title') ?? '').slice(0, 40);\n const detail = tag === 'iframe' ? ` ${describeIframe(node)}` : '';\n appendDebug(`child+ ${tag}${title ? ` title=\"${title}\"` : ''}${detail} dims=${formatDims(node)}`);\n });\n } else if (mutation.type === 'attributes' && mutation.target instanceof Element) {\n const target = mutation.target;\n if (target.tagName.toLowerCase() !== 'iframe') continue;\n const attr = mutation.attributeName;\n if (attr === 'src' || attr === 'srcdoc') {\n appendDebug(`attr~ iframe ${attr}=${attr === 'srcdoc' ? `[${(target.getAttribute('srcdoc') ?? '').length}ch]` : classifyIframeSrc(target.getAttribute('src'))} dims=${formatDims(target)}`);\n }\n }\n }\n });\n containerObserver.observe(container, {\n childList: true,\n subtree: true,\n attributes: true,\n attributeFilter: ['src', 'srcdoc'],\n });\n }\n\n // Render watchdog. Snapshots the container + iframes at 3s/8s/15s\n // if render() hasn't resolved. Uses describeIframe so we see src,\n // srcdoc length, name (zoid uses iframe names for postMessage\n // routing), and sandbox attribute — enough to distinguish \"iframe\n // shell exists but content never loaded\" (postMessage/storage\n // failure) from \"iframe loaded but render() didn't fire\" (PayPal\n // SDK internal bug or unmounted parent).\n const snapshotContainer = (when: string) => {\n if (cancelled || rendered) return;\n const iframes = container.querySelectorAll('iframe');\n const hasStorageAccess = typeof document !== 'undefined' && 'hasStorageAccess' in document;\n appendDebug(`watchdog:${when} container=${formatDims(container)} children=${container.childElementCount} iframes=${iframes.length} visibility=${typeof document !== 'undefined' ? document.visibilityState : '(no document)'} cookies=${typeof navigator !== 'undefined' ? navigator.cookieEnabled : '?'} hasStorageAccessApi=${hasStorageAccess} paypalNetRequests=${paypalRequestCount.value}`);\n iframes.forEach((frame, i) => {\n const title = (frame.getAttribute('title') ?? '').slice(0, 40);\n appendDebug(` iframe[${i}] ${formatDims(frame)}${title ? ` title=\"${title}\"` : ''} ${describeIframe(frame)}`);\n const content = inspectFrameContent(frame);\n if (content) appendDebug(` ${content}`);\n });\n if (errorMessages.length === 0) {\n appendDebug(` (no PayPal/zoid window errors captured)`);\n }\n };\n if (debug) {\n watchdogTimers.push(setTimeout(() => snapshotContainer('3s'), 3000));\n watchdogTimers.push(setTimeout(() => snapshotContainer('8s'), 8000));\n watchdogTimers.push(setTimeout(() => snapshotContainer('15s'), 15000));\n }\n\n appendDebug('render:start');\n buttons.render(container).then(() => {\n appendDebug(`render:resolved cancelled=${cancelled}`);\n stopDiagnostics();\n if (cancelled) {\n // Component unmounted while render was in flight — render is now\n // complete, so close gracefully here instead of from cleanup\n // (cleanup couldn't see `activeButtons` yet at the time it ran).\n typedButtons.close().catch(() => {});\n return;\n }\n activeButtons = typedButtons;\n rendered = true;\n setReady(true);\n }).catch((err: unknown) => {\n const message = err instanceof Error ? err.message : 'PayPal failed to render.';\n appendDebug(`render:rejected msg=${message.slice(0, 120)}`);\n stopDiagnostics();\n markRenderFailed(message);\n });\n })\n .catch((err: unknown) => {\n const message = err instanceof Error ? err.message : 'PayPal SDK failed to load.';\n appendDebug(`loadScript:rejected msg=${message.slice(0, 120)}`);\n markRenderFailed(message);\n });\n }, 0);\n\n return () => {\n cancelled = true;\n // If the deferred load never fired (e.g. StrictMode's synchronous\n // cleanup), clearTimeout prevents the dead mount from ever calling\n // loadScript. The surviving mount's deferred timer runs next tick and\n // owns the lifecycle alone.\n clearTimeout(startTimer);\n stopDiagnostics();\n // Prefer PayPal's graceful teardown over `container.innerHTML = ''`,\n // which races the SDK's async `render()` and triggers\n // \"Detected container element removed from DOM\".\n if (activeButtons) {\n activeButtons.close().catch(() => {});\n }\n };\n }, [baseUrl, clientId, currency, environment, isSubscription, sessionId, existingOrderId]);\n\n // On-screen lifecycle tracer, only rendered when `debug` is true.\n const debugPanel = debug ? (\n <pre\n data-testid=\"flopay-direct-paypal-debug\"\n style={{\n margin: '0 0 8px 0',\n padding: '6px 8px',\n background: failed ? '#fef2f2' : '#f3f4f6',\n border: `1px solid ${failed ? '#fca5a5' : '#d1d5db'}`,\n borderRadius: 6,\n color: '#111827',\n font: '11px/1.35 ui-monospace, SFMono-Regular, Menlo, monospace',\n whiteSpace: 'pre-wrap',\n wordBreak: 'break-word',\n maxHeight: 220,\n overflowY: 'auto',\n }}\n >\n {`FloPay/DirectPayPal-debug (ready=${ready} failed=${failed})`}\n {debugLines.length === 0 ? '\\n(waiting for first lifecycle event…)' : `\\n${debugLines.join('\\n')}`}\n </pre>\n ) : null;\n\n // If PayPal can't load/render at all, render nothing in production, or only\n // the diagnostic panel when `debug` is on (so the failure mode stays visible\n // on screen).\n if (failed) {\n return debug ? <div>{debugPanel}</div> : null;\n }\n\n return (\n // Single wrapper so the parent flex container sees exactly one flex item\n // (otherwise the fragment's placeholder + container become two siblings\n // and any spacing-sensitive layout has to reason about both). The wrapper\n // intentionally has no margin/padding so the parent owns all spacing.\n <div>\n {debugPanel}\n {/*\n Stacking context: the container must stay in the layout flow with\n non-zero dimensions for PayPal's zoid framework to mount its iframes —\n a `display: none` parent leaves the iframe 0×0 and `render()` never\n resolves. The placeholder absolutely-positions over the container so\n the user sees a skeleton until PayPal's button is interactive.\n */}\n <div style={{ position: 'relative', minHeight: DEFAULT_BUTTON_HEIGHT }}>\n {!ready && (\n <div\n data-testid=\"flopay-direct-paypal-placeholder\"\n style={{\n position: 'absolute',\n inset: 0,\n borderRadius: 8,\n background: '#e5e7eb',\n animation: 'flopay-pulse 1.5s ease-in-out infinite',\n pointerEvents: 'none',\n }}\n />\n )}\n <div\n ref={containerRef}\n data-testid=\"flopay-direct-paypal-container\"\n // `display: flex` makes PayPal's injected `.paypal-buttons` a flex\n // child instead of an inline-block. That kills the baseline descender\n // space that would otherwise read as a phantom margin below the\n // button (looking like a doubled flex `gap` in the parent column).\n // `opacity: 0` (not `display: none`) keeps the container measurable\n // so PayPal can render into it before `ready` flips true.\n style={{\n minHeight: DEFAULT_BUTTON_HEIGHT,\n display: 'flex',\n opacity: ready ? 1 : 0,\n }}\n aria-busy={submitting || isProcessing}\n />\n </div>\n </div>\n );\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 applyFriendlyMessageOverride,\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 const rawMessage = error?.message ?? fallbackMessage;\n const message = applyFriendlyMessageOverride(rawMessage) ?? rawMessage;\n\n return Object.assign(\n new FloPayError(\n message,\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 nestedGateways = nestedRecord.gateways;\n if (nestedGateways && typeof nestedGateways === 'object') {\n const stripeGateway = (nestedGateways as Record<string, unknown>).stripe;\n if (stripeGateway && typeof stripeGateway === 'object') {\n const stripeRecord = stripeGateway as Record<string, unknown>;\n const gatewayCandidates = [\n stripeRecord.stripeClientSecret,\n stripeRecord.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\n return undefined;\n}\n\nasync function recover3DSRedirectResult({\n billingApiUrl,\n sessionId,\n nonce,\n responseJson,\n}: {\n billingApiUrl: string;\n sessionId?: string | null;\n nonce?: string;\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, nonce);\n const refreshedToken = unified.data.stripe?.clientSecret;\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 nonce: session.clientSecret,\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 nonce: session.clientSecret,\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 session.clientSecret ? { nonce: session.clientSecret } : undefined,\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 const friendly = applyFriendlyMessageOverride(err.message);\n if (friendly && friendly !== err.message) {\n return Object.assign(\n new FloPayError(friendly, err.type, {\n code: err.code,\n declineCode: err.declineCode,\n param: err.param,\n statusCode: err.statusCode,\n }),\n { checkoutMethod: (err as SavedPaymentFlowError).checkoutMethod },\n ) as SavedPaymentFlowError;\n }\n return err as SavedPaymentFlowError;\n }\n\n const rawMessage = err instanceof Error ? err.message : 'Payment failed. Please try again.';\n const message = applyFriendlyMessageOverride(rawMessage) ?? rawMessage;\n\n return new FloPayError(message, 'api_error') as SavedPaymentFlowError;\n}\n\n/**\n * Stripe Elements publishable keys resolved from a normalized session. The\n * \"PayPal\" entry here refers to the legacy Stripe-rendered PayPal account\n * (`gateways.stripe`'s dedicated PayPal sub-account), not the new direct\n * PayPal gateway — direct PayPal lives in `gateways.paypal` and is rendered\n * via the official PayPal JS SDK rather than through Stripe Elements.\n *\n * For PayPal-only sessions (`gateways.paypal` set, no `gateways.stripe`),\n * `publishableKey` is `undefined` and the caller should skip Stripe Elements\n * entirely. Only throws when the session advertises no supported gateway at\n * all.\n */\nexport function resolveSavedPaymentPublishableKeys(\n unified: NormalizedCheckoutSession,\n): {\n publishableKey?: string;\n paypalPublishableKey?: string;\n} {\n const publishableKey = unified.data.stripe?.publishableKey;\n const hasDirectPaypal = Boolean(unified.data.paypal?.publishableKey);\n\n if (!publishableKey && !hasDirectPaypal) {\n throw new FloPayError(\n 'Session advertises no supported gateways (expected `gateways.stripe` and/or `gateways.paypal`).',\n 'validation_error',\n );\n }\n\n if (!publishableKey) {\n // Direct-PayPal-only session: no Stripe Elements at all.\n return {};\n }\n\n return {\n publishableKey,\n // Direct-PayPal sessions can still use Stripe's PayPal Element for the\n // saved-PM redirect leg. Prefer the dedicated Stripe-PayPal sub-account\n // publishable key when the backend advertises one; fall back to the\n // primary Stripe publishable key so the resume flow still has a Stripe\n // instance to drive Stripe's PayPal PI.\n paypalPublishableKey: unified.data.stripe?.paypalPublishableKey ?? publishableKey,\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 | null;\n paypalFlopay: FloPay | null;\n}> {\n if (!publishableKey) {\n // PayPal-only session: no Stripe Elements instance to load. The\n // saved-PM Stripe-PayPal resume leg isn't available, but direct PayPal\n // doesn't need it.\n return { flopay: null, paypalFlopay: null };\n }\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 /**\n * Session-bound checkout token returned by session creation\n * (`CheckoutSessionResult.nonce` or `session.clientSecret`). Forwarded as\n * `x-checkout-session-token` on every continuation request — required by\n * post-#640 backends (`TeamFloPay/backend#640`), which 401 the call when the\n * header is missing or does not match the session's stored nonce.\n * `FloPayCheckout` plumbs this prop automatically.\n */\n nonce?: 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 nonce,\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 nonce,\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 Stripe-rendered PayPal path. Routes\n // confirmation through the PayPal FloPay instance (falls back to the\n // primary Stripe instance when no dedicated PayPal sub-account is\n // configured).\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, nonce, 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 intentHeaders: Record<string, string> = { 'Content-Type': 'application/json' };\n if (nonce) intentHeaders['x-checkout-session-token'] = nonce;\n const intentResponse = await fetch(`${baseUrl}/v1/checkouts/payments/intents`, {\n method: 'POST',\n headers: intentHeaders,\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, nonce, email, firstName, lastName, 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 /**\n * Session-bound checkout token returned by session creation. Forwarded as\n * `x-checkout-session-token` on continuation requests — required by\n * post-#640 backends.\n */\n nonce?: 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 nonce,\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 nonce,\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, nonce, 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 nonce,\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, nonce, 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 ThemeId,\n} from '@flopay/shared';\nimport type {\n ButtonsLayoutStyles,\n ButtonsLayoutTheme,\n CheckoutItem,\n CheckoutProduct,\n CheckoutSubscription,\n} from '@flopay/shared';\nimport { FloPayError, resolveBillingApiUrl, resolveButtonsLayoutTheme, resolveTheme } from '@flopay/shared';\nimport { CardButtonContentSlot } from './card-button-content.js';\nimport { buildDeclineEvent } from './checkout-utils.js';\nimport { FloPayCheckout } from './flopay-checkout.js';\nimport { derivePrimaryTileStyle } from './split-card-form.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 normalizeSavedPaymentError,\n processSavedPaymentForMode,\n} from './saved-payment-flow.js';\n\nconst DEFAULT_BUTTONS_LAYOUT_BUTTON_HEIGHT = 44;\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 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\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 /**\n * @deprecated Ignored. The backend now picks the customer's most recent\n * vaulted payment method via `getLatestByUserId` and rebinds the session's\n * gateway to match it (see `apps/api`'s `createSingle` auto-checkout\n * branch). Passing this prop has no effect — it is retained only to avoid\n * breaking existing integrations.\n */\n paymentMethodId?: string;\n /**\n * @deprecated Ignored. The backend orchestrates gateway routing — clients\n * no longer choose between card and PayPal at the SDK boundary. Passing\n * this prop has no effect.\n */\n checkoutMethod?: CheckoutButtonMethod;\n clientId?: string;\n /**\n * Unified products array (TeamFloPay/backend#760). When supplied,\n * `items`/`subscriptions` are ignored. The SDK folds the legacy fields\n * into this shape internally.\n */\n products?: CheckoutProduct[];\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 /**\n * High-level theme bundle that styles the button (and the fallback\n * `FloPayCheckout` modal that opens when the saved-payment charge needs\n * user interaction). One of: `'classic'`, `'modern-light'`, `'modern-dark'`,\n * `'bold-light'`, `'bold-dark'`, `'glass-light'`, `'glass-dark'`. Explicit\n * `buttonsStyles` still wins for fine-grained overrides.\n */\n theme?: ThemeId;\n /**\n * @deprecated Use `theme` instead. Legacy buttons-layout preset\n * (`'default' | 'minimal' | 'rounded' | 'dark'`). Still honored for\n * back-compat.\n */\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 // Enforce the documented precedence: when `products` is supplied the legacy\n // `items`/`subscriptions` are dropped so the draft can't carry an ambiguous\n // cart. `createAndFetchSession` folds the legacy fields into `products[]`\n // only when `products` is absent (`params.products ?? foldIntoProducts(...)`).\n // Use `!= null` so `products={null}` is treated as absent too, matching the\n // `??` semantics downstream — otherwise the legacy fields would be dropped\n // here but `null ?? foldIntoProducts(undefined, undefined)` would yield `[]`.\n const hasProducts = props.products != null;\n\n return {\n clientId: props.clientId,\n products: props.products,\n items: hasProducts ? undefined : props.items,\n subscriptions: hasProducts ? undefined : 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 // Deprecated — accepted for back-compat and silently ignored. Backend\n // resolves the customer's latest payment method server-side.\n paymentMethodId: _deprecatedPaymentMethodId,\n checkoutMethod: _deprecatedCheckoutMethod,\n clientId,\n products,\n items,\n subscriptions,\n account,\n successUrl,\n cancelUrl,\n couponCodes,\n tagsData,\n utmMetadata,\n billingApiUrl,\n locale,\n theme,\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 products,\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 products,\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\n const isMountedRef = useRef(true);\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 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: { status: 'succeeded' },\n session: completedSession,\n sessionId: completedSession.id || resolvedSessionId,\n autoCompleted: false,\n });\n return;\n }\n\n if (apiResult.autoProcessingError) {\n throw checkoutProcessErrorToFloPayError(\n apiResult.autoProcessingError,\n 'Automatic payment failed. Please try again.',\n {\n checkoutMethod: apiResult.autoProcessingError.checkoutMethod,\n },\n );\n }\n\n if (options?.fromCreateSession && apiResult.autoProcessingAttempted === true) {\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 }\n\n // Existing-session path: backend's `createSingle` auto-checkout did not\n // run, so kick off /process. The SDK no longer ships client-built\n // `tokenizedData` — the backend resolves the customer's latest vaulted\n // payment method server-side (see `apps/api`'s `process` /\n // `processPendingSession` for the orchestration that owns this now).\n const result = await processSavedPaymentForMode({\n billingApiUrl: resolvedBillingUrl,\n sessionId: resolvedSessionId ?? session.id,\n session,\n });\n\n if (result.type !== 'success') {\n // The backend should not be requesting a client-side redirect when it\n // owns gateway routing. Anything other than `success` is treated as a\n // failure and falls through to the standard error path (fallback\n // checkout for recoverable cases).\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 }\n\n await showSuccess({\n result: result.result,\n session,\n sessionId: session.id || resolvedSessionId,\n autoCompleted: false,\n });\n } catch (err) {\n const floPayErr = normalizeSavedPaymentError(err);\n const fallbackSessionId = session.id || resolvedSessionId;\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 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 });\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 // Resolution: `theme` (high-level bundle) takes precedence over the legacy\n // `buttonsTheme` preset; explicit `buttonsStyles` overrides individual fields\n // on top of whichever base was chosen.\n const themeBundle = useMemo(() => resolveTheme(theme), [theme]);\n const bStyles = useMemo<ButtonsLayoutStyles>(() => {\n const base = themeBundle?.buttonsLayout ?? resolveButtonsLayoutTheme(buttonsTheme);\n if (!stylesOverride) return base;\n return {\n ...base,\n ...stylesOverride,\n cardButton: { ...base.cardButton, ...stylesOverride.cardButton },\n };\n }, [themeBundle, 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 // `bStyles.cardButton` first so the bundle's padding / typography\n // / radius / shadow come through, then `derivePrimaryTileStyle`\n // on top so the auto-pay button carries the *submit* button's\n // background and text colours — making it visually identical to\n // the \"Confirm Payment\" / \"Pay with X\" actions it stands in for.\n // Inline `style` consumer override stays at the end so explicit\n // per-button overrides still win.\n ...bStyles.cardButton as React.CSSProperties,\n ...derivePrimaryTileStyle({\n themeBundle,\n resolvedPrimaryColor:\n (themeBundle?.appearance.variables?.colorPrimary as string | undefined) ?? '#4A49FF',\n resolvedBorderRadius:\n (themeBundle?.appearance.variables?.borderRadius as string | undefined) ?? '8px',\n submitButtonStyle: bStyles.submitButton as React.CSSProperties | undefined,\n }),\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 transition: 'border-color 0.2s, box-shadow 0.2s, transform 0.1s',\n position: 'relative',\n opacity: disabled || isProcessing ? 0.6 : 1,\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 locale={locale}\n theme={theme}\n buttonsTheme={buttonsTheme}\n buttonsStyles={stylesOverride}\n initialErrorMessage={fallbackSession.errorMessage}\n cardTitleContent={null}\n onComplete={handleFallbackComplete}\n onError={handleFallbackError}\n onDecline={handleFallbackDecline}\n />\n </div>\n </div>\n )}\n </>\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,IAAAA,gBAAoD;AAGpD,oBAAqC;;;ACHrC,mBAA8B;AAsCvB,IAAM,oBAAgB,4BAAkC;AAAA,EAC7D,QA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AW;AAAA,cACX,SAAS;AAAA,cACT,eAAe;AAAA,cACf,KAAK;AAAA,YACP;AAAA,YAEA;AAAA,cAAC;AAAA;AAAA,gBACC,WAAW,gBAAgB;AAAA,gBAC3B,cAAa;AAAA,gBACb,eAAe;AAAA,gBACf;AAAA,gBACA;AAAA,gBACA;AAAA,gBACA,eAAe;AAAA,gBACf,qBAAqB,gBAAgB;AAAA,gBACrC,kBAAkB;AAAA,gBAClB,YAAY;AAAA,gBACZ,SAAS;AAAA,gBACT,WAAW;AAAA;AAAA,YACb;AAAA;AAAA,QACF;AAAA;AAAA,IACF;AAAA,KAEJ;AAEJ;","names":["import_react","import_react","import_js","import_shared","import_react","import_jsx_runtime","import_react","import_jsx_runtime","import_shared","import_js","import_react","import_react","import_shared","import_react","import_jsx_runtime","import_shared","import_react","import_shared","import_jsx_runtime","import_shared","import_jsx_runtime","SplitCardForm","useStripeRaw","useStripeElements","React","StripeElements","stateValue","message","error","import_js","import_shared","error","import_jsx_runtime","DEFAULT_BUTTONS_LAYOUT_BUTTON_HEIGHT","activeSessionId","React","import_js","import_shared","import_react","import_jsx_runtime","CheckoutForm","error","import_js","import_shared","import_react","import_jsx_runtime","import_react","import_js","import_shared","import_jsx_runtime","DEFAULT_BUTTONS_LAYOUT_BUTTON_HEIGHT","sleep"]}
|