@flopay/react 0.3.14 → 0.3.15

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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/provider.tsx","../src/context.ts","../src/flopay-checkout.tsx","../src/card-button-content.tsx","../src/elements.tsx","../src/split-card-form.tsx","../src/hooks.ts","../src/checkout-utils.ts","../src/checkout-form.tsx","../src/paypal-button.tsx"],"sourcesContent":["import React, { useEffect, useState, useMemo } from 'react';\nimport type { FloPay, FloPayElements } from '@flopay/js';\nimport type { FloPayAppearance } from '@flopay/shared';\nimport { resolveBillingApiUrl } from '@flopay/shared';\nimport { FloPayContext } from './context.js';\n\n/** Props for the `FloPayProvider` component. */\nexport interface FloPayProviderProps {\n /** A `FloPay` instance or a promise that resolves to one (from `loadFloPay()`). */\n flopay: Promise<FloPay> | FloPay;\n /** 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 /** 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 options,\n children,\n}: FloPayProviderProps): React.ReactElement {\n const [flopay, setFloPay] = useState<FloPay | null>(\n floPayProp instanceof Promise ? null : floPayProp,\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 // 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 });\n setElements(els);\n\n return () => {\n els.destroy();\n };\n }, [flopay, options?.appearance, options?.clientSecret, options?.amount, options?.currency]);\n\n const resolvedBillingApiUrl = resolveBillingApiUrl(options?.billingApiUrl);\n\n const value = useMemo(\n () => ({ flopay, elements, billingApiUrl: resolvedBillingApiUrl }),\n [flopay, 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 { CheckoutMode, CheckoutSession, FloPayError } from '@flopay/shared';\n\n/** Internal context value for the FloPay provider. */\nexport interface FloPayContextValue {\n flopay: 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}\n\nexport const FloPayContext = createContext<FloPayContextValue>({\n flopay: 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 { loadFloPay, PaymentAPI } from '@flopay/js';\nimport type { FloPay } from '@flopay/js';\nimport type {\n BeforeButtonClickEvent,\n CheckoutButtonMethod,\n FloPayAppearance,\n DeclineEvent,\n InlineSessionDraft,\n InlineSessionPatch,\n PaymentResult,\n CheckoutSession,\n CheckoutMode,\n NormalizedCheckoutSession,\n} from '@flopay/shared';\nimport { FloPayError, resolveBillingApiUrl, buildCheckoutDisplayData, resolveButtonsLayoutTheme } from '@flopay/shared';\nimport type { ButtonsLayoutStyles, ButtonsLayoutTheme } from '@flopay/shared';\nimport {\n BackButtonContentSlot,\n CardButtonContentSlot,\n TitleContentSlot,\n isEmptySlotContent,\n} from './card-button-content.js';\nimport { FloPayProvider } from './provider.js';\nimport { SplitCardForm } from './split-card-form.js';\nimport { CheckoutContext } from './context.js';\nimport {\n buildDeclineEvent,\n buildSyntheticSession,\n ensureInlineSessionReady,\n mergeInlineSessionPatch,\n mergeInlineSessionPatches,\n} from './checkout-utils.js';\n\n/** Props for the all-in-one `FloPayCheckout` wrapper. */\nexport interface FloPayCheckoutProps {\n /** The checkout session ID (UUID from billing API). Required unless `createSession` is provided. */\n sessionId?: string;\n /**\n * Create a checkout session inline — no separate API route needed.\n * The component POSTs to the billing API, gets the full session back, and renders the form.\n * Alternative to `sessionId` (provide one or the other).\n */\n createSession?: InlineSessionDraft;\n /** Billing API base URL. Defaults to the shared `BILLING_API_URL` constant. */\n billingApiUrl?: string;\n /** Visual appearance for payment elements. */\n appearance?: FloPayAppearance;\n /** Locale for payment elements (default: 'auto'). */\n locale?: string;\n /**\n * Fallback Stripe publishable key — used only if the session response\n * doesn't include `gatewayData.publishableKey`.\n *\n * When the backend returns full session data (e.g. via `createSession`\n * with `?expand=true`), the response's `gatewayData.publishableKey` is\n * the single source of truth and this prop is not needed.\n */\n fallbackPublishableKey?: 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 /** Whether to show the PayPal button (default: true). */\n showPayPal?: boolean;\n /** Whether to show Apple Pay button (default: true). Only renders on supported devices. */\n showApplePay?: boolean;\n /** Whether to show Google Pay button (default: true). Only renders on supported devices. */\n showGooglePay?: boolean;\n /** Layout mode: 'default' (all visible) or 'buttons' (PayPal/wallets + expandable card form). */\n layout?: 'default' | 'buttons';\n /** Theme preset for the buttons layout: 'default', 'minimal', 'rounded', or 'dark'. */\n buttonsTheme?: import('@flopay/shared').ButtonsLayoutTheme;\n /** Custom style overrides for the buttons layout. Merged on top of the theme preset. */\n buttonsStyles?: import('@flopay/shared').ButtonsLayoutStyles;\n /** Custom React content rendered inside the card button when `layout=\"buttons\"`. */\n cardButtonContent?: React.ReactNode;\n /** Custom React content rendered for the buttons-layout card back button label. */\n cardBackButtonContent?: React.ReactNode;\n /** Custom React content rendered for the card-form title. */\n cardTitleContent?: React.ReactNode;\n /**\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 the credit/debit card button continues.\n * Card only: this does not run for PayPal or wallet buttons.\n * In `layout=\"buttons\"` with `createSession`, the returned patch is merged\n * into the inline session params before the real card session is created.\n */\n onBeforeButtonClick?: (\n event: BeforeButtonClickEvent,\n ) => void | false | Promise<void | false | InlineSessionPatch> | InlineSessionPatch;\n /**\n * Enable AVS (Address Verification). Shows country dropdown + ZIP/postcode input\n * in the card form. When enabled, billing_details are passed to Stripe for AVS checks.\n */\n enableAVS?: boolean;\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 /**\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/**\n * All-in-one checkout component. Fetches the session, initializes the\n * payment provider, and renders the appropriate UI based on checkout mode.\n *\n * **Modes:**\n * - `full` (default) — renders `SplitCardForm` with card fields + wallet buttons\n * - `confirm` — renders a \"Confirm Purchase\" button, uses saved payment method\n * - `auto` — auto-submits with saved PM, falls back to `full` on failure\n *\n * ```tsx\n * <FloPayCheckout\n * sessionId=\"sess_abc123\"\n * onComplete={(result) => router.push('/success')}\n * onError={(err) => console.error(err)}\n * />\n * ```\n */\nexport function FloPayCheckout({\n sessionId: sessionIdProp,\n createSession: createSessionParams,\n billingApiUrl,\n appearance,\n locale,\n fallbackPublishableKey,\n loading: loadingNode,\n error: errorNode,\n onComplete,\n onError,\n onDecline,\n showPayPal = true,\n showApplePay = true,\n showGooglePay = true,\n layout,\n buttonsTheme,\n buttonsStyles,\n cardButtonContent,\n cardBackButtonContent,\n cardTitleContent,\n onButtonClick,\n onBeforeButtonClick,\n enableAVS,\n avsLayout,\n submitLabel,\n className,\n children,\n checkoutMode: checkoutModeProp,\n confirmLabel,\n renderConfirmButton,\n onSessionCompleted,\n}: FloPayCheckoutProps): React.ReactElement {\n const resolvedBillingUrl = resolveBillingApiUrl(billingApiUrl);\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 [session, setSession] = useState<CheckoutSession | null>(null);\n const [resolvedSessionId, setResolvedSessionId] = useState<string>(sessionIdProp ?? '');\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>(null);\n const [createSessionPatch, setCreateSessionPatch] = useState<InlineSessionPatch | undefined>(undefined);\n const [createSessionPatchBaseHash, setCreateSessionPatchBaseHash] = useState('');\n const [cardBootstrapPending, setCardBootstrapPending] = useState(false);\n const [deferredCardOpen, setDeferredCardOpen] = useState(false);\n const autoCheckoutAttempted = useRef(false);\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 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 effectiveCreateSession = useMemo(\n () => createSessionParams\n ? mergeInlineSessionPatch(createSessionParams, activeCreateSessionPatch)\n : undefined,\n [createSessionParams, activeCreateSessionPatch],\n );\n\n useEffect(() => {\n setCreateSessionPatch(undefined);\n setCreateSessionPatchBaseHash(baseCreateSessionHash);\n }, [baseCreateSessionHash]);\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 /** Response from the process endpoint when additional auth is needed. */\n type ProcessRedirectResult = {\n type: 'paypal_redirect_required' | '3ds_required';\n threeDSecureToken: string;\n paymentMethodId?: string;\n };\n\n // ── Process payment for auto/confirm modes ──\n // Returns null on success, or a redirect result if PayPal/3DS auth is needed.\n\n const processPaymentForMode = useCallback(\n async (sess: CheckoutSession): Promise<ProcessRedirectResult | null> => {\n const baseUrl = resolvedBillingUrl.replace(/\\/+$/, '');\n const response = await fetch(`${baseUrl}/v1/checkouts/sessions/process`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'x-user-id': sess.customer?.id ?? '',\n },\n body: JSON.stringify({\n sessionId: resolvedSessionId,\n tokenizedData: { id: undefined },\n accountData: {\n userId: sess.customer?.id ?? '',\n email: sess.customer?.email ?? '',\n firstName: sess.customer?.firstName ?? '',\n lastName: sess.customer?.lastName ?? '',\n },\n }),\n });\n\n if (response.ok) {\n onCompleteRef.current?.({ status: 'succeeded' });\n return null;\n }\n\n const json = (await response.json().catch(() => null)) as Record<\n string,\n unknown\n > | null;\n\n // PayPal or 3DS required — return the redirect data so the caller\n // can handle it after Stripe is initialized.\n if (\n (json?.type === 'paypal_redirect_required' ||\n json?.type === '3ds_required') &&\n json?.threeDSecureToken\n ) {\n return {\n type: json.type as ProcessRedirectResult['type'],\n threeDSecureToken: json.threeDSecureToken as string,\n paymentMethodId: json.paymentMethodId as string | undefined,\n };\n }\n\n // Card requires authentication but backend didn't provide a client\n // secret (authentication_required from Stripe). Treat as 3DS required\n // so the caller can fall back to full mode or trigger 3DS.\n if (json?.gatewayErrorCode === 'authentication_required') {\n return {\n type: '3ds_required' as const,\n threeDSecureToken: '', // No client secret available\n };\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 [resolvedBillingUrl, resolvedSessionId],\n );\n\n // ── Handle redirect results (3DS / PayPal) using Stripe ──\n\n const handleRedirectResult = useCallback(\n async (\n redirectResult: ProcessRedirectResult,\n sess: CheckoutSession,\n options?: { attempt3DS?: boolean },\n ): Promise<boolean> => {\n const stripe = flopayRef.current?.getRawProvider() as import('@stripe/stripe-js').Stripe | null;\n if (!stripe) return false;\n\n if (redirectResult.type === '3ds_required') {\n if (!options?.attempt3DS || !redirectResult.threeDSecureToken) {\n // Confirm mode or no client secret available: fall back to full mode\n setModeError('Your card requires authentication. Please enter your payment details below.');\n return false;\n }\n\n // Auto mode: trigger 3DS authentication inline.\n // The backend already created the subscription with allow_incomplete.\n // Its invoice PI needs 3DS — after handleNextAction, Stripe auto-resolves\n // the invoice and activates the subscription. No resubmit needed.\n const { error: nextActionError, paymentIntent } = await stripe.handleNextAction({\n clientSecret: redirectResult.threeDSecureToken,\n });\n\n if (nextActionError) {\n setModeError(nextActionError.message ?? '3DS authentication failed.');\n emitDecline('card', nextActionError.message ?? '3DS authentication failed.', {\n code: nextActionError.code,\n });\n return false;\n }\n\n if (paymentIntent && (\n paymentIntent.status === 'requires_capture' ||\n paymentIntent.status === 'succeeded'\n )) {\n onCompleteRef.current?.({ status: 'succeeded', paymentIntentId: paymentIntent.id });\n return true;\n }\n return false;\n }\n\n if (redirectResult.type === 'paypal_redirect_required') {\n const confirmParams: Record<string, unknown> = {\n return_url: window.location.href,\n };\n if (redirectResult.paymentMethodId) {\n confirmParams['payment_method'] = redirectResult.paymentMethodId;\n }\n\n const { error } = await stripe.confirmPayment({\n clientSecret: redirectResult.threeDSecureToken,\n confirmParams: confirmParams as { return_url: string },\n redirect: 'if_required',\n });\n\n if (error) {\n setModeError(error.message ?? 'PayPal authorization failed.');\n emitDecline('paypal', error.message ?? 'PayPal authorization failed.', {\n code: error.code,\n });\n return false;\n }\n onCompleteRef.current?.({ status: 'succeeded' });\n return true;\n }\n\n return false;\n },\n [resolvedBillingUrl, resolvedSessionId, emitDecline],\n );\n\n // ── Session creation dedup ──\n // Prevents duplicate POSTs from React StrictMode double-invoking the effect.\n // Maps cache key → in-flight promise so the second invocation awaits the first.\n const inflightRef = useRef<Map<string, Promise<{ sid: string; result: NormalizedCheckoutSession }>>>(new Map());\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 const deferInlineSessionUntilCardClick = Boolean(\n effectiveCreateSession &&\n !children &&\n layout === 'buttons' &&\n onBeforeButtonClick &&\n (effectiveCreateSession.checkoutMode ?? checkoutModeProp ?? 'full') === 'full',\n );\n\n // ── Deterministic hash for session caching ──\n\n function hashCreateParams(params: InlineSessionDraft | undefined): string {\n const key = JSON.stringify({\n c: params?.clientId,\n successUrl: params?.successUrl,\n cancelUrl: params?.cancelUrl,\n i: params?.items?.map(x => `${x.providerItemId}:${x.totalAmount}:${x.overrideAmount ?? ''}:${x.quantity ?? 1}`).sort(),\n s: params?.subscriptions?.map(x => `${x.providerPlanId}:${x.totalAmount}:${x.overrideAmount ?? ''}:${x.quantity ?? 1}`).sort(),\n account: params?.account,\n couponCodes: params?.couponCodes,\n tagsData: params?.tagsData,\n utmMetadata: params?.utmMetadata,\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 async function resolveInlineSession(\n params: InlineSessionDraft,\n cacheKey: string,\n ): Promise<{ sid: string; result: NormalizedCheckoutSession }> {\n ensureInlineSessionReady(params);\n\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 if (realResult.data.session?.status === 'complete') {\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 realResult = await api.createAndFetchSession(params);\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 const cacheKey = hashCreateParams(mergedParams);\n\n let promise = inflightRef.current.get(cacheKey);\n if (!promise) {\n promise = resolveInlineSession(mergedParams, cacheKey);\n inflightRef.current.set(cacheKey, promise);\n }\n\n let resolved: { sid: string; result: NormalizedCheckoutSession };\n try {\n resolved = await promise;\n } finally {\n inflightRef.current.delete(cacheKey);\n }\n\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 let publishableKey: string | undefined;\n if (realResult.provider === 'stripe') {\n publishableKey = realResult.data.stripe?.publishableKey;\n }\n if (!publishableKey) publishableKey = fallbackPublishableKey;\n\n if (!publishableKey) {\n throw new FloPayError(\n 'No publishable key found. Provide fallbackPublishableKey or ensure the session includes gatewayData.publishableKey.',\n 'validation_error',\n );\n }\n\n const instance = await loadFloPay(publishableKey, {\n billingApiUrl: resolvedBillingUrl,\n locale,\n });\n flopayRef.current = instance;\n setFloPay(instance);\n initializedHashRef.current = cacheKey;\n setIsLoading(false);\n\n return resolved;\n },\n [fallbackPublishableKey, locale, resolvedBillingUrl],\n );\n\n const handleDeferredCardButtonClick = useCallback(async () => {\n if (cardBootstrapPending) return;\n\n setLoadError(null);\n setCardBootstrapPending(true);\n\n try {\n const beforeClickResult = await onBeforeButtonClick?.({\n method: 'card',\n createSession: effectiveCreateSession,\n });\n\n if (beforeClickResult === false) {\n setDeferredCardOpen(false);\n return;\n }\n\n const patch = beforeClickResult && typeof beforeClickResult === 'object'\n ? beforeClickResult\n : undefined;\n const baseParams = createSessionParamsRef.current;\n\n if (!baseParams) {\n throw new FloPayError(\n 'createSession is required to bootstrap checkout.',\n 'validation_error',\n );\n }\n\n ensureInlineSessionReady(mergeInlineSessionPatch(baseParams, patch));\n setDeferredCardOpen(true);\n onButtonClick?.('card');\n await bootstrapInlineSession(patch);\n } catch (err) {\n setDeferredCardOpen(false);\n const floPayErr = err instanceof FloPayError\n ? err\n : new FloPayError(\n err instanceof Error ? err.message : 'Failed to start card checkout.',\n 'api_error',\n );\n setLoadError(floPayErr);\n onErrorRef.current?.(floPayErr);\n } finally {\n setCardBootstrapPending(false);\n }\n }, [\n bootstrapInlineSession,\n baseCreateSessionHash,\n cardBootstrapPending,\n effectiveCreateSession,\n onButtonClick,\n onBeforeButtonClick,\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 if (deferInlineSessionUntilCardClick) {\n if (initializedHashRef.current !== createSessionHash) {\n setSession(null);\n setUnified(null);\n setFloPay(null);\n setResolvedSessionId('');\n setDeferredCardOpen(false);\n flopayRef.current = null;\n }\n setCurrentMode(createSessionParamsRef.current?.checkoutMode ?? checkoutModeProp ?? 'full');\n setIsLoading(false);\n return () => { cancelled = true; };\n }\n\n // Already initialized with the same params — skip.\n if (initializedHashRef.current === createSessionHash) return;\n\n const params = createSessionParamsRef.current!;\n setSession(buildSyntheticSession(params, checkoutModeProp));\n setCurrentMode(params.checkoutMode ?? checkoutModeProp ?? 'full');\n setIsLoading(false);\n\n (async () => {\n try {\n await bootstrapInlineSession();\n } catch (err) {\n if (cancelled) return;\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(resolvedSessionId);\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 const effectiveMode = checkoutModeProp ?? sess.checkoutMode ?? 'full';\n setCurrentMode(effectiveMode);\n\n const hasPayPalRedirectParams =\n typeof window !== 'undefined' &&\n new URLSearchParams(window.location.search).has('payment_intent');\n\n if (\n effectiveMode === 'auto' &&\n !autoCheckoutAttempted.current &&\n !hasPayPalRedirectParams\n ) {\n autoCheckoutAttempted.current = true;\n const stripeInitPromise = initStripe(result);\n\n try {\n const redirectResult = await processPaymentForMode(sess);\n if (!redirectResult) {\n if (!cancelled) setIsLoading(false);\n return;\n }\n if (cancelled) return;\n await stripeInitPromise;\n const handled = await handleRedirectResult(redirectResult, sess, { attempt3DS: true });\n if (!cancelled) {\n if (!handled) setCurrentMode('full');\n setIsLoading(false);\n }\n return;\n } catch {\n if (cancelled) return;\n setCurrentMode('full');\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 let publishableKey: string | undefined;\n if (result.provider === 'stripe') {\n publishableKey = result.data.stripe?.publishableKey;\n }\n if (!publishableKey) publishableKey = fallbackPublishableKey;\n\n if (!publishableKey) {\n throw new FloPayError(\n 'No publishable key found in session response. Provide a fallbackPublishableKey prop or ensure the session includes gatewayData.publishableKey.',\n 'validation_error',\n );\n }\n\n const instance = await loadFloPay(publishableKey, {\n billingApiUrl: resolvedBillingUrl,\n locale,\n });\n\n flopayRef.current = instance;\n setFloPay(instance);\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 }, [resolvedSessionId, createSessionHash, checkoutModeProp, deferInlineSessionUntilCardClick, bootstrapInlineSession]);\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 const redirectResult = await processPaymentForMode(session);\n\n if (!redirectResult) {\n // Payment succeeded directly\n return;\n }\n\n // 3DS or PayPal auth required — handle it\n const handled = await handleRedirectResult(redirectResult, session);\n if (!handled) {\n setCurrentMode('full');\n }\n } catch (err) {\n const floPayErr =\n err instanceof FloPayError\n ? err\n : new FloPayError(\n err instanceof Error ? err.message : 'Payment failed',\n 'api_error',\n );\n setModeError(floPayErr.message);\n onError?.(floPayErr);\n emitDecline('card', floPayErr);\n setCurrentMode('full');\n } finally {\n setConfirmProcessing(false);\n }\n }, [confirmProcessing, session, processPaymentForMode, handleRedirectResult, onError, emitDecline]);\n\n // Provider options from session data\n const providerOptions = useMemo(() => {\n if (!unified || !session) return undefined;\n\n const opts: {\n appearance?: FloPayAppearance;\n paymentMethodCreation: 'manual';\n billingApiUrl: string;\n clientSecret?: string;\n amount?: number;\n currency?: string;\n } = {\n appearance,\n paymentMethodCreation: 'manual',\n billingApiUrl: resolvedBillingUrl,\n };\n\n if (\n unified.provider === 'stripe' &&\n unified.data.stripe?.clientSecret\n ) {\n opts.clientSecret = unified.data.stripe.clientSecret;\n } else {\n // Use display total (respects hideItems logic) instead of raw session.amount\n const displayTotal = buildCheckoutDisplayData(session).total;\n opts.amount = Math.round(displayTotal * 100) || session.amount;\n opts.currency = session.currency?.toLowerCase();\n }\n\n return opts;\n }, [unified, session, appearance, resolvedBillingUrl]);\n\n // Checkout context\n const checkoutValue = useMemo(\n () => ({\n session,\n loading: isLoading,\n error: loadError,\n checkoutMode: currentMode,\n }),\n [session, isLoading, loadError, currentMode],\n );\n const shouldShowInterimButtons =\n Boolean(createSessionParams) &&\n layout === 'buttons' &&\n (!flopay || !providerOptions);\n const shouldKeepDeferredInterimVisible =\n shouldShowInterimButtons && deferInlineSessionUntilCardClick;\n\n // ── Loading state ──\n if (isLoading) {\n if (loadingNode) return <>{loadingNode}</>;\n\n // Buttons layout: show button-shaped skeletons\n if (layout === 'buttons') {\n const skeletonBar = (h: number) => (\n <div style={{\n height: h, borderRadius: 8, background: '#e5e7eb',\n animation: 'flopay-loading-pulse 1.5s ease-in-out infinite',\n }} />\n );\n return (\n <div style={{ display: 'flex', flexDirection: 'column', gap: '0.5rem' }}>\n {showPayPal && skeletonBar(44)}\n {(showApplePay || showGooglePay) && skeletonBar(44)}\n {skeletonBar(48)}\n <style>{`@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }`}</style>\n </div>\n );\n }\n\n // Default layout: centered spinner\n return (\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 );\n }\n\n // ── Error state ──\n if (loadError && !shouldKeepDeferredInterimVisible) {\n if (errorNode) return <>{errorNode(loadError)}</>;\n return (\n <div\n style={{\n padding: 24,\n textAlign: 'center',\n color: '#dc2626',\n fontSize: 14,\n }}\n >\n {loadError.message}\n </div>\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 <CheckoutContext.Provider value={checkoutValue}>\n <InterimButtonsView\n onButtonClick={onButtonClick}\n onCardButtonClick={deferInlineSessionUntilCardClick ? handleDeferredCardButtonClick : undefined}\n cardLoading={cardBootstrapPending}\n cardOpen={deferInlineSessionUntilCardClick ? deferredCardOpen : undefined}\n errorMessage={shouldKeepDeferredInterimVisible ? loadError?.message ?? null : null}\n showPayPal={deferInlineSessionUntilCardClick ? false : showPayPal}\n showApplePay={deferInlineSessionUntilCardClick ? false : showApplePay}\n showGooglePay={deferInlineSessionUntilCardClick ? false : showGooglePay}\n buttonsTheme={buttonsTheme}\n buttonsStyles={buttonsStyles}\n cardButtonContent={cardButtonContent}\n cardBackButtonContent={cardBackButtonContent}\n cardTitleContent={cardTitleContent}\n />\n </CheckoutContext.Provider>\n );\n }\n\n if (!flopay || !providerOptions) return <></>;\n\n // ── Confirm mode ──\n if (currentMode === 'confirm') {\n return (\n <CheckoutContext.Provider value={checkoutValue}>\n <FloPayProvider flopay={flopay} 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 );\n }\n\n // ── Full mode (default / fallback) ──\n return (\n <CheckoutContext.Provider value={checkoutValue}>\n <FloPayProvider flopay={flopay} options={providerOptions}>\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 {children ? (\n <SessionInjector\n sessionId={resolvedSessionId}\n billingApiUrl={resolvedBillingUrl}\n session={session}\n >\n {children}\n </SessionInjector>\n ) : (\n <SplitCardForm\n sessionId={resolvedSessionId}\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 showPayPal={showPayPal}\n showApplePay={showApplePay}\n showGooglePay={showGooglePay}\n layout={layout}\n buttonsTheme={buttonsTheme}\n buttonsStyles={buttonsStyles}\n cardButtonContent={cardButtonContent}\n cardBackButtonContent={cardBackButtonContent}\n cardTitleContent={cardTitleContent}\n onButtonClick={onButtonClick}\n onBeforeButtonClick={onBeforeButtonClick}\n enableAVS={enableAVS}\n avsLayout={avsLayout}\n country={session?.customer?.country}\n initialCardOpen={deferredCardOpen}\n submitLabel={submitLabel}\n className={className}\n />\n )}\n </FloPayProvider>\n </CheckoutContext.Provider>\n );\n}\n\n/**\n * Auto-injects session props into child form components.\n * Explicit props on children take precedence over injected values.\n */\nfunction SessionInjector({\n sessionId,\n billingApiUrl,\n session,\n children,\n}: {\n sessionId: string;\n billingApiUrl: string;\n session: CheckoutSession | null;\n children: React.ReactNode;\n}) {\n return (\n <>\n {React.Children.map(children, (child) => {\n if (!React.isValidElement(child)) return child;\n\n const existing = child.props as Record<string, unknown>;\n const injected: Record<string, unknown> = {};\n\n if (!existing.sessionId) injected.sessionId = sessionId;\n if (!existing.billingApiUrl) injected.billingApiUrl = billingApiUrl;\n\n if (session?.customer) {\n if (!existing.email) injected.email = session.customer.email;\n if (!existing.userId) injected.userId = session.customer.id;\n if (!existing.firstName)\n injected.firstName = session.customer.firstName;\n if (!existing.lastName)\n injected.lastName = session.customer.lastName;\n }\n\n if (Object.keys(injected).length === 0) return child;\n return React.cloneElement(child, injected);\n })}\n </>\n );\n}\n\n/**\n * Interim buttons view rendered while Stripe initializes in the background.\n * Shows skeleton bars for PayPal/wallets and a fully interactive Credit/Debit Card button.\n */\nfunction InterimButtonsView({\n onButtonClick,\n onCardButtonClick,\n cardLoading = false,\n cardOpen,\n errorMessage,\n showPayPal,\n showApplePay,\n showGooglePay,\n buttonsTheme,\n buttonsStyles: stylesOverride,\n cardButtonContent,\n cardBackButtonContent,\n cardTitleContent,\n}: {\n onButtonClick?: (method: CheckoutButtonMethod) => void;\n onCardButtonClick?: () => void | Promise<void>;\n cardLoading?: boolean;\n cardOpen?: boolean;\n errorMessage?: string | null;\n showPayPal: boolean;\n showApplePay: boolean;\n showGooglePay: boolean;\n buttonsTheme?: ButtonsLayoutTheme;\n buttonsStyles?: ButtonsLayoutStyles;\n cardButtonContent?: React.ReactNode;\n cardBackButtonContent?: React.ReactNode;\n cardTitleContent?: React.ReactNode;\n}) {\n const [showCardForm, setShowCardForm] = useState(false);\n const isCardOpenControlled = typeof cardOpen === 'boolean';\n\n useEffect(() => {\n if (isCardOpenControlled) {\n setShowCardForm(cardOpen);\n }\n }, [cardOpen, isCardOpenControlled]);\n\n const bStyles = useMemo<ButtonsLayoutStyles>(() => {\n const base = resolveButtonsLayoutTheme(buttonsTheme);\n if (!stylesOverride) return base;\n return {\n ...base,\n ...stylesOverride,\n cardButton: { ...base.cardButton, ...stylesOverride.cardButton },\n cardFormContainer: { ...base.cardFormContainer, ...stylesOverride.cardFormContainer },\n backButton: { ...base.backButton, ...stylesOverride.backButton },\n backButtonIcon: { ...base.backButtonIcon, ...stylesOverride.backButtonIcon },\n submitButton: { ...base.submitButton, ...stylesOverride.submitButton },\n title: { ...base.title, ...stylesOverride.title },\n };\n }, [buttonsTheme, stylesOverride]);\n\n const skeleton = (h: number) => (\n <div style={{\n height: h, borderRadius: 8, background: '#e5e7eb',\n animation: 'flopay-interim-pulse 1.5s ease-in-out infinite',\n }} />\n );\n\n if (showCardForm) {\n // Show a card form placeholder with back button — real form takes over when Stripe loads\n const inputBorder = bStyles.cardInputBorder ?? '#e5e7eb';\n const inputBg = bStyles.cardInputBackground ?? 'white';\n const hideBackButtonLabel = isEmptySlotContent(cardBackButtonContent);\n const hideTitle = isEmptySlotContent(cardTitleContent);\n return (\n <div style={{\n backgroundColor: (bStyles.cardFormContainer?.backgroundColor as string) ?? 'white',\n borderRadius: '8px',\n animation: 'flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both',\n overflow: 'hidden',\n ...bStyles.cardFormContainer as React.CSSProperties,\n }}>\n <div style={{ display: 'flex', alignItems: 'center', padding: '0.75rem 0 0.625rem' }}>\n <button\n type=\"button\"\n onClick={() => {\n if (!isCardOpenControlled) {\n setShowCardForm(false);\n }\n }}\n aria-label=\"Back to payment methods\"\n disabled={isCardOpenControlled || cardLoading}\n style={{\n display: 'inline-flex', alignItems: 'center', gap: hideBackButtonLabel ? 0 : '0.5rem',\n background: 'none', border: 'none',\n color: '#4b5563', fontSize: '0.85rem', fontWeight: 500,\n padding: 0, flexShrink: 0, opacity: isCardOpenControlled || cardLoading ? 0.6 : 1,\n cursor: isCardOpenControlled || cardLoading ? 'not-allowed' : 'pointer',\n ...bStyles.backButton as React.CSSProperties,\n }}\n >\n <span style={{\n display: 'inline-flex', alignItems: 'center', justifyContent: 'center',\n width: 28, height: 28, borderRadius: '50%',\n backgroundColor: '#f3f4f6',\n ...bStyles.backButtonIcon as React.CSSProperties,\n }}>\n <svg width=\"14\" height=\"14\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2.5\" strokeLinecap=\"round\" strokeLinejoin=\"round\">\n <path d=\"M15 18l-6-6 6-6\" />\n </svg>\n </span>\n <BackButtonContentSlot content={cardBackButtonContent} />\n </button>\n {hideTitle ? (\n <div style={{ flex: 1 }} />\n ) : (\n <div style={{\n flex: 1, textAlign: 'center', fontWeight: 600, fontSize: '1.05rem',\n color: '#262833', paddingRight: 80,\n ...bStyles.title as React.CSSProperties,\n }}>\n <TitleContentSlot content={cardTitleContent} />\n </div>\n )}\n </div>\n {/* Skeleton card fields */}\n <div style={{ backgroundColor: inputBg, border: `1px solid ${inputBorder}`, borderTopLeftRadius: 8, borderTopRightRadius: 8, padding: 12, height: 45 }}>\n <div style={{ width: '60%', height: 14, borderRadius: 4, background: '#e5e7eb', animation: 'flopay-interim-pulse 1.5s ease-in-out infinite' }} />\n </div>\n <div style={{ display: 'flex' }}>\n <div style={{ flex: 1, backgroundColor: inputBg, border: `1px solid ${inputBorder}`, borderTop: 'none', borderRight: 'none', borderBottomLeftRadius: 8, padding: 12, height: 45 }}>\n <div style={{ width: '50%', height: 14, borderRadius: 4, background: '#e5e7eb', animation: 'flopay-interim-pulse 1.5s ease-in-out infinite' }} />\n </div>\n <div style={{ flex: 1, backgroundColor: inputBg, border: `1px solid ${inputBorder}`, borderTop: 'none', borderBottomRightRadius: 8, padding: 12, height: 45 }}>\n <div style={{ width: '40%', height: 14, borderRadius: 4, background: '#e5e7eb', animation: 'flopay-interim-pulse 1.5s ease-in-out infinite' }} />\n </div>\n </div>\n <div style={{ backgroundColor: inputBg, border: `1px solid ${inputBorder}`, borderRadius: 8, marginTop: 8, padding: 12, height: 45 }}>\n <div style={{ width: '45%', height: 14, borderRadius: 4, background: '#e5e7eb', animation: 'flopay-interim-pulse 1.5s ease-in-out infinite' }} />\n </div>\n <div style={{\n height: 50, borderRadius: 8, marginTop: 16, background: '#c8c8ff',\n animation: 'flopay-interim-pulse 1.5s ease-in-out infinite',\n ...bStyles.submitButton as React.CSSProperties,\n opacity: 0.5,\n }} />\n <style>{`\n @keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }\n @keyframes flopay-interim-expand {\n 0% { opacity: 0; max-height: 0; transform: translateY(-12px); }\n 40% { opacity: 1; }\n 100% { opacity: 1; max-height: 600px; transform: translateY(0); }\n }\n `}</style>\n </div>\n );\n }\n\n return (\n <div style={{ display: 'flex', flexDirection: 'column', gap: '0.5rem' }}>\n {showPayPal && skeleton(44)}\n {(showApplePay || showGooglePay) && skeleton(44)}\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%', padding: '0.9rem 1rem',\n backgroundColor: 'white', color: '#262833',\n border: '1px solid #d1d5db', borderRadius: '8px',\n fontSize: bStyles.cardButtonFontSize ?? '0.95rem', fontWeight: 600,\n cursor: cardLoading ? 'not-allowed' : 'pointer', display: 'flex',\n alignItems: 'center', justifyContent: 'center', gap: '0.625rem',\n boxShadow: '0 1px 2px rgba(0,0,0,0.04)',\n transition: 'transform 0.1s',\n position: 'relative',\n opacity: cardLoading ? 0.6 : 1,\n ...bStyles.cardButton as React.CSSProperties,\n }}\n onMouseDown={(e) => { e.currentTarget.style.transform = 'scale(0.985)'; }}\n onMouseUp={(e) => { e.currentTarget.style.transform = 'scale(1)'; }}\n >\n <CardButtonContentSlot content={cardButtonContent} />\n </button>\n {errorMessage && (\n <div style={{\n margin: '0.25rem 0', padding: '0.625rem 0.875rem',\n background: '#FEF2F2', border: '1px solid #FECACA', borderRadius: '8px',\n color: '#991B1B', fontSize: '0.85rem', fontWeight: 600,\n display: 'flex', alignItems: 'center', gap: '0.5rem',\n ...(bStyles.errorBanner as React.CSSProperties | undefined),\n }}>\n <svg width=\"16\" height=\"16\" viewBox=\"0 0 24 24\" fill=\"none\" style={{ flexShrink: 0 }}>\n <path d=\"M12 9v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z\" stroke=\"#DC2626\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\" />\n </svg>\n {errorMessage}\n </div>\n )}\n <style>{`@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }`}</style>\n </div>\n );\n}\n","import React from 'react';\n\nexport function DefaultCardButtonContent(): React.ReactElement {\n return (\n <>\n <svg\n width=\"20\"\n height=\"20\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"1.5\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n aria-hidden=\"true\"\n >\n <rect width=\"20\" height=\"14\" x=\"2\" y=\"5\" rx=\"2\" />\n <line x1=\"2\" x2=\"22\" y1=\"10\" y2=\"10\" />\n </svg>\n Credit / Debit Card\n <svg\n width=\"16\"\n height=\"16\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"#9ca3af\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n style={{ position: 'absolute', right: '1rem' }}\n aria-hidden=\"true\"\n >\n <path d=\"M9 18l6-6-6-6\" />\n </svg>\n </>\n );\n}\n\nexport function DefaultBackButtonContent(): React.ReactElement {\n return <>Go back</>;\n}\n\nexport function DefaultTitleContent(): React.ReactElement {\n return <>Secure card checkout</>;\n}\n\nexport function isEmptySlotContent(content: React.ReactNode | undefined): boolean {\n return content !== undefined && (content === '' || content === null || content === false);\n}\n\nexport function CardButtonContentSlot({\n content,\n}: {\n content?: React.ReactNode;\n}): React.ReactElement {\n return <>{content === undefined ? <DefaultCardButtonContent /> : content}</>;\n}\n\nexport function BackButtonContentSlot({\n content,\n}: {\n content?: React.ReactNode;\n}): React.ReactElement {\n return <>{content === undefined ? <DefaultBackButtonContent /> : content}</>;\n}\n\nexport function TitleContentSlot({\n content,\n}: {\n content?: React.ReactNode;\n}): React.ReactElement {\n return <>{content === undefined ? <DefaultTitleContent /> : content}</>;\n}\n","import React, { useEffect, useRef, useContext } from 'react';\nimport type { ElementType, ElementChangeEvent, ElementOptions, MountedElement } from '@flopay/shared';\nimport { FloPayContext } from './context.js';\n\n/** Common props shared by all element components. */\nexport interface ElementComponentProps {\n /** Additional CSS class for the wrapper div. */\n className?: string;\n /** Element id attribute for the wrapper div. */\n id?: string;\n /** Inline styles for the wrapper div. */\n style?: React.CSSProperties;\n /** Options forwarded to the underlying element. */\n options?: Partial<ElementOptions>;\n /** Fired when the element's value changes. */\n onChange?: (event: ElementChangeEvent) => void;\n /** Fired when the element is fully rendered and ready. */\n onReady?: () => void;\n /** Fired when the element gains focus. */\n onFocus?: () => void;\n /** Fired when the element loses focus. */\n onBlur?: () => void;\n /** Fired when the Escape key is pressed inside the element. */\n onEscape?: () => void;\n}\n\n/**\n * Generic element component factory.\n *\n * Each element component:\n * 1. Gets the Elements instance from context\n * 2. Creates the appropriate element type\n * 3. Mounts it to a ref'd container div\n * 4. Forwards events as props\n * 5. Cleans up on unmount\n *\n * TODO: In a future phase, each element will render inside an iframe\n * for PCI DSS SAQ-A compliance. For now, they wrap the provider's\n * elements directly.\n */\nfunction createElementComponent(\n elementType: ElementType,\n displayName: string,\n): React.FC<ElementComponentProps> {\n function ElementComponent({\n className,\n id,\n style,\n options,\n onChange,\n onReady,\n onFocus,\n onBlur,\n onEscape,\n }: ElementComponentProps) {\n const containerRef = useRef<HTMLDivElement>(null);\n const elementRef = useRef<MountedElement | null>(null);\n const { elements } = useContext(FloPayContext);\n\n useEffect(() => {\n if (!elements || !containerRef.current) return;\n\n let mounted = true;\n\n (async () => {\n // Reuse existing element if Stripe already created one of this type\n // (handles React Strict Mode double-mount).\n let element = elements.getElement(elementType);\n if (!element) {\n element = await elements.create(elementType, options);\n }\n\n if (!mounted || !containerRef.current) {\n return;\n }\n\n element.mount(containerRef.current);\n elementRef.current = element;\n\n if (onChange) element.on('change', onChange as (...args: unknown[]) => void);\n if (onReady) element.on('ready', onReady as (...args: unknown[]) => void);\n if (onFocus) element.on('focus', onFocus as (...args: unknown[]) => void);\n if (onBlur) element.on('blur', onBlur as (...args: unknown[]) => void);\n if (onEscape) element.on('escape', onEscape as (...args: unknown[]) => void);\n })();\n\n return () => {\n mounted = false;\n // Unmount only — don't destroy. Stripe Elements tracks elements\n // internally; destroying prevents reuse on Strict Mode remount.\n // Guard with try/catch: the element may already be destroyed if\n // the parent provider recreated the Elements group (e.g. on\n // appearance change).\n if (elementRef.current) {\n try {\n elementRef.current.unmount();\n } catch {\n // Element already destroyed — safe to ignore\n }\n elementRef.current = null;\n }\n };\n }, [elements]);\n\n return <div ref={containerRef} className={className} id={id} style={style} />;\n }\n\n ElementComponent.displayName = displayName;\n return ElementComponent;\n}\n\n/**\n * Renders the unified Payment Element — a single component that accepts\n * cards, wallets, and other payment methods.\n *\n * TODO: Will render inside an iframe for PCI compliance in a future phase.\n */\nexport const PaymentElement = createElementComponent('payment', 'PaymentElement');\n\n/**\n * Renders a combined card input (number + expiry + CVC).\n *\n * TODO: Will render inside an iframe for PCI compliance in a future phase.\n */\nexport const CardElement = createElementComponent('card', 'CardElement');\n\n/**\n * Renders a card number input field.\n *\n * TODO: Will render inside an iframe for PCI compliance in a future phase.\n */\nexport const CardNumberElement = createElementComponent('cardNumber', 'CardNumberElement');\n\n/**\n * Renders a card expiry input field.\n *\n * TODO: Will render inside an iframe for PCI compliance in a future phase.\n */\nexport const CardExpiryElement = createElementComponent('cardExpiry', 'CardExpiryElement');\n\n/**\n * Renders a card CVC input field.\n *\n * TODO: Will render inside an iframe for PCI compliance in a future phase.\n */\nexport const CardCvcElement = createElementComponent('cardCvc', 'CardCvcElement');\n\n/**\n * Renders an address input element.\n */\nexport const AddressElement = createElementComponent('address', 'AddressElement');\n","import {\n CardCvcElement,\n CardExpiryElement,\n CardNumberElement,\n} from './elements.js';\nimport {\n ExpressCheckoutElement,\n Elements as StripeElements,\n useElements as useStripeElements,\n useStripe as useStripeRaw,\n} from '@stripe/react-stripe-js';\nimport type {\n BeforeButtonClickEvent,\n CheckoutButtonMethod,\n DeclineEvent,\n InlineSessionPatch,\n PaymentResult,\n TokenizedBody,\n ButtonsLayoutStyles,\n} from '@flopay/shared';\nimport { resolveButtonsLayoutTheme, getPostalCodeLabel, COUNTRY_OPTIONS } from '@flopay/shared';\nimport React, { forwardRef, useCallback, useEffect, useImperativeHandle, useMemo, useRef, useState } from 'react';\nimport type { Stripe, StripeExpressCheckoutElementConfirmEvent } from '@stripe/stripe-js';\nimport { useBillingApiUrl, useElements, useFloPay } from './hooks.js';\nimport {\n BackButtonContentSlot,\n CardButtonContentSlot,\n TitleContentSlot,\n isEmptySlotContent,\n} from './card-button-content.js';\nimport { buildDeclineEvent, mergeAccountPatch } from './checkout-utils.js';\n\nimport { FloPayError } from '@flopay/shared';\n\n/** localStorage key for persisting wallet payment state across redirects. */\nconst WALLET_RESUME_KEY = 'flopay_wallet_resume';\n\ntype MaybePromise<T> = T | Promise<T>;\n\n// ─── Global keyframes (always present — not gated behind overlay render) ────\n\nconst FLOPAY_KEYFRAMES = `\n@keyframes flopay-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }\n@keyframes flopay-fade-in { 0% { opacity: 0; } 100% { opacity: 1; } }\n@keyframes flopay-buttons-enter {\n 0% { opacity: 0; transform: translateX(-16px) scale(0.97); }\n 100% { opacity: 1; transform: translateX(0) scale(1); }\n}\n@keyframes flopay-buttons-exit {\n 0% { opacity: 1; transform: translateX(0) scale(1); }\n 100% { opacity: 0; transform: translateX(-16px) scale(0.97); }\n}\n@keyframes flopay-card-enter {\n 0% { opacity: 0; transform: translateX(16px) scale(0.97); }\n 100% { opacity: 1; transform: translateX(0) scale(1); }\n}\n@keyframes flopay-card-exit {\n 0% { opacity: 1; transform: translateX(0) scale(1); }\n 100% { opacity: 0; transform: translateX(16px) scale(0.97); }\n}\n`;\n\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// ─── Processing Overlay with animated states ─────────────────────────────────\n\ntype OverlayStatus = 'processing' | 'success' | 'error';\n\nfunction ProcessingOverlay({ status, errorMessage }: { status: OverlayStatus; errorMessage?: string | null }) {\n return (\n <div style={{\n position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.35)',\n display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 1000,\n backdropFilter: 'blur(2px)',\n }}>\n <div style={{\n background: 'white', borderRadius: 12, padding: '2rem 2.5rem',\n textAlign: 'center', boxShadow: '0 8px 32px rgba(0,0,0,0.18)', minWidth: 240,\n display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 16,\n }}>\n <div style={{ width: 48, height: 48, position: 'relative' }}>\n {status === 'processing' && (\n <svg width=\"48\" height=\"48\" viewBox=\"0 0 24 24\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\"\n style={{ animation: 'flopay-spin 0.8s linear infinite' }}>\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 d=\"M7 12.5l3 3 7-7\" stroke=\"white\" strokeWidth=\"2.5\" strokeLinecap=\"round\" strokeLinejoin=\"round\"\n style={{ strokeDasharray: 20, strokeDashoffset: 20, animation: 'flopay-draw 0.4s 0.15s ease forwards' }} />\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 d=\"M8 8l8 8M16 8l-8 8\" stroke=\"white\" strokeWidth=\"2.5\" strokeLinecap=\"round\"\n style={{ strokeDasharray: 12, strokeDashoffset: 12, animation: 'flopay-draw 0.3s 0.1s ease forwards' }} />\n </svg>\n </div>\n )}\n </div>\n <span style={{\n fontSize: 14, fontWeight: 600, letterSpacing: '0.05em',\n color: status === 'success' ? '#16a34a' : status === 'error' ? '#dc2626' : '#374151',\n }}>\n {status === 'processing' && 'PROCESSING...'}\n {status === 'success' && 'PAYMENT SUCCESSFUL'}\n {status === 'error' && 'PAYMENT FAILED'}\n </span>\n {status === 'success' && (\n <p style={{\n fontSize: 13,\n color: '#6b7280',\n fontWeight: 400,\n maxWidth: 260,\n lineHeight: 1.4,\n margin: 0,\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 style={{\n fontSize: 13, color: '#6b7280', fontWeight: 400,\n maxWidth: 260, lineHeight: 1.4, margin: 0,\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\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 first name changes (from the name input). */\n onFirstNameChange?: (value: string) => void;\n /** Callback when last name changes (from the name input). */\n onLastNameChange?: (value: string) => void;\n /**\n * Show PayPal button above card fields. Defaults to `true`.\n * Uses Stripe's ExpressCheckoutElement in a separate Elements instance,\n * matching checkout/StripeCardForm architecture.\n */\n showPayPal?: boolean;\n /** Show Apple Pay button. Defaults to `true`. Only renders on supported devices. */\n showApplePay?: boolean;\n /** Show Google Pay button. Defaults to `true`. Only renders on supported devices. */\n showGooglePay?: boolean;\n /**\n * Layout mode for the payment form.\n * - `'default'` — all payment methods + card form shown together (current behavior)\n * - `'buttons'` — PayPal, wallets, and a \"Credit / Debit Card\" button; clicking the card\n * button expands the card form with a back button to return to the button view\n */\n layout?: 'default' | 'buttons';\n /**\n * Theme preset for the `buttons` layout. Ignored when `layout` is `'default'`.\n * - `'default'` — white card button, neutral borders\n * - `'minimal'` — borderless, subtle backgrounds\n * - `'rounded'` — large border radius, soft shadows\n * - `'dark'` — dark backgrounds, light text\n */\n buttonsTheme?: import('@flopay/shared').ButtonsLayoutTheme;\n /** Custom style overrides for the `buttons` layout. Merged on top of the theme preset. */\n buttonsStyles?: import('@flopay/shared').ButtonsLayoutStyles;\n /** Custom React content rendered inside the card button when `layout=\"buttons\"`. */\n cardButtonContent?: React.ReactNode;\n /** Custom React content rendered for the buttons-layout card back button label. */\n cardBackButtonContent?: React.ReactNode;\n /** Custom React content rendered for the card-form title. */\n cardTitleContent?: React.ReactNode;\n /**\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 the credit/debit card button continues.\n * Card only: this does not run for PayPal or wallet buttons.\n */\n onBeforeButtonClick?: (\n event: BeforeButtonClickEvent,\n ) => MaybePromise<void | false | InlineSessionPatch>;\n /**\n * Enable AVS (Address Verification). Shows country dropdown + ZIP/postcode input.\n * When enabled, billing_details are passed to Stripe's createPaymentMethod for AVS checks.\n */\n enableAVS?: boolean;\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 /** Callback when AVS country changes. */\n onCountryChange?: (country: string) => void;\n /** Callback when AVS ZIP/postal code changes. */\n onZipChange?: (zip: string) => void;\n /** Total amount in cents (smallest currency unit). Used for wallet/PayPal Elements config. */\n totalAmount?: number;\n /** Currency code (used for PayPal Elements config). */\n currency?: string;\n /** Render the card form expanded on first paint when `layout=\"buttons\"`. */\n initialCardOpen?: boolean;\n}\n\n/**\n * Split card checkout form matching `checkout/StripeCardForm`:\n * PayPal button → divider → CardNumber → CardExpiry + CardCVC → Full Name → Submit.\n *\n * PayPal uses its own Stripe Elements instance (no `paymentMethodCreation`)\n * exactly like checkout does with two separate `<Elements>` wrappers.\n */\nexport const SplitCardForm = forwardRef<SplitCardFormRef, SplitCardFormProps>(\n function SplitCardForm(props, ref) {\n return <SplitCardFormInner {...props} innerRef={ref} />;\n },\n);\n\n// ─── PayPal button (own Elements instance) ──────────────────────────────────\n// Mirrors checkout/StripeCardForm's StripePayPalButtonInner exactly.\n\nfunction PayPalButtonInner({\n sessionId,\n email,\n billingApiUrl,\n onTokenizedBody,\n onErrorChange,\n isProcessing = false,\n onButtonClick,\n onDecline,\n}: {\n sessionId: string;\n email?: string;\n billingApiUrl: string;\n onTokenizedBody: (body: TokenizedBody) => void;\n onErrorChange?: (error: string | null) => void;\n isProcessing?: boolean;\n onButtonClick?: (method: CheckoutButtonMethod) => void;\n onDecline?: (decline: DeclineEvent) => void;\n}) {\n const stripe = useStripeRaw();\n const elements = useStripeElements();\n const [ready, setReady] = useState(false);\n const [submitting, setSubmitting] = useState(false);\n const paypalResumeAttempted = useRef(false);\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 (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\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 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 // PayPal confirm handler — called by ExpressCheckoutElement onConfirm\n const handlePayPalConfirm = useCallback(async (_event: StripeExpressCheckoutElementConfirmEvent) => {\n if (!stripe || !elements) return;\n\n onButtonClick?.('paypal');\n\n try {\n setSubmitting(true);\n onErrorChange?.(null);\n\n if (!sessionId || !email) {\n throw new Error('Missing sessionId or email for PayPal payment');\n }\n\n // 1. Create PayPal PaymentMethod so backend can attach it to the intent\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 console.warn('[FloPay] Could not create PayPal PM upfront:', pmError.message);\n }\n\n // 2. Create PaymentIntent via backend with pm_xxx (or 'paypal' as fallback)\n // isPaypal must be string 'true' — backend checks === 'true'\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: paymentMethod?.id ?? 'paypal',\n isPaypal: 'true',\n }),\n });\n\n if (!intentResponse.ok) throw new Error('Failed to create payment intent');\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 // 3. Confirm payment — pass payment_method if available\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 // 4. Extract pm_xxx from confirmed intent.\n // Send the PM + PI id so the backend can capture the pre-authorized PI\n // and extract the reusable PM with the PayPal billing agreement.\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 } 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]);\n\n return (\n <>\n <div>\n <ExpressCheckoutElement\n onReady={() => setReady(true)}\n onLoadError={() => { /* PayPal not available — hide gracefully */ }}\n onConfirm={handlePayPalConfirm}\n onCancel={() => {\n onDecline?.(buildDeclineEvent('paypal', 'PayPal checkout was cancelled.'));\n }}\n options={{\n buttonType: { paypal: 'paypal' } as Record<string, string>,\n paymentMethods: {\n applePay: 'never',\n googlePay: 'never',\n paypal: 'auto',\n link: 'never',\n },\n } as Parameters<typeof ExpressCheckoutElement>[0]['options']}\n />\n </div>\n {submitting && <ProcessingOverlay status=\"processing\" />}\n </>\n );\n}\n\n// ─── Wallet buttons (Apple Pay / Google Pay — own Elements instance) ────────\n// Uses raw stripe + elements from its own StripeElements context,\n// matching checkout/StripeCardForm's handleExpressCheckoutConfirm exactly.\n\nfunction WalletButtonInner({\n sessionId,\n email,\n billingApiUrl,\n showApplePay = true,\n showGooglePay = true,\n onTokenizedBody,\n onErrorChange,\n onButtonClick,\n onDecline,\n}: {\n sessionId: string;\n email?: string;\n billingApiUrl: string;\n showApplePay?: boolean;\n showGooglePay?: boolean;\n onTokenizedBody: (body: TokenizedBody) => void;\n onErrorChange?: (error: string | null) => void;\n onButtonClick?: (method: CheckoutButtonMethod) => void;\n onDecline?: (decline: DeclineEvent) => void;\n}) {\n const stripe = useStripeRaw();\n const elements = useStripeElements();\n const [ready, setReady] = useState(false);\n const [submitting, setSubmitting] = useState(false);\n const baseUrl = billingApiUrl.replace(/\\/+$/, '');\n const lastWalletMethodRef = useRef<CheckoutButtonMethod>('card');\n\n const handleWalletConfirm = useCallback(\n async (_event: StripeExpressCheckoutElementConfirmEvent) => {\n if (!stripe || !elements) return;\n\n // Detect wallet type from the express checkout event\n const walletType = (_event as unknown as { expressPaymentType?: string }).expressPaymentType;\n onButtonClick?.(walletType === 'apple_pay' ? 'apple_pay' : 'google_pay');\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 (!sessionId || !email) {\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,\n email,\n paymentMethodType: paymentMethod.id,\n isPaypal: false,\n }),\n });\n\n if (!intentResponse.ok) throw new Error('Failed to create payment intent');\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 method = walletType === 'apple_pay' ? 'apple_pay' : 'google_pay';\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 } 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],\n );\n\n return (\n <>\n <div>\n <ExpressCheckoutElement\n onReady={() => setReady(true)}\n onLoadError={() => { /* wallets not available on this device — hide */ }}\n onClick={(event) => {\n lastWalletMethodRef.current = event.expressPaymentType === 'apple_pay' ? 'apple_pay' : 'google_pay';\n event.resolve();\n }}\n onConfirm={handleWalletConfirm}\n onCancel={() => {\n onDecline?.(buildDeclineEvent(lastWalletMethodRef.current, 'Wallet checkout was cancelled.'));\n }}\n options={{\n buttonType: { applePay: 'plain', googlePay: 'plain' } as Record<string, string>,\n paymentMethods: {\n applePay: showApplePay ? 'always' : 'never',\n googlePay: showGooglePay ? 'always' : 'never',\n paypal: 'never',\n link: 'never',\n amazonPay: 'never',\n klarna: 'never',\n },\n layout: { maxColumns: 1, overflow: 'never' },\n } as Parameters<typeof ExpressCheckoutElement>[0]['options']}\n />\n </div>\n {submitting && <ProcessingOverlay status=\"processing\" />}\n </>\n );\n}\n\n// ─── Main form ──────────────────────────────────────────────────────────────\n\nfunction SplitCardFormInner({\n sessionId,\n billingApiUrl,\n email,\n userId,\n onComplete,\n onError,\n onDecline,\n onTokenizedBody,\n firstName,\n lastName,\n chv,\n submitLabel = 'CONFIRM PAYMENT',\n className,\n children,\n isProcessing: externalProcessing,\n error: externalError,\n onErrorChange,\n onFirstNameChange,\n onLastNameChange,\n showPayPal = true,\n showApplePay = true,\n showGooglePay = true,\n layout = 'default',\n buttonsTheme,\n buttonsStyles: buttonsStylesOverride,\n cardButtonContent,\n cardBackButtonContent,\n cardTitleContent,\n onButtonClick,\n onBeforeButtonClick,\n enableAVS = false,\n avsLayout: avsLayoutProp = 'row',\n country: countryProp,\n zip: zipProp,\n onCountryChange,\n onZipChange,\n totalAmount = 0,\n currency = 'usd',\n initialCardOpen = false,\n innerRef,\n}: SplitCardFormProps & { innerRef: React.Ref<SplitCardFormRef> }) {\n const flopay = useFloPay();\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 const [selectedCountry, setSelectedCountry] = useState(countryProp ?? 'US');\n const [zipCode, setZipCode] = useState(zipProp ?? '');\n const [accountPatch, setAccountPatch] = useState<InlineSessionPatch['account']>({});\n const zipCodeRef = useRef(zipProp ?? '');\n const selectedCountryRef = useRef(countryProp ?? 'US');\n\n // Buttons ↔ Card transition state machine\n type ViewState = 'buttons' | 'expanding' | 'card' | 'collapsing';\n const [viewState, setViewState] = useState<ViewState>(initialCardOpen ? 'card' : 'buttons');\n const showCardForm = viewState === 'expanding' || viewState === 'card';\n const TRANSITION_MS = 280;\n\n const expandToCard = useCallback(() => {\n setViewState('expanding');\n setTimeout(() => setViewState('card'), TRANSITION_MS);\n }, []);\n\n const collapseToButtons = useCallback(() => {\n setViewState('collapsing');\n setTimeout(() => setViewState('buttons'), TRANSITION_MS);\n }, []);\n\n useEffect(() => {\n if (layout === 'buttons' && initialCardOpen) {\n setViewState('card');\n }\n }, [layout, initialCardOpen]);\n const [fullName, setFullName] = useState('');\n const [formReady, setFormReady] = useState(false);\n const [overlayStatus, setOverlayStatus] = useState<OverlayStatus | null>(null);\n const processingRef = useRef(false);\n\n const resolvedBillingApiUrl = billingApiUrl || contextBillingUrl;\n const displayError = externalError ?? error;\n\n // Resolve buttons layout styles: theme preset merged with custom overrides\n const bStyles = useMemo<ButtonsLayoutStyles>(() => {\n const base = resolveButtonsLayoutTheme(buttonsTheme);\n if (!buttonsStylesOverride) return base;\n return {\n ...base,\n ...buttonsStylesOverride,\n cardButton: { ...base.cardButton, ...buttonsStylesOverride.cardButton },\n cardFormContainer: { ...base.cardFormContainer, ...buttonsStylesOverride.cardFormContainer },\n backButton: { ...base.backButton, ...buttonsStylesOverride.backButton },\n backButtonIcon: { ...base.backButtonIcon, ...buttonsStylesOverride.backButtonIcon },\n submitButton: { ...base.submitButton, ...buttonsStylesOverride.submitButton },\n title: { ...base.title, ...buttonsStylesOverride.title },\n };\n }, [buttonsTheme, buttonsStylesOverride]);\n const isSubmitting = externalProcessing ?? processing;\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 PayPal Elements provider\n const stripeInstance = useMemo(() => {\n if (!flopay) return null;\n return flopay.getRawProvider() as Stripe | null;\n }, [flopay]);\n\n // totalAmount is in cents (smallest currency unit) when passed from FloPayCheckout.\n // Stripe Elements `amount` expects cents.\n const amountInCents = totalAmount || 100; // minimum 1 cent\n\n // Wallet (Apple/Google Pay) Elements options — uses paymentMethodCreation: 'manual'\n // to match the main card Elements, allowing explicit createPaymentMethod() calls.\n const walletOptions = useMemo(() => ({\n mode: 'payment' as const,\n amount: amountInCents,\n currency: currency.toLowerCase(),\n paymentMethodCreation: 'manual' as const,\n captureMethod: 'manual' as const,\n }), [amountInCents, currency]);\n\n // PayPal Elements options — no paymentMethodCreation (matches checkout)\n const paypalOptions = useMemo(() => ({\n mode: 'payment' as const,\n amount: amountInCents,\n currency: currency.toLowerCase(),\n captureMethod: 'manual' as const,\n }), [amountInCents, currency]);\n\n const updateError = useCallback(\n (err: string | null) => {\n setError(err);\n onErrorChange?.(err);\n },\n [onErrorChange],\n );\n\n const emitDecline = useCallback(\n (\n method: CheckoutButtonMethod,\n input: string | FloPayError,\n overrides?: { code?: string; declineCode?: string },\n ) => {\n onDecline?.(buildDeclineEvent(method, input, overrides));\n },\n [onDecline],\n );\n\n const showWallets = showApplePay || showGooglePay;\n\n const handleNameChange = useCallback((value: string) => {\n setFullName(value);\n const parts = value.trim().split(/\\s+/);\n onFirstNameChange?.(parts[0] ?? '');\n onLastNameChange?.(parts.length > 1 ? parts.slice(1).join(' ') : '');\n }, [onFirstNameChange, onLastNameChange]);\n\n const runBeforeCardButtonClick = useCallback(async (): Promise<boolean> => {\n if (!onBeforeButtonClick) return true;\n\n try {\n const result = await onBeforeButtonClick({\n method: 'card',\n sessionId: sessionId || undefined,\n });\n\n if (result === false) {\n return false;\n }\n\n if (result?.account) {\n setAccountPatch((prev) => ({ ...(prev ?? {}), ...result.account }));\n }\n\n return true;\n } catch (err) {\n const floPayErr = err instanceof FloPayError\n ? err\n : new FloPayError(\n err instanceof Error ? err.message : 'Card before-click hook failed.',\n 'validation_error',\n );\n updateError(floPayErr.message);\n onError?.(floPayErr);\n return false;\n }\n }, [onBeforeButtonClick, sessionId, updateError, onError]);\n\n // ── Internal processPayment + 3DS retry ──\n\n const processPaymentInternal = useCallback(\n async (tokenizedBody: TokenizedBody) => {\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 try {\n const response = await fetch(`${baseUrl}/v1/checkouts/sessions/process`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'x-user-id': resolvedAccount.userId ?? '',\n },\n body: JSON.stringify({\n sessionId,\n tokenizedData: tokenizedBody,\n accountData: {\n userId: resolvedAccount.userId ?? '',\n email: resolvedAccount.email ?? '',\n firstName: resolvedAccount.firstName ?? fullName.trim().split(/\\s+/)[0] ?? '',\n lastName: resolvedAccount.lastName ?? fullName.trim().split(/\\s+/).slice(1).join(' ') ?? '',\n ...(enableAVS ? { zip: zipCodeRef.current, country: selectedCountryRef.current } : {}),\n },\n chv,\n }),\n });\n\n if (response.ok) {\n setOverlayStatus('success');\n await new Promise((r) => setTimeout(r, 1200));\n onComplete?.({\n status: 'succeeded',\n paymentIntentId: tokenizedBody.threeDSecureActionResultTokenId,\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 const result = await flopay.confirmPayment({\n clientSecret: secret,\n returnUrl: window.location.href,\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 }\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 const stripeInstance = flopay.getRawProvider() as Stripe | null;\n if (!stripeInstance) {\n updateError('Payment provider 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 stripeInstance.confirmPayment({\n clientSecret: secret,\n confirmParams: confirmParams as { return_url: string },\n redirect: 'if_required',\n });\n\n if (confirmError) {\n setOverlayStatus('error');\n const message = confirmError.message ?? 'PayPal payment failed.';\n updateError(message);\n emitDecline('paypal', message, {\n code: confirmError.code,\n });\n }\n } catch (err) {\n setOverlayStatus('error');\n updateError(err instanceof Error ? err.message : 'PayPal authorization failed.');\n }\n return;\n }\n\n setOverlayStatus('error');\n const message = (json?.message as string) ?? 'Payment failed. Please try again.';\n updateError(message);\n emitDecline(tokenizedBody.isPaypal ? 'paypal' : 'card', message, {\n code: (json?.code ?? json?.gatewayErrorCode) as string | undefined,\n declineCode: (json?.declineCode ?? json?.gatewayDeclineReason) as string | undefined,\n });\n await new Promise((r) => setTimeout(r, 1500));\n } catch (err) {\n setOverlayStatus('error');\n updateError(err instanceof Error ? err.message : 'An unexpected error occurred');\n await new Promise((r) => setTimeout(r, 1500));\n } finally {\n setProcessing(false);\n setOverlayStatus(null);\n processingRef.current = false;\n }\n },\n [baseUrl, sessionId, resolvedAccount, fullName, chv, flopay, onComplete, onError, updateError, emitDecline],\n );\n\n const dispatchTokenizedBody = useCallback(\n (tokenizedBody: TokenizedBody) => {\n if (onTokenizedBody) {\n onTokenizedBody(tokenizedBody);\n } else {\n processPaymentInternal(tokenizedBody);\n }\n },\n [onTokenizedBody, processPaymentInternal],\n );\n\n // ── Imperative 3DS handler ──\n\n useImperativeHandle(innerRef, () => ({\n async handleNextAction(secret: string) {\n if (!flopay) return;\n\n setIs3DSActive(true);\n try {\n const result = await flopay.confirmPayment({\n clientSecret: secret,\n returnUrl: window.location.href,\n });\n\n if (result.error) {\n updateError(result.error.message);\n onError?.(result.error);\n emitDecline('card', result.error);\n } else if (result.status === 'succeeded' || result.status === 'processing') {\n dispatchTokenizedBody({\n id: result.paymentIntentId,\n type: 'card',\n threeDSecureActionResultTokenId: result.paymentIntentId,\n });\n }\n } catch (err) {\n updateError(err instanceof Error ? err.message : 'Payment authentication failed.');\n } finally {\n setIs3DSActive(false);\n }\n },\n }), [flopay, dispatchTokenizedBody, onError, updateError, emitDecline]);\n\n // ── Wallet resume ──\n\n useEffect(() => {\n if (typeof window === 'undefined') return;\n\n const stored = localStorage.getItem(WALLET_RESUME_KEY);\n if (!stored) return;\n\n try {\n const payload = JSON.parse(stored) as {\n sessionId: string;\n paymentIntentId: string;\n tokenType: string;\n tokenId: string;\n status: string;\n };\n\n if (payload.sessionId === sessionId) {\n localStorage.removeItem(WALLET_RESUME_KEY);\n dispatchTokenizedBody({\n id: payload.tokenId,\n type: payload.tokenType,\n threeDSecureActionResultTokenId: payload.paymentIntentId,\n });\n }\n } catch {\n localStorage.removeItem(WALLET_RESUME_KEY);\n }\n }, [sessionId, dispatchTokenizedBody]);\n\n // ── Card submit ──\n\n const handleSubmit = useCallback(\n async (e: React.FormEvent) => {\n e.preventDefault();\n if (!flopay || !elements || isSubmitting || processingRef.current) return;\n\n if (layout !== 'buttons') {\n onButtonClick?.('card');\n }\n setProcessing(true);\n setOverlayStatus('processing');\n updateError(null);\n\n // Track whether we handed off to processPaymentInternal (which manages its own overlay)\n let handedOff = false;\n\n try {\n // Matches checkout/StripeCardForm exactly:\n // 1. createPaymentMethod → 2. createPaymentIntent → 3. confirmCardPayment → 4. onTokenizedBody\n\n // 0. Validate AVS fields (required when enableAVS is true)\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 (enableAVS && !zipCodeRef.current.trim()) {\n updateError(getPostalCodeLabel(selectedCountryRef.current) + ' is required');\n return;\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 const billingDetails = enableAVS ? {\n name: fullName,\n address: {\n country: selectedCountryRef.current,\n postal_code: zipCodeRef.current,\n },\n } : undefined;\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) throw new FloPayError('Failed to create payment intent', 'api_error');\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, 1500));\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: pmResult.paymentMethodId,\n type: 'card',\n threeDSecureActionResultTokenId: confirmResult.paymentIntentId,\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, 1500));\n } finally {\n if (!handedOff) {\n setProcessing(false);\n setOverlayStatus(null);\n }\n }\n },\n [flopay, elements, isSubmitting, sessionId, resolvedAccount.email, baseUrl, isSelfContained, dispatchTokenizedBody, onButtonClick, onError, updateError, emitDecline, layout],\n );\n\n const isReady = flopay !== null && elements !== null;\n\n if (!isReady) {\n return <div data-testid=\"flopay-loading\" aria-busy=\"true\">Loading payment form...</div>;\n }\n\n const isButtons = layout === 'buttons';\n const resolvedBorder = isButtons ? (bStyles.cardInputBorder ?? '#e5e7eb') : '#A4A4FF';\n const cardBg = isButtons ? ((bStyles.cardFormContainer?.backgroundColor as string) ?? 'white') : '#EDEDFF';\n const cardInputBg = isButtons ? (bStyles.cardInputBackground ?? 'white') : 'white';\n const hideBackButtonLabel = isEmptySlotContent(cardBackButtonContent);\n const hideTitle = isEmptySlotContent(cardTitleContent);\n const nameInputOverrides = isButtons ? bStyles.nameInput : undefined;\n const resolvedInputFontSize = bStyles.cardInputFontSize\n ?? toCssSize(nameInputOverrides?.fontSize)\n ?? '16px';\n const resolvedInputFontFamily = typeof nameInputOverrides?.fontFamily === 'string'\n ? nameInputOverrides.fontFamily\n : 'Poppins, sans-serif';\n const resolvedInputFontWeight = toCssWeight(nameInputOverrides?.fontWeight) ?? 400;\n const resolvedInputColor = bStyles.cardInputColor\n ?? (typeof nameInputOverrides?.color === 'string' ? nameInputOverrides.color : undefined)\n ?? '#262833';\n const resolvedPlaceholderColor = bStyles.cardInputPlaceholderColor ?? '#9ca3af';\n const sharedInputTypography: React.CSSProperties = {\n fontSize: resolvedInputFontSize,\n fontFamily: resolvedInputFontFamily,\n fontWeight: resolvedInputFontWeight,\n color: resolvedInputColor,\n WebkitFontSmoothing: 'antialiased',\n MozOsxFontSmoothing: 'grayscale',\n };\n const sharedInputPlaceholderVars = {\n '--flopay-input-placeholder-color': resolvedPlaceholderColor,\n '--flopay-input-font-size': resolvedInputFontSize,\n '--flopay-input-font-family': resolvedInputFontFamily,\n '--flopay-input-font-weight': String(resolvedInputFontWeight),\n } as React.CSSProperties;\n\n // Stripe Element style — keeps the iframe typography aligned with the plain text inputs.\n const stripeElementStyle = {\n style: {\n base: {\n ...sharedInputTypography,\n fontSmoothing: 'antialiased',\n '::placeholder': {\n color: resolvedPlaceholderColor,\n fontSize: resolvedInputFontSize,\n fontFamily: resolvedInputFontFamily,\n fontWeight: resolvedInputFontWeight,\n },\n },\n invalid: { color: '#ef4444' },\n },\n };\n\n // ── Card fields block (shared between both layouts) ──\n const cardFormBlock = (\n <div style={{\n backgroundColor: cardBg, borderRadius: '8px',\n padding: isButtons ? '0' : '1rem',\n ...(isButtons ? bStyles.cardFormContainer as React.CSSProperties : {}),\n ...(isButtons ? { padding: bStyles.cardFormContainer?.padding ?? '0' } : {}),\n ...sharedInputPlaceholderVars,\n }}>\n <style>{`\n .flopay-shared-input::placeholder {\n color: var(--flopay-input-placeholder-color);\n opacity: 1;\n font-size: var(--flopay-input-font-size);\n font-family: var(--flopay-input-font-family);\n font-weight: var(--flopay-input-font-weight);\n }\n `}</style>\n {/* Header: back button + title on same row (buttons layout) */}\n {isButtons && showCardForm && (\n <div style={{\n display: 'flex', alignItems: 'center', padding: '0.75rem 0 0.625rem',\n }}>\n <button\n type=\"button\"\n onClick={collapseToButtons}\n style={{\n display: 'inline-flex', alignItems: 'center', gap: hideBackButtonLabel ? 0 : '0.5rem',\n background: 'none', border: 'none', cursor: 'pointer',\n color: '#4b5563', fontSize: bStyles.backButtonFontSize ?? '0.85rem', fontWeight: 500,\n padding: 0, transition: 'color 0.15s', flexShrink: 0,\n ...bStyles.backButton as React.CSSProperties,\n }}\n aria-label=\"Back to payment methods\"\n >\n <span style={{\n display: 'inline-flex', alignItems: 'center', justifyContent: 'center',\n width: 28, height: 28, borderRadius: '50%',\n backgroundColor: '#f3f4f6', transition: 'background-color 0.15s',\n ...bStyles.backButtonIcon as React.CSSProperties,\n }}>\n <svg width=\"14\" height=\"14\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2.5\" strokeLinecap=\"round\" strokeLinejoin=\"round\">\n <path d=\"M15 18l-6-6 6-6\" />\n </svg>\n </span>\n <BackButtonContentSlot content={cardBackButtonContent} />\n </button>\n {hideTitle ? (\n <div style={{ flex: 1 }} />\n ) : (\n <div style={{\n flex: 1, textAlign: 'center', fontWeight: 600,\n fontSize: bStyles.titleFontSize ?? '1.05rem',\n color: '#262833', paddingRight: 80,\n ...bStyles.title as React.CSSProperties,\n }}>\n <TitleContentSlot content={cardTitleContent} />\n </div>\n )}\n </div>\n )}\n\n {/* Title (default layout only) */}\n {!isButtons && !hideTitle && (\n <div style={{ textAlign: 'center', fontWeight: 600, fontSize: '1.1rem', padding: '0.5rem 0', color: '#262833' }}>\n <TitleContentSlot content={cardTitleContent} />\n </div>\n )}\n\n {/* Card Number */}\n <div style={{\n backgroundColor: cardInputBg, border: `1px solid ${resolvedBorder}`,\n borderTopLeftRadius: '8px', borderTopRightRadius: '8px', padding: '10px',\n }}>\n <CardNumberElement onReady={() => setFormReady(true)} options={stripeElementStyle} />\n </div>\n\n {/* Expiry + CVC */}\n <div style={{ display: 'flex' }}>\n <div style={{\n flex: 1, backgroundColor: cardInputBg, border: `1px solid ${resolvedBorder}`,\n borderTop: 'none', borderRight: 'none',\n borderBottomLeftRadius: '8px', padding: '10px',\n }}>\n <CardExpiryElement options={stripeElementStyle} />\n </div>\n <div style={{\n flex: 1, backgroundColor: cardInputBg, border: `1px solid ${resolvedBorder}`,\n borderTop: 'none', borderBottomRightRadius: '8px', padding: '10px',\n }}>\n <CardCvcElement options={stripeElementStyle} />\n </div>\n </div>\n\n {/* Full Name */}\n <div style={{\n backgroundColor: cardInputBg, border: `1px solid ${resolvedBorder}`,\n borderRadius: '8px', marginTop: '0.5rem', padding: '10px',\n }}>\n <input\n className=\"flopay-shared-input\"\n placeholder=\"Full Name on Card\"\n autoComplete=\"cc-name\"\n value={fullName}\n onChange={(e) => handleNameChange(e.target.value)}\n disabled={isSubmitting}\n required\n style={{\n width: '100%', border: 'none', outline: 'none', background: 'transparent',\n ...sharedInputTypography,\n ...(isButtons && bStyles.nameInput ? bStyles.nameInput as React.CSSProperties : {}),\n }}\n />\n </div>\n\n {/* AVS: Country + ZIP/Postcode */}\n {enableAVS && (\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 <div style={{\n flex: avsLayoutProp === 'row' ? 1 : undefined,\n backgroundColor: cardInputBg, border: `1px solid ${resolvedBorder}`,\n padding: '10px',\n ...(avsLayoutProp === 'row'\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 }}\n disabled={isSubmitting}\n autoComplete=\"country\"\n data-testid=\"flopay-country\"\n style={{\n width: '100%', border: 'none', outline: 'none', background: 'transparent',\n ...sharedInputTypography,\n cursor: 'pointer',\n ...(isButtons && bStyles.nameInput ? bStyles.nameInput as React.CSSProperties : {}),\n }}\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 <div style={{\n flex: avsLayoutProp === 'row' ? 1 : undefined,\n backgroundColor: cardInputBg, border: `1px solid ${resolvedBorder}`,\n padding: '10px',\n ...(avsLayoutProp === 'row'\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={{\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 </div>\n )}\n\n {displayError && (\n <div role=\"alert\" data-testid=\"flopay-error\" style={{\n margin: '0.75rem 0', padding: '0.625rem 0.875rem',\n background: '#FEF2F2', border: '1px solid #FECACA', borderRadius: '8px',\n color: '#991B1B', fontSize: '0.85rem', fontWeight: 600,\n display: 'flex', alignItems: 'center', gap: '0.5rem',\n ...(isButtons && bStyles.errorBanner ? bStyles.errorBanner as React.CSSProperties : {}),\n }}>\n <svg width=\"16\" height=\"16\" viewBox=\"0 0 24 24\" fill=\"none\" style={{ flexShrink: 0 }}>\n <path d=\"M12 9v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z\" stroke=\"#DC2626\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\" />\n </svg>\n {displayError}\n </div>\n )}\n\n {children ?? (\n <button\n type=\"submit\"\n disabled={!formReady || isSubmitting}\n data-testid=\"flopay-submit\"\n style={{\n width: '100%', padding: '0.875rem', marginTop: '1rem',\n backgroundColor: '#4A49FF', color: 'white', border: 'none',\n borderRadius: '8px',\n fontSize: (isButtons && bStyles.submitButtonFontSize) ? bStyles.submitButtonFontSize : '1rem',\n fontWeight: 600,\n cursor: !formReady || isSubmitting ? 'not-allowed' : 'pointer',\n opacity: !formReady || isSubmitting ? 0.5 : 1,\n ...((isButtons ? bStyles.submitButton : {}) as React.CSSProperties),\n }}\n >\n {isSubmitting ? 'PROCESSING...' : submitLabel}\n </button>\n )}\n\n {/* Security footer — only in default layout */}\n {!isButtons && (\n <div style={{\n backgroundColor: '#EFF9F0', borderRadius: '8px', padding: '0.75rem',\n marginTop: '0.75rem', textAlign: 'center', fontSize: '0.85rem',\n fontWeight: 600, color: '#7DAD3A',\n }}>\n Secure Card Checkout\n </div>\n )}\n </div>\n );\n\n // ── Buttons layout ──\n if (layout === 'buttons') {\n const isButtonsView = viewState === 'buttons' || viewState === 'expanding';\n const isCardView = viewState === 'expanding' || viewState === 'card' || viewState === 'collapsing';\n\n const buttonsAnim = viewState === 'expanding'\n ? `flopay-buttons-exit ${TRANSITION_MS}ms cubic-bezier(0.4, 0, 0.2, 1) both`\n : viewState === 'collapsing'\n ? `flopay-buttons-enter ${TRANSITION_MS}ms cubic-bezier(0, 0, 0.2, 1) both`\n : undefined;\n\n const cardAnim = viewState === 'expanding'\n ? `flopay-card-enter ${TRANSITION_MS}ms cubic-bezier(0, 0, 0.2, 1) both`\n : viewState === 'collapsing'\n ? `flopay-card-exit ${TRANSITION_MS}ms cubic-bezier(0.4, 0, 0.2, 1) both`\n : undefined;\n\n return (\n <form onSubmit={handleSubmit} className={className} style={{ position: 'relative' }}>\n <FloPayKeyframes />\n {overlayStatus && <ProcessingOverlay status={overlayStatus} errorMessage={displayError} />}\n\n {/* Container — uses grid overlap so both views can coexist during transition */}\n <div style={{ display: 'grid' }}>\n\n {/* Payment method buttons — always mounted to preserve PayPal/wallet Elements */}\n <div style={{\n gridArea: '1 / 1',\n display: 'flex', flexDirection: 'column', gap: '0.5rem',\n // When card form is showing (and not transitioning), hide but keep mounted\n ...(!isButtonsView && !buttonsAnim ? { visibility: 'hidden' as const, position: 'absolute' as const, pointerEvents: 'none' as const, width: '100%' } : {}),\n ...(buttonsAnim ? { animation: buttonsAnim, pointerEvents: 'none' as const } : {}),\n }}>\n {/* PayPal */}\n {showPayPal && stripeInstance ? (\n <StripeElements stripe={stripeInstance} 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 />\n </StripeElements>\n ) : showPayPal ? (\n <div style={{ height: 44, borderRadius: 8, background: '#e5e7eb', animation: 'flopay-pulse 1.5s ease-in-out infinite' }} />\n ) : null}\n\n {/* Wallets (Apple Pay / Google Pay) */}\n {showWallets && stripeInstance ? (\n <StripeElements stripe={stripeInstance} options={walletOptions}>\n <WalletButtonInner\n sessionId={sessionId}\n email={resolvedAccount.email}\n billingApiUrl={resolvedBillingApiUrl}\n showApplePay={showApplePay}\n showGooglePay={showGooglePay}\n onTokenizedBody={dispatchTokenizedBody}\n onErrorChange={updateError}\n onButtonClick={onButtonClick}\n onDecline={onDecline}\n />\n </StripeElements>\n ) : showWallets ? (\n <div style={{ height: 44, borderRadius: 8, background: '#e5e7eb', animation: 'flopay-pulse 1.5s ease-in-out infinite' }} />\n ) : null}\n\n {/* Credit / Debit Card button */}\n <button\n type=\"button\"\n onClick={async () => {\n const shouldContinue = await runBeforeCardButtonClick();\n if (!shouldContinue) return;\n onButtonClick?.('card');\n expandToCard();\n }}\n style={{\n width: '100%', padding: '0.9rem 1rem',\n backgroundColor: 'white', color: '#262833',\n border: '1px solid #d1d5db', borderRadius: '8px',\n fontSize: bStyles.cardButtonFontSize ?? '0.95rem', fontWeight: 600,\n cursor: 'pointer', display: 'flex',\n alignItems: 'center', justifyContent: 'center', gap: '0.625rem',\n transition: 'border-color 0.2s, box-shadow 0.2s, transform 0.1s',\n boxShadow: '0 1px 2px rgba(0,0,0,0.04)',\n position: 'relative',\n ...bStyles.cardButton as React.CSSProperties,\n }}\n onMouseDown={(e) => { e.currentTarget.style.transform = 'scale(0.985)'; }}\n onMouseUp={(e) => { e.currentTarget.style.transform = 'scale(1)'; }}\n >\n <CardButtonContentSlot content={cardButtonContent} />\n </button>\n\n {displayError && viewState === 'buttons' && (\n <div role=\"alert\" data-testid=\"flopay-error\" style={{\n margin: '0.25rem 0', padding: '0.625rem 0.875rem',\n background: '#FEF2F2', border: '1px solid #FECACA', borderRadius: '8px',\n color: '#991B1B', fontSize: '0.85rem', fontWeight: 600,\n display: 'flex', alignItems: 'center', gap: '0.5rem',\n ...(bStyles.errorBanner ? bStyles.errorBanner as React.CSSProperties : {}),\n }}>\n <svg width=\"16\" height=\"16\" viewBox=\"0 0 24 24\" fill=\"none\" style={{ flexShrink: 0 }}>\n <path d=\"M12 9v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z\" stroke=\"#DC2626\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\" />\n </svg>\n {displayError}\n </div>\n )}\n </div>\n\n {/* Card form */}\n {isCardView && (\n <div style={{\n gridArea: '1 / 1',\n ...(cardAnim ? { animation: cardAnim } : {}),\n ...(viewState === 'collapsing' ? { pointerEvents: 'none' as const } : {}),\n }}>\n {cardFormBlock}\n </div>\n )}\n </div>\n </form>\n );\n }\n\n // ── Default layout ──\n return (\n <form onSubmit={handleSubmit} className={className} style={{ position: 'relative' }}>\n <FloPayKeyframes />\n {overlayStatus && <ProcessingOverlay status={overlayStatus} errorMessage={displayError} />}\n\n {/* Wallet buttons (Apple Pay / Google Pay) — own Stripe Elements instance */}\n {showWallets && stripeInstance && (\n <StripeElements stripe={stripeInstance} options={walletOptions}>\n <WalletButtonInner\n sessionId={sessionId}\n email={resolvedAccount.email}\n billingApiUrl={resolvedBillingApiUrl}\n showApplePay={showApplePay}\n showGooglePay={showGooglePay}\n onTokenizedBody={dispatchTokenizedBody}\n onErrorChange={updateError}\n onDecline={onDecline}\n />\n </StripeElements>\n )}\n\n {/* PayPal — own Stripe Elements instance */}\n {showPayPal && stripeInstance && (\n <StripeElements stripe={stripeInstance} options={paypalOptions}>\n <PayPalButtonInner\n sessionId={sessionId}\n email={resolvedAccount.email}\n billingApiUrl={resolvedBillingApiUrl}\n onTokenizedBody={dispatchTokenizedBody}\n onErrorChange={updateError}\n isProcessing={isSubmitting}\n onDecline={onDecline}\n />\n </StripeElements>\n )}\n\n {/* Divider between wallet/PayPal buttons and card fields */}\n {((showWallets && stripeInstance) || (showPayPal && stripeInstance)) && (\n <div style={{\n display: 'flex', alignItems: 'center', gap: '0.75rem',\n margin: '0.5rem 0 0.75rem', color: '#999', fontSize: '0.85rem',\n }}>\n <div style={{ flex: 1, height: 1, backgroundColor: '#ddd' }} />\n <span>or pay with card</span>\n <div style={{ flex: 1, height: 1, backgroundColor: '#ddd' }} />\n </div>\n )}\n\n {cardFormBlock}\n </form>\n );\n}\n","import { useContext } from 'react';\nimport type { FloPay, FloPayElements } from '@flopay/js';\nimport type { CheckoutSession, FloPayError } from '@flopay/shared';\nimport { resolveBillingApiUrl } from '@flopay/shared';\nimport { FloPayContext, CheckoutContext } from './context.js';\nimport type { CheckoutContextValue } from './context.js';\n\n/**\n * Returns the current `FloPay` instance, or `null` if the provider\n * is still loading (i.e. the `loadFloPay()` promise has not resolved yet).\n *\n * Must be called within a `<FloPayProvider>`.\n */\nexport function useFloPay(): FloPay | null {\n const ctx = useContext(FloPayContext);\n return ctx.flopay;\n}\n\n/**\n * Returns the 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 type {\n CheckoutAccount,\n CheckoutButtonMethod,\n CheckoutMode,\n CheckoutSession,\n DeclineEvent,\n InlineSessionDraft,\n InlineSessionParams,\n InlineSessionPatch,\n} from '@flopay/shared';\nimport { FloPayError } from '@flopay/shared';\n\nexport function mergeInlineSessionPatches(\n base: InlineSessionPatch | undefined,\n patch: InlineSessionPatch | undefined,\n): InlineSessionPatch | undefined {\n if (!patch) return base;\n if (!base) return patch;\n\n return {\n account: { ...(base.account ?? {}), ...(patch.account ?? {}) },\n couponCodes: patch.couponCodes ?? base.couponCodes,\n tagsData: {\n ...(base.tagsData ?? {}),\n ...(patch.tagsData ?? {}),\n },\n utmMetadata: patch.utmMetadata ?? base.utmMetadata,\n };\n}\n\nexport function mergeInlineSessionPatch(\n params: InlineSessionDraft,\n patch: InlineSessionPatch | undefined,\n): InlineSessionDraft {\n if (!patch) return params;\n\n return {\n ...params,\n account: {\n ...params.account,\n ...(patch.account ?? {}),\n },\n couponCodes: patch.couponCodes ?? params.couponCodes,\n tagsData: {\n ...(params.tagsData ?? {}),\n ...(patch.tagsData ?? {}),\n },\n utmMetadata: patch.utmMetadata ?? params.utmMetadata,\n };\n}\n\nexport function buildSyntheticSession(\n params: InlineSessionDraft,\n checkoutModeOverride?: CheckoutMode,\n): CheckoutSession {\n const totalAmount = [\n ...(params.items ?? []).map((item) => (item.overrideAmount ?? item.totalAmount) ?? 0),\n ...(params.subscriptions ?? []).map((subscription) => (subscription.overrideAmount ?? subscription.totalAmount) ?? 0),\n ].reduce((sum, value) => sum + value, 0);\n const currency = params.items?.[0]?.currency\n ?? params.subscriptions?.[0]?.currency\n ?? 'USD';\n\n return {\n id: '',\n clientSecret: '',\n mode: 'payment',\n amount: Math.round(totalAmount * 100),\n currency,\n status: 'open',\n customer: {\n id: params.account.userId,\n email: params.account.email ?? '',\n firstName: params.account.firstName,\n lastName: params.account.lastName,\n gender: params.account.gender ?? undefined,\n city: params.account.city ?? undefined,\n state: params.account.state ?? undefined,\n country: params.account.country ?? undefined,\n zip: params.account.zip ?? undefined,\n },\n successUrl: params.successUrl,\n cancelUrl: params.cancelUrl,\n checkoutMode: (params.checkoutMode ?? checkoutModeOverride ?? 'full') as CheckoutMode,\n items: (params.items ?? []).map((item, idx) => ({\n uuid: `synthetic-item-${idx}`,\n checkoutSessionId: '',\n providerItemId: item.providerItemId,\n providerItemName: item.providerItemName ?? item.providerItemId,\n quantity: item.quantity ?? 1,\n totalAmount: item.totalAmount,\n overrideAmount: item.overrideAmount ?? null,\n currency: item.currency ?? currency,\n })),\n subscriptions: (params.subscriptions ?? []).map((subscription, idx) => ({\n uuid: `synthetic-sub-${idx}`,\n checkoutSessionId: '',\n providerPlanId: subscription.providerPlanId,\n providerPlanName: subscription.providerPlanName ?? subscription.providerPlanId,\n quantity: subscription.quantity ?? 1,\n totalAmount: subscription.totalAmount,\n overrideAmount: subscription.overrideAmount ?? null,\n currency: subscription.currency ?? currency,\n })),\n };\n}\n\nexport function ensureInlineSessionReady(\n params: InlineSessionDraft,\n): asserts params is InlineSessionParams {\n if (!params.account.email?.trim()) {\n throw new FloPayError(\n 'Email is required before continuing with card checkout.',\n 'validation_error',\n { param: 'createSession.account.email' },\n );\n }\n}\n\nexport function splitFullName(name: string | null | undefined): {\n firstName?: string;\n lastName?: string;\n} {\n const parts = name?.trim().split(/\\s+/).filter(Boolean) ?? [];\n if (parts.length === 0) return {};\n return {\n firstName: parts[0],\n lastName: parts.length > 1 ? parts.slice(1).join(' ') : undefined,\n };\n}\n\nexport function mergeAccountPatch<T extends {\n userId?: string;\n email?: string;\n firstName?: string;\n lastName?: string;\n country?: string | null;\n zip?: string | null;\n}>(\n base: T,\n patch: Partial<CheckoutAccount> | undefined,\n): T {\n if (!patch) return base;\n return {\n ...base,\n ...patch,\n };\n}\n\nexport function buildDeclineEvent(\n method: CheckoutButtonMethod,\n input: string | FloPayError,\n overrides?: {\n code?: string;\n declineCode?: string;\n },\n): DeclineEvent {\n const message = typeof input === 'string' ? input : input.message;\n const code = typeof input === 'string' ? overrides?.code : overrides?.code ?? input.code;\n const declineCode = typeof input === 'string'\n ? overrides?.declineCode\n : overrides?.declineCode ?? input.declineCode;\n\n return {\n method,\n message,\n ...(code ? { code } : {}),\n ...(declineCode ? { declineCode } : {}),\n };\n}\n","import type {\n DeclineEvent,\n PaymentResult,\n TokenizedBody,\n} from '@flopay/shared';\nimport { FloPayError } from '@flopay/shared';\nimport React, { forwardRef, useCallback, useEffect, useImperativeHandle, useState } from 'react';\nimport { useFloPay, useElements, useBillingApiUrl } from './hooks.js';\nimport { PaymentElement } from './elements.js';\nimport { AddressElement } from './elements.js';\nimport { buildDeclineEvent } 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 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 (tokenizedBody: TokenizedBody) => {\n setProcessing(true);\n updateError(null);\n\n try {\n const response = await fetch(`${baseUrl}/v1/checkouts/sessions/process`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'x-user-id': userId ?? '',\n },\n body: JSON.stringify({\n sessionId,\n tokenizedData: tokenizedBody,\n accountData: {\n userId: userId ?? '',\n email: email ?? '',\n firstName: firstName ?? '',\n lastName: lastName ?? '',\n },\n chv,\n }),\n });\n\n if (response.ok) {\n onComplete?.({\n status: 'succeeded',\n paymentIntentId: tokenizedBody.threeDSecureActionResultTokenId,\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 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 return;\n }\n\n if (result.status === 'succeeded' || result.status === 'processing') {\n // Resubmit with 3DS result — only send the 3DS token, not original card token\n await processPaymentInternal({\n id: result.paymentIntentId,\n type: 'card',\n threeDSecureActionResultTokenId: result.paymentIntentId,\n });\n }\n } finally {\n setIs3DSActive(false);\n }\n return;\n }\n\n // PayPal redirect required\n if (json?.type === 'paypal_redirect_required') {\n const secret = json['clientSecret'] as string;\n const pmId = json['paymentMethodId'] as string;\n if (flopay && secret) {\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 await flopay.confirmPayment({\n clientSecret: secret,\n returnUrl: window.location.href,\n });\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, onComplete, onError, 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\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 pmResult = await flopay.createPaymentMethod();\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) throw new FloPayError('Failed to create payment intent', 'api_error');\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 // 5. Send PM + PI to processPaymentInternal (or parent via onTokenizedBody)\n dispatchTokenizedBody({\n id: pmResult.paymentMethodId,\n type: 'card',\n threeDSecureActionResultTokenId: confirmResult.paymentIntentId,\n });\n } catch (err) {\n updateError(err instanceof Error ? err.message : 'An unexpected error occurred');\n } finally {\n if (isSelfContained) {\n // processing state managed by processPaymentInternal\n } else {\n setProcessing(false);\n }\n }\n },\n [flopay, elements, isSubmitting, sessionId, email, baseUrl, isSelfContained, dispatchTokenizedBody, onError, updateError, emitDecline],\n );\n\n const isReady = flopay !== null && elements !== null;\n\n return (\n <form onSubmit={handleSubmit} className={className} style={{ position: 'relative' }}>\n {(is3DSActive || isSubmitting) && (\n <div data-testid=\"flopay-overlay\" style={{\n position: 'absolute', inset: 0,\n background: 'rgba(255,255,255,0.7)',\n display: 'flex', alignItems: 'center', justifyContent: 'center',\n zIndex: 10,\n }}>\n {is3DSActive ? 'Verifying payment...' : 'Processing...'}\n </div>\n )}\n\n {!isReady && (\n <div data-testid=\"flopay-loading\" aria-busy=\"true\">\n Loading payment form...\n </div>\n )}\n\n {isReady && (\n <>\n <PaymentElement options={{ layout }} />\n\n {showAddress && (\n <AddressElement options={{ mode: showAddress === true ? 'billing' : showAddress }} />\n )}\n\n {displayError && (\n <div role=\"alert\" data-testid=\"flopay-error\" style={{ color: 'red', margin: '0.75rem 0' }}>\n {displayError}\n </div>\n )}\n\n {children ?? (\n <button\n type=\"submit\"\n disabled={isSubmitting || !isReady}\n data-testid=\"flopay-submit\"\n >\n {isSubmitting ? 'Processing...' : submitLabel}\n </button>\n )}\n </>\n )}\n </form>\n );\n}\n","import type { TokenizedBody } from '@flopay/shared';\nimport { FloPayError } from '@flopay/shared';\nimport React, { useCallback, useEffect, useRef, useState } from 'react';\nimport { useFloPay, useElements, useBillingApiUrl } from './hooks.js';\n\n/**\n * Props for the `PayPalButton` component.\n *\n * Must be rendered inside its own `FloPayProvider` with `paymentMethodCreation: undefined`\n * (not 'manual') — PayPal cannot share the same Elements instance as card fields.\n */\nexport interface PayPalButtonProps {\n /** The checkout session ID (UUID from billing API). */\n sessionId: string;\n /** Billing API base URL. Optional — defaults to the value from FloPayProvider or the shared constant. */\n billingApiUrl?: string;\n /** User's email. */\n email?: string;\n /** User ID for processing payments. */\n userId?: string;\n /** First name for billing. */\n firstName?: string;\n /** Last name for billing. */\n lastName?: string;\n /** Checkout version for tracking. */\n chv?: string;\n /**\n * Called with tokenized data after PayPal authorization.\n * If omitted, the component calls processPayment internally.\n */\n onTokenizedBody?: (body: TokenizedBody) => void;\n /** Called on successful payment (self-contained mode). */\n onComplete?: () => void;\n /** Called when an error occurs. */\n onErrorChange?: (error: string | null) => void;\n /** External processing state. */\n isProcessing?: boolean;\n}\n\n/**\n * PayPal button that handles the full PayPal payment flow.\n *\n * **Important**: PayPal requires its own `FloPayProvider` — it cannot share\n * the same Stripe Elements instance as card fields when they use\n * `paymentMethodCreation: 'manual'`. This matches `checkout/StripeCardForm`\n * which renders PayPal in a separate `<Elements>` wrapper.\n *\n * ```tsx\n * {/* Card fields provider (paymentMethodCreation: 'manual') *\\/}\n * <FloPayProvider flopay={flopay} options={{ amount, currency }}>\n * <SplitCardForm ... />\n * </FloPayProvider>\n *\n * {/* PayPal provider (no paymentMethodCreation) *\\/}\n * <FloPayProvider flopay={flopay} options={{ amount, currency, paymentMethodCreation: 'auto' }}>\n * <PayPalButton ... />\n * </FloPayProvider>\n * ```\n */\nexport function PayPalButton({\n sessionId,\n billingApiUrl,\n email,\n userId,\n firstName,\n lastName,\n chv,\n onTokenizedBody,\n onComplete,\n onErrorChange,\n isProcessing = false,\n}: PayPalButtonProps): React.ReactElement {\n const flopay = useFloPay();\n const elements = useElements();\n const contextBillingUrl = useBillingApiUrl();\n const [ready, setReady] = useState(false);\n const [submitting, setSubmitting] = useState(false);\n const paypalResumeAttempted = useRef(false);\n const baseUrl = (billingApiUrl || contextBillingUrl).replace(/\\/+$/, '');\n\n // ── Internal processPayment (self-contained mode) ──\n\n const processPaymentInternal = useCallback(\n async (tokenizedBody: TokenizedBody) => {\n try {\n const response = await fetch(`${baseUrl}/v1/checkouts/sessions/process`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'x-user-id': userId ?? '',\n },\n body: JSON.stringify({\n sessionId,\n tokenizedData: tokenizedBody,\n accountData: {\n userId: userId ?? '',\n email: email ?? '',\n firstName: firstName ?? '',\n lastName: lastName ?? '',\n },\n chv,\n }),\n });\n\n if (response.ok) {\n onComplete?.();\n return;\n }\n\n const json = await response.json().catch(() => null) as Record<string, unknown> | null;\n onErrorChange?.((json?.message as string) ?? 'Payment failed. Please try again.');\n } catch (err) {\n onErrorChange?.(err instanceof Error ? err.message : 'An unexpected error occurred');\n }\n },\n [baseUrl, sessionId, userId, email, firstName, lastName, chv, onComplete, onErrorChange],\n );\n\n const dispatchTokenizedBody = useCallback(\n (body: TokenizedBody) => {\n if (onTokenizedBody) {\n onTokenizedBody(body);\n } else {\n processPaymentInternal(body);\n }\n },\n [onTokenizedBody, processPaymentInternal],\n );\n\n // ── Resume PayPal redirect return ──\n\n useEffect(() => {\n if (!flopay || paypalResumeAttempted.current) return;\n\n const params = new URLSearchParams(window.location.search);\n const paymentIntentId = params.get('payment_intent');\n const clientSecret = params.get('payment_intent_client_secret');\n const redirectStatus = params.get('redirect_status');\n\n if (!paymentIntentId || !clientSecret) return;\n paypalResumeAttempted.current = true;\n\n (async () => {\n try {\n setSubmitting(true);\n\n if (redirectStatus === 'failed') {\n onErrorChange?.('PayPal payment was declined. Please try again.');\n return;\n }\n\n // Retrieve the PaymentIntent to check status (matches checkout/StripeCardForm resume)\n const provider = flopay.getRawProvider() as { retrievePaymentIntent?: (cs: string) => Promise<{ paymentIntent?: { id: string; status: string; payment_method: string | { id: string } }; error?: { message: string } }> } | null;\n if (!provider?.retrievePaymentIntent) {\n onErrorChange?.('Cannot retrieve PayPal payment status.');\n return;\n }\n\n const { paymentIntent, error: retrieveError } = await provider.retrievePaymentIntent(clientSecret);\n if (retrieveError) {\n onErrorChange?.(retrieveError.message ?? 'Failed to retrieve PayPal payment status.');\n return;\n }\n\n if (paymentIntent && (paymentIntent.status === 'requires_capture' || paymentIntent.status === 'succeeded')) {\n const pmId = typeof paymentIntent.payment_method === 'string'\n ? paymentIntent.payment_method\n : paymentIntent.payment_method?.id;\n\n dispatchTokenizedBody({\n id: pmId ?? paymentIntent.id,\n type: 'card',\n threeDSecureActionResultTokenId: paymentIntent.id,\n isPaypal: true,\n });\n\n // Clean up URL params\n const url = new URL(window.location.href);\n url.searchParams.delete('payment_intent');\n url.searchParams.delete('payment_intent_client_secret');\n url.searchParams.delete('redirect_status');\n window.history.replaceState({}, '', url.toString());\n } else {\n onErrorChange?.('PayPal payment was not completed. Please try again.');\n }\n } catch (err) {\n onErrorChange?.(err instanceof Error ? err.message : 'Failed to complete PayPal payment.');\n } finally {\n setSubmitting(false);\n }\n })();\n }, [flopay, dispatchTokenizedBody, onErrorChange]);\n\n // ── PayPal confirm handler ──\n\n const handlePayPalConfirm = useCallback(async () => {\n if (!flopay || !elements) return;\n\n try {\n setSubmitting(true);\n onErrorChange?.(null);\n\n if (!sessionId || !email) {\n throw new FloPayError('Missing sessionId or email for PayPal payment', 'validation_error');\n }\n\n // 1. Create PaymentIntent via billing API with PayPal flag\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: 'paypal',\n isPaypal: 'true',\n }),\n });\n\n if (!intentResponse.ok) throw new FloPayError('Failed to create payment intent', 'api_error');\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 response', 'api_error');\n\n // 2. Confirm payment — PayPal will redirect\n const result = await flopay.confirmPayment({\n clientSecret: intentClientSecret,\n returnUrl: window.location.href,\n });\n\n // If we get here without redirect, payment completed inline\n if (result.status === 'succeeded' || result.status === 'processing') {\n dispatchTokenizedBody({\n id: result.paymentIntentId,\n type: 'card',\n threeDSecureActionResultTokenId: result.paymentIntentId,\n isPaypal: true,\n });\n } else if (result.error) {\n onErrorChange?.(result.error.message);\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"],"mappings":";AAAA,SAAgB,WAAW,UAAU,eAAe;AAGpD,SAAS,4BAA4B;;;ACHrC,SAAS,qBAAqB;AAmBvB,IAAM,gBAAgB,cAAkC;AAAA,EAC7D,QAAQ;AAAA,EACR,UAAU;AAAA,EACV,eAAe;AACjB,CAAC;AAEM,IAAM,kBAAkB,cAAoC;AAAA,EACjE,SAAS;AAAA,EACT,SAAS;AAAA,EACT,OAAO;AACT,CAAC;;;ADmEG;AA1DG,SAAS,eAAe;AAAA,EAC7B,QAAQ;AAAA,EACR;AAAA,EACA;AACF,GAA4C;AAC1C,QAAM,CAAC,QAAQ,SAAS,IAAI;AAAA,IAC1B,sBAAsB,UAAU,OAAO;AAAA,EACzC;AACA,QAAM,CAAC,UAAU,WAAW,IAAI,SAAgC,IAAI;AAGpE,YAAU,MAAM;AACd,QAAI,YAAY;AAEhB,QAAI,sBAAsB,SAAS;AACjC,iBAAW,KAAK,CAAC,aAAa;AAC5B,YAAI,CAAC,WAAW;AACd,oBAAU,QAAQ;AAAA,QACpB;AAAA,MACF,CAAC;AAAA,IACH,OAAO;AACL,gBAAU,UAAU;AAAA,IACtB;AAEA,WAAO,MAAM;AACX,kBAAY;AAAA,IACd;AAAA,EACF,GAAG,C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B,uBAAa,kBAAkB;AAAA;AAAA,IAClC,GACF;AAAA,KAEE,cAAc,iBACd,gBAAAA,KAAC,SAAI,OAAO;AAAA,MACV,UAAU;AAAA,MAAS,OAAO;AAAA,MAAG,YAAY;AAAA,MACzC,SAAS;AAAA,MAAQ,YAAY;AAAA,MAAU,gBAAgB;AAAA,MAAU,QAAQ;AAAA,IAC3E,GACE,0BAAAA,KAAC,SAAI,OAAO;AAAA,MACV,YAAY;AAAA,MAAS,cAAc;AAAA,MAAG,SAAS;AAAA,MAC/C,WAAW;AAAA,MAAU,WAAW;AAAA,MAA+B,OAAO;AAAA,IACxE,GAAG,0CAEH,GACF;AAAA,KAEJ;AAEJ;","names":["React","useCallback","useEffect","useMemo","useRef","useState","FloPayError","resolveBillingApiUrl","resolveButtonsLayoutTheme","jsx","useEffect","jsx","useEffect","useEffect","useMemo","useRef","useState","useContext","resolveBillingApiUrl","useContext","resolveBillingApiUrl","FloPayError","Fragment","jsx","jsxs","SplitCardForm","useState","useRef","useEffect","useMemo","stripeInstance","message","Fragment","jsx","jsxs","resolveBillingApiUrl","useState","useRef","useMemo","useEffect","useCallback","FloPayError","React","resolveButtonsLayoutTheme","FloPayError","forwardRef","useCallback","useEffect","useImperativeHandle","useState","Fragment","jsx","jsxs","WALLET_RESUME_KEY","forwardRef","CheckoutForm","useState","useCallback","useImperativeHandle","useEffect","FloPayError","FloPayError","useCallback","useEffect","useRef","useState","Fragment","jsx","jsxs","useState","useRef","useCallback","useEffect","FloPayError"]}
1
+ {"version":3,"sources":["../src/provider.tsx","../src/context.ts","../src/flopay-checkout.tsx","../src/card-button-content.tsx","../src/elements.tsx","../src/split-card-form.tsx","../src/hooks.ts","../src/checkout-utils.ts","../src/checkout-form.tsx","../src/paypal-button.tsx"],"sourcesContent":["import React, { useEffect, useState, useMemo } from 'react';\nimport type { FloPay, FloPayElements } from '@flopay/js';\nimport type { FloPayAppearance } from '@flopay/shared';\nimport { resolveBillingApiUrl } from '@flopay/shared';\nimport { FloPayContext } from './context.js';\n\n/** Props for the `FloPayProvider` component. */\nexport interface FloPayProviderProps {\n /** A `FloPay` instance or a promise that resolves to one (from `loadFloPay()`). */\n flopay: Promise<FloPay> | FloPay;\n /** 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 /** 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 options,\n children,\n}: FloPayProviderProps): React.ReactElement {\n const [flopay, setFloPay] = useState<FloPay | null>(\n floPayProp instanceof Promise ? null : floPayProp,\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 // 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 });\n setElements(els);\n\n return () => {\n els.destroy();\n };\n }, [flopay, options?.appearance, options?.clientSecret, options?.amount, options?.currency]);\n\n const resolvedBillingApiUrl = resolveBillingApiUrl(options?.billingApiUrl);\n\n const value = useMemo(\n () => ({ flopay, elements, billingApiUrl: resolvedBillingApiUrl }),\n [flopay, 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 InlineSessionPatch,\n} from '@flopay/shared';\n\n/** Internal context value for the FloPay provider. */\nexport interface FloPayContextValue {\n flopay: 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 applyInlineSessionPatch?: (patch: InlineSessionPatch) => Promise<void>;\n inlineSessionPatchProcessing?: boolean;\n}\n\nexport const FloPayContext = createContext<FloPayContextValue>({\n flopay: 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 { loadFloPay, 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 { FloPayError, resolveBillingApiUrl, buildCheckoutDisplayData, resolveButtonsLayoutTheme } from '@flopay/shared';\nimport type { ButtonsLayoutStyles, ButtonsLayoutTheme } from '@flopay/shared';\nimport {\n BackButtonContentSlot,\n CardButtonContentSlot,\n TitleContentSlot,\n isEmptySlotContent,\n} from './card-button-content.js';\nimport { FloPayProvider } from './provider.js';\nimport { SplitCardForm } from './split-card-form.js';\nimport { CheckoutContext } from './context.js';\nimport {\n buildDeclineEvent,\n buildSyntheticSession,\n mergeInlineSessionPatch,\n mergeInlineSessionPatches,\n} from './checkout-utils.js';\n\n/** Props for the all-in-one `FloPayCheckout` wrapper. */\nexport interface FloPayCheckoutProps {\n /** The checkout session ID (UUID from billing API). Required unless `createSession` is provided. */\n sessionId?: string;\n /**\n * Create a checkout session inline — no separate API route needed.\n * The component POSTs to the billing API, gets the full session back, and renders the form.\n * Alternative to `sessionId` (provide one or the other).\n */\n createSession?: InlineSessionDraft;\n /** Billing API base URL. Defaults to the shared `BILLING_API_URL` constant. */\n billingApiUrl?: string;\n /** Visual appearance for payment elements. */\n appearance?: FloPayAppearance;\n /** Locale for payment elements (default: 'auto'). */\n locale?: string;\n /**\n * Fallback Stripe publishable key — used only if the session response\n * doesn't include `gatewayData.publishableKey`.\n *\n * When the backend returns full session data (e.g. via `createSession`\n * with `?expand=true`), the response's `gatewayData.publishableKey` is\n * the single source of truth and this prop is not needed.\n */\n fallbackPublishableKey?: 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 /** Whether to show the PayPal button (default: true). */\n showPayPal?: boolean;\n /** Whether to show Apple Pay button (default: true). Only renders on supported devices. */\n showApplePay?: boolean;\n /** Whether to show Google Pay button (default: true). Only renders on supported devices. */\n showGooglePay?: boolean;\n /** Layout mode: 'default' (all visible) or 'buttons' (PayPal/wallets + expandable card form). */\n layout?: 'default' | 'buttons';\n /** Theme preset for the buttons layout: 'default', 'minimal', 'rounded', or 'dark'. */\n buttonsTheme?: import('@flopay/shared').ButtonsLayoutTheme;\n /** Custom style overrides for the buttons layout. Merged on top of the theme preset. */\n buttonsStyles?: import('@flopay/shared').ButtonsLayoutStyles;\n /** Custom React content rendered inside the card button when `layout=\"buttons\"`. */\n cardButtonContent?: React.ReactNode;\n /** Custom React content rendered for the buttons-layout card back button label. */\n cardBackButtonContent?: React.ReactNode;\n /** Custom React content rendered for the card-form title. */\n cardTitleContent?: React.ReactNode;\n /**\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 the credit/debit card button continues.\n * Card only: this does not run for PayPal or wallet buttons.\n * In `layout=\"buttons\"` with `createSession`, the returned patch is merged\n * into the inline session params before the real card session is created.\n */\n onBeforeButtonClick?: (\n event: BeforeButtonClickEvent,\n ) => void | false | Promise<void | false | InlineSessionPatch> | InlineSessionPatch;\n /**\n * Enable AVS (Address Verification). Shows country dropdown + ZIP/postcode input\n * in the card form. When enabled, billing_details are passed to Stripe for AVS checks.\n */\n enableAVS?: boolean;\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 /**\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\nfunction hasInlineSessionPatchData(\n patch: InlineSessionPatch | undefined,\n): boolean {\n if (!patch) return false;\n\n return Boolean(\n (patch.account && Object.keys(patch.account).length > 0)\n || patch.couponCodes !== undefined\n || patch.tagsData !== undefined\n || patch.utmMetadata !== undefined,\n );\n}\n\n/**\n * All-in-one checkout component. Fetches the session, initializes the\n * payment provider, and renders the appropriate UI based on checkout mode.\n *\n * **Modes:**\n * - `full` (default) — renders `SplitCardForm` with card fields + wallet buttons\n * - `confirm` — renders a \"Confirm Purchase\" button, uses saved payment method\n * - `auto` — auto-submits with saved PM, falls back to `full` on failure\n *\n * ```tsx\n * <FloPayCheckout\n * sessionId=\"sess_abc123\"\n * onComplete={(result) => router.push('/success')}\n * onError={(err) => console.error(err)}\n * />\n * ```\n */\nexport function FloPayCheckout({\n sessionId: sessionIdProp,\n createSession: createSessionParams,\n billingApiUrl,\n appearance,\n locale,\n fallbackPublishableKey,\n loading: loadingNode,\n error: errorNode,\n onComplete,\n onError,\n onDecline,\n showPayPal = true,\n showApplePay = true,\n showGooglePay = true,\n layout,\n buttonsTheme,\n buttonsStyles,\n cardButtonContent,\n cardBackButtonContent,\n cardTitleContent,\n onButtonClick,\n onBeforeButtonClick,\n enableAVS,\n avsLayout,\n submitLabel,\n className,\n children,\n checkoutMode: checkoutModeProp,\n confirmLabel,\n renderConfirmButton,\n onSessionCompleted,\n}: FloPayCheckoutProps): React.ReactElement {\n const resolvedBillingUrl = resolveBillingApiUrl(billingApiUrl);\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 [session, setSession] = useState<CheckoutSession | null>(null);\n const [resolvedSessionId, setResolvedSessionId] = useState<string>(sessionIdProp ?? '');\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>(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\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 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 effectiveCreateSession = useMemo(\n () => createSessionParams\n ? mergeInlineSessionPatch(createSessionParams, activeCreateSessionPatch)\n : undefined,\n [createSessionParams, activeCreateSessionPatch],\n );\n\n useEffect(() => {\n setCreateSessionPatch(undefined);\n setCreateSessionPatchBaseHash(baseCreateSessionHash);\n }, [baseCreateSessionHash]);\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 /** Response from the process endpoint when additional auth is needed. */\n type ProcessRedirectResult = {\n type: 'paypal_redirect_required' | '3ds_required';\n threeDSecureToken: string;\n paymentMethodId?: string;\n };\n\n // ── Process payment for auto/confirm modes ──\n // Returns null on success, or a redirect result if PayPal/3DS auth is needed.\n\n const processPaymentForMode = useCallback(\n async (sess: CheckoutSession): Promise<ProcessRedirectResult | null> => {\n const baseUrl = resolvedBillingUrl.replace(/\\/+$/, '');\n const response = await fetch(`${baseUrl}/v1/checkouts/sessions/process`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'x-user-id': sess.customer?.id ?? '',\n },\n body: JSON.stringify({\n sessionId: resolvedSessionId,\n tokenizedData: { id: undefined },\n accountData: {\n userId: sess.customer?.id ?? '',\n email: sess.customer?.email ?? '',\n firstName: sess.customer?.firstName ?? '',\n lastName: sess.customer?.lastName ?? '',\n },\n }),\n });\n\n if (response.ok) {\n onCompleteRef.current?.({ status: 'succeeded' });\n return null;\n }\n\n const json = (await response.json().catch(() => null)) as Record<\n string,\n unknown\n > | null;\n\n // PayPal or 3DS required — return the redirect data so the caller\n // can handle it after Stripe is initialized.\n if (\n (json?.type === 'paypal_redirect_required' ||\n json?.type === '3ds_required') &&\n json?.threeDSecureToken\n ) {\n return {\n type: json.type as ProcessRedirectResult['type'],\n threeDSecureToken: json.threeDSecureToken as string,\n paymentMethodId: json.paymentMethodId as string | undefined,\n };\n }\n\n // Card requires authentication but backend didn't provide a client\n // secret (authentication_required from Stripe). Treat as 3DS required\n // so the caller can fall back to full mode or trigger 3DS.\n if (json?.gatewayErrorCode === 'authentication_required') {\n return {\n type: '3ds_required' as const,\n threeDSecureToken: '', // No client secret available\n };\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 [resolvedBillingUrl, resolvedSessionId],\n );\n\n // ── Handle redirect results (3DS / PayPal) using Stripe ──\n\n const handleRedirectResult = useCallback(\n async (\n redirectResult: ProcessRedirectResult,\n sess: CheckoutSession,\n options?: { attempt3DS?: boolean },\n ): Promise<boolean> => {\n const stripe = flopayRef.current?.getRawProvider() as import('@stripe/stripe-js').Stripe | null;\n if (!stripe) return false;\n\n if (redirectResult.type === '3ds_required') {\n if (!options?.attempt3DS || !redirectResult.threeDSecureToken) {\n // Confirm mode or no client secret available: fall back to full mode\n setModeError('Your card requires authentication. Please enter your payment details below.');\n return false;\n }\n\n // Auto mode: trigger 3DS authentication inline.\n // The backend already created the subscription with allow_incomplete.\n // Its invoice PI needs 3DS — after handleNextAction, Stripe auto-resolves\n // the invoice and activates the subscription. No resubmit needed.\n const { error: nextActionError, paymentIntent } = await stripe.handleNextAction({\n clientSecret: redirectResult.threeDSecureToken,\n });\n\n if (nextActionError) {\n setModeError(nextActionError.message ?? '3DS authentication failed.');\n emitDecline('card', nextActionError.message ?? '3DS authentication failed.', {\n code: nextActionError.code,\n });\n return false;\n }\n\n if (paymentIntent && (\n paymentIntent.status === 'requires_capture' ||\n paymentIntent.status === 'succeeded'\n )) {\n onCompleteRef.current?.({ status: 'succeeded', paymentIntentId: paymentIntent.id });\n return true;\n }\n return false;\n }\n\n if (redirectResult.type === 'paypal_redirect_required') {\n const confirmParams: Record<string, unknown> = {\n return_url: window.location.href,\n };\n if (redirectResult.paymentMethodId) {\n confirmParams['payment_method'] = redirectResult.paymentMethodId;\n }\n\n const { error } = await stripe.confirmPayment({\n clientSecret: redirectResult.threeDSecureToken,\n confirmParams: confirmParams as { return_url: string },\n redirect: 'if_required',\n });\n\n if (error) {\n setModeError(error.message ?? 'PayPal authorization failed.');\n emitDecline('paypal', error.message ?? 'PayPal authorization failed.', {\n code: error.code,\n });\n return false;\n }\n onCompleteRef.current?.({ status: 'succeeded' });\n return true;\n }\n\n return false;\n },\n [resolvedBillingUrl, resolvedSessionId, emitDecline],\n );\n\n // ── Session creation dedup ──\n // Prevents duplicate POSTs from React StrictMode double-invoking the effect.\n // Maps cache key → in-flight promise so the second invocation awaits the first.\n const inflightRef = useRef<Map<string, Promise<{ sid: string; result: NormalizedCheckoutSession }>>>(new Map());\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 const key = JSON.stringify({\n c: params?.clientId,\n successUrl: params?.successUrl,\n cancelUrl: params?.cancelUrl,\n i: params?.items?.map(x => `${x.providerItemId}:${x.totalAmount}:${x.overrideAmount ?? ''}:${x.quantity ?? 1}`).sort(),\n s: params?.subscriptions?.map(x => `${x.providerPlanId}:${x.totalAmount}:${x.overrideAmount ?? ''}:${x.quantity ?? 1}`).sort(),\n account: params?.account,\n couponCodes: params?.couponCodes,\n tagsData: params?.tagsData,\n utmMetadata: params?.utmMetadata,\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 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 if (realResult.data.session?.status === 'complete') {\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 realResult = await api.createAndFetchSession(params as InlineSessionParams);\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 const cacheKey = hashCreateParams(mergedParams);\n\n let promise = inflightRef.current.get(cacheKey);\n if (!promise) {\n promise = resolveInlineSession(mergedParams, cacheKey);\n inflightRef.current.set(cacheKey, promise);\n }\n\n let resolved: { sid: string; result: NormalizedCheckoutSession };\n try {\n resolved = await promise;\n } finally {\n inflightRef.current.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 let publishableKey: string | undefined;\n if (realResult.provider === 'stripe') {\n publishableKey = realResult.data.stripe?.publishableKey;\n }\n if (!publishableKey) publishableKey = fallbackPublishableKey;\n\n if (!publishableKey) {\n throw new FloPayError(\n 'No publishable key found. Provide fallbackPublishableKey or ensure the session includes gatewayData.publishableKey.',\n 'validation_error',\n );\n }\n\n const instance = await loadFloPay(publishableKey, {\n billingApiUrl: resolvedBillingUrl,\n locale,\n });\n flopayRef.current = instance;\n setFloPay(instance);\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 [fallbackPublishableKey, locale, resolvedBillingUrl],\n );\n\n const handleInlineSessionPatch = useCallback(async (patch: InlineSessionPatch) => {\n if (!hasInlineSessionPatchData(patch) || cardBootstrapPending) return;\n\n setCardBootstrapPending(true);\n try {\n await bootstrapInlineSession(patch);\n } finally {\n setCardBootstrapPending(false);\n }\n }, [\n bootstrapInlineSession,\n cardBootstrapPending,\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 // Already initialized with the same params — skip.\n if (initializedHashRef.current === createSessionHash) return;\n\n const params = createSessionParamsRef.current!;\n setSession(buildSyntheticSession(params, checkoutModeProp));\n setCurrentMode(params.checkoutMode ?? checkoutModeProp ?? 'full');\n setIsLoading(false);\n\n (async () => {\n try {\n await bootstrapInlineSession();\n } catch (err) {\n if (cancelled) return;\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(resolvedSessionId);\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 const effectiveMode = checkoutModeProp ?? sess.checkoutMode ?? 'full';\n setCurrentMode(effectiveMode);\n\n const hasPayPalRedirectParams =\n typeof window !== 'undefined' &&\n new URLSearchParams(window.location.search).has('payment_intent');\n\n if (\n effectiveMode === 'auto' &&\n !autoCheckoutAttempted.current &&\n !hasPayPalRedirectParams\n ) {\n autoCheckoutAttempted.current = true;\n const stripeInitPromise = initStripe(result);\n\n try {\n const redirectResult = await processPaymentForMode(sess);\n if (!redirectResult) {\n if (!cancelled) setIsLoading(false);\n return;\n }\n if (cancelled) return;\n await stripeInitPromise;\n const handled = await handleRedirectResult(redirectResult, sess, { attempt3DS: true });\n if (!cancelled) {\n if (!handled) setCurrentMode('full');\n setIsLoading(false);\n }\n return;\n } catch {\n if (cancelled) return;\n setCurrentMode('full');\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 let publishableKey: string | undefined;\n if (result.provider === 'stripe') {\n publishableKey = result.data.stripe?.publishableKey;\n }\n if (!publishableKey) publishableKey = fallbackPublishableKey;\n\n if (!publishableKey) {\n throw new FloPayError(\n 'No publishable key found in session response. Provide a fallbackPublishableKey prop or ensure the session includes gatewayData.publishableKey.',\n 'validation_error',\n );\n }\n\n const instance = await loadFloPay(publishableKey, {\n billingApiUrl: resolvedBillingUrl,\n locale,\n });\n\n flopayRef.current = instance;\n setFloPay(instance);\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 }, [resolvedSessionId, createSessionHash, checkoutModeProp, bootstrapInlineSession]);\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 const redirectResult = await processPaymentForMode(session);\n\n if (!redirectResult) {\n // Payment succeeded directly\n return;\n }\n\n // 3DS or PayPal auth required — handle it\n const handled = await handleRedirectResult(redirectResult, session);\n if (!handled) {\n setCurrentMode('full');\n }\n } catch (err) {\n const floPayErr =\n err instanceof FloPayError\n ? err\n : new FloPayError(\n err instanceof Error ? err.message : 'Payment failed',\n 'api_error',\n );\n setModeError(floPayErr.message);\n onError?.(floPayErr);\n emitDecline('card', floPayErr);\n setCurrentMode('full');\n } finally {\n setConfirmProcessing(false);\n }\n }, [confirmProcessing, session, processPaymentForMode, handleRedirectResult, onError, emitDecline]);\n\n // Provider options from session data\n const providerOptions = useMemo(() => {\n if (!unified || !session) return undefined;\n\n const opts: {\n appearance?: FloPayAppearance;\n paymentMethodCreation: 'manual';\n billingApiUrl: string;\n clientSecret?: string;\n amount?: number;\n currency?: string;\n } = {\n appearance,\n paymentMethodCreation: 'manual',\n billingApiUrl: resolvedBillingUrl,\n };\n\n if (\n unified.provider === 'stripe' &&\n unified.data.stripe?.clientSecret\n ) {\n opts.clientSecret = unified.data.stripe.clientSecret;\n } else {\n // Use display total (respects hideItems logic) instead of raw session.amount\n const displayTotal = buildCheckoutDisplayData(session).total;\n opts.amount = Math.round(displayTotal * 100) || session.amount;\n opts.currency = session.currency?.toLowerCase();\n }\n\n return opts;\n }, [unified, session, appearance, resolvedBillingUrl]);\n\n const shouldHandleInlineSessionPatch = Boolean(\n createSessionParams &&\n !children &&\n layout === 'buttons' &&\n onBeforeButtonClick &&\n (effectiveCreateSession?.checkoutMode ?? checkoutModeProp ?? 'full') === 'full',\n );\n\n // Checkout context\n const checkoutValue = useMemo(\n () => ({\n session,\n loading: isLoading,\n error: loadError,\n checkoutMode: currentMode,\n applyInlineSessionPatch: shouldHandleInlineSessionPatch\n ? handleInlineSessionPatch\n : undefined,\n inlineSessionPatchProcessing: cardBootstrapPending,\n }),\n [\n session,\n isLoading,\n loadError,\n currentMode,\n shouldHandleInlineSessionPatch,\n handleInlineSessionPatch,\n cardBootstrapPending,\n ],\n );\n const shouldShowInterimButtons =\n Boolean(createSessionParams) &&\n layout === 'buttons' &&\n (!flopay || !providerOptions);\n\n // ── Loading state ──\n if (isLoading) {\n if (loadingNode) return <>{loadingNode}</>;\n\n // Buttons layout: show button-shaped skeletons\n if (layout === 'buttons') {\n const skeletonBar = (h: number) => (\n <div style={{\n height: h, borderRadius: 8, background: '#e5e7eb',\n animation: 'flopay-loading-pulse 1.5s ease-in-out infinite',\n }} />\n );\n return (\n <div style={{ display: 'flex', flexDirection: 'column', gap: '0.5rem' }}>\n {showPayPal && skeletonBar(44)}\n {(showApplePay || showGooglePay) && skeletonBar(44)}\n {skeletonBar(48)}\n <style>{`@keyframes flopay-loading-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }`}</style>\n </div>\n );\n }\n\n // Default layout: centered spinner\n return (\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 );\n }\n\n // ── Error state ──\n if (loadError) {\n if (errorNode) return <>{errorNode(loadError)}</>;\n return (\n <div\n style={{\n padding: 24,\n textAlign: 'center',\n color: '#dc2626',\n fontSize: 14,\n }}\n >\n {loadError.message}\n </div>\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 <CheckoutContext.Provider value={checkoutValue}>\n <InterimButtonsView\n onButtonClick={onButtonClick}\n showPayPal={showPayPal}\n showApplePay={showApplePay}\n showGooglePay={showGooglePay}\n buttonsTheme={buttonsTheme}\n buttonsStyles={buttonsStyles}\n cardButtonContent={cardButtonContent}\n cardBackButtonContent={cardBackButtonContent}\n cardTitleContent={cardTitleContent}\n />\n </CheckoutContext.Provider>\n );\n }\n\n if (!flopay || !providerOptions) return <></>;\n\n // ── Confirm mode ──\n if (currentMode === 'confirm') {\n return (\n <CheckoutContext.Provider value={checkoutValue}>\n <FloPayProvider flopay={flopay} 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 );\n }\n\n // ── Full mode (default / fallback) ──\n return (\n <CheckoutContext.Provider value={checkoutValue}>\n <FloPayProvider flopay={flopay} options={providerOptions}>\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 {children ? (\n <SessionInjector\n sessionId={resolvedSessionId}\n billingApiUrl={resolvedBillingUrl}\n session={session}\n >\n {children}\n </SessionInjector>\n ) : (\n <SplitCardForm\n sessionId={resolvedSessionId}\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 showPayPal={showPayPal}\n showApplePay={showApplePay}\n showGooglePay={showGooglePay}\n layout={layout}\n buttonsTheme={buttonsTheme}\n buttonsStyles={buttonsStyles}\n cardButtonContent={cardButtonContent}\n cardBackButtonContent={cardBackButtonContent}\n cardTitleContent={cardTitleContent}\n onButtonClick={onButtonClick}\n onBeforeButtonClick={onBeforeButtonClick}\n enableAVS={enableAVS}\n avsLayout={avsLayout}\n country={session?.customer?.country}\n submitLabel={submitLabel}\n className={className}\n />\n )}\n </FloPayProvider>\n </CheckoutContext.Provider>\n );\n}\n\n/**\n * Auto-injects session props into child form components.\n * Explicit props on children take precedence over injected values.\n */\nfunction SessionInjector({\n sessionId,\n billingApiUrl,\n session,\n children,\n}: {\n sessionId: string;\n billingApiUrl: string;\n session: CheckoutSession | null;\n children: React.ReactNode;\n}) {\n return (\n <>\n {React.Children.map(children, (child) => {\n if (!React.isValidElement(child)) return child;\n\n const existing = child.props as Record<string, unknown>;\n const injected: Record<string, unknown> = {};\n\n if (!existing.sessionId) injected.sessionId = sessionId;\n if (!existing.billingApiUrl) injected.billingApiUrl = billingApiUrl;\n\n if (session?.customer) {\n if (!existing.email) injected.email = session.customer.email;\n if (!existing.userId) injected.userId = session.customer.id;\n if (!existing.firstName)\n injected.firstName = session.customer.firstName;\n if (!existing.lastName)\n injected.lastName = session.customer.lastName;\n }\n\n if (Object.keys(injected).length === 0) return child;\n return React.cloneElement(child, injected);\n })}\n </>\n );\n}\n\n/**\n * Interim buttons view rendered while Stripe initializes in the background.\n * Shows skeleton bars for PayPal/wallets and a fully interactive Credit/Debit Card button.\n */\nfunction InterimButtonsView({\n onButtonClick,\n onCardButtonClick,\n cardLoading = false,\n cardOpen,\n errorMessage,\n showPayPal,\n showApplePay,\n showGooglePay,\n buttonsTheme,\n buttonsStyles: stylesOverride,\n cardButtonContent,\n cardBackButtonContent,\n cardTitleContent,\n}: {\n onButtonClick?: (method: CheckoutButtonMethod) => void;\n onCardButtonClick?: () => void | Promise<void>;\n cardLoading?: boolean;\n cardOpen?: boolean;\n errorMessage?: string | null;\n showPayPal: boolean;\n showApplePay: boolean;\n showGooglePay: boolean;\n buttonsTheme?: ButtonsLayoutTheme;\n buttonsStyles?: ButtonsLayoutStyles;\n cardButtonContent?: React.ReactNode;\n cardBackButtonContent?: React.ReactNode;\n cardTitleContent?: React.ReactNode;\n}) {\n const [showCardForm, setShowCardForm] = useState(false);\n const isCardOpenControlled = typeof cardOpen === 'boolean';\n\n useEffect(() => {\n if (isCardOpenControlled) {\n setShowCardForm(cardOpen);\n }\n }, [cardOpen, isCardOpenControlled]);\n\n const bStyles = useMemo<ButtonsLayoutStyles>(() => {\n const base = resolveButtonsLayoutTheme(buttonsTheme);\n if (!stylesOverride) return base;\n return {\n ...base,\n ...stylesOverride,\n cardButton: { ...base.cardButton, ...stylesOverride.cardButton },\n cardFormContainer: { ...base.cardFormContainer, ...stylesOverride.cardFormContainer },\n backButton: { ...base.backButton, ...stylesOverride.backButton },\n backButtonIcon: { ...base.backButtonIcon, ...stylesOverride.backButtonIcon },\n submitButton: { ...base.submitButton, ...stylesOverride.submitButton },\n title: { ...base.title, ...stylesOverride.title },\n };\n }, [buttonsTheme, stylesOverride]);\n\n const skeleton = (h: number) => (\n <div style={{\n height: h, borderRadius: 8, background: '#e5e7eb',\n animation: 'flopay-interim-pulse 1.5s ease-in-out infinite',\n }} />\n );\n\n if (showCardForm) {\n // Show a card form placeholder with back button — real form takes over when Stripe loads\n const inputBorder = bStyles.cardInputBorder ?? '#e5e7eb';\n const inputBg = bStyles.cardInputBackground ?? 'white';\n const hideBackButtonLabel = isEmptySlotContent(cardBackButtonContent);\n const hideTitle = isEmptySlotContent(cardTitleContent);\n return (\n <div style={{\n backgroundColor: (bStyles.cardFormContainer?.backgroundColor as string) ?? 'white',\n borderRadius: '8px',\n animation: 'flopay-interim-expand 0.35s cubic-bezier(0.4, 0, 0.2, 1) both',\n overflow: 'hidden',\n ...bStyles.cardFormContainer as React.CSSProperties,\n }}>\n <div style={{ display: 'flex', alignItems: 'center', padding: '0.75rem 0 0.625rem' }}>\n <button\n type=\"button\"\n onClick={() => {\n if (!isCardOpenControlled) {\n setShowCardForm(false);\n }\n }}\n aria-label=\"Back to payment methods\"\n disabled={isCardOpenControlled || cardLoading}\n style={{\n display: 'inline-flex', alignItems: 'center', gap: hideBackButtonLabel ? 0 : '0.5rem',\n background: 'none', border: 'none',\n color: '#4b5563', fontSize: '0.85rem', fontWeight: 500,\n padding: 0, flexShrink: 0, opacity: isCardOpenControlled || cardLoading ? 0.6 : 1,\n cursor: isCardOpenControlled || cardLoading ? 'not-allowed' : 'pointer',\n ...bStyles.backButton as React.CSSProperties,\n }}\n >\n <span style={{\n display: 'inline-flex', alignItems: 'center', justifyContent: 'center',\n width: 28, height: 28, borderRadius: '50%',\n backgroundColor: '#f3f4f6',\n ...bStyles.backButtonIcon as React.CSSProperties,\n }}>\n <svg width=\"14\" height=\"14\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2.5\" strokeLinecap=\"round\" strokeLinejoin=\"round\">\n <path d=\"M15 18l-6-6 6-6\" />\n </svg>\n </span>\n <BackButtonContentSlot content={cardBackButtonContent} />\n </button>\n {hideTitle ? (\n <div style={{ flex: 1 }} />\n ) : (\n <div style={{\n flex: 1, textAlign: 'center', fontWeight: 600, fontSize: '1.05rem',\n color: '#262833', paddingRight: 80,\n ...bStyles.title as React.CSSProperties,\n }}>\n <TitleContentSlot content={cardTitleContent} />\n </div>\n )}\n </div>\n {/* Skeleton card fields */}\n <div style={{ backgroundColor: inputBg, border: `1px solid ${inputBorder}`, borderTopLeftRadius: 8, borderTopRightRadius: 8, padding: 12, height: 45 }}>\n <div style={{ width: '60%', height: 14, borderRadius: 4, background: '#e5e7eb', animation: 'flopay-interim-pulse 1.5s ease-in-out infinite' }} />\n </div>\n <div style={{ display: 'flex' }}>\n <div style={{ flex: 1, backgroundColor: inputBg, border: `1px solid ${inputBorder}`, borderTop: 'none', borderRight: 'none', borderBottomLeftRadius: 8, padding: 12, height: 45 }}>\n <div style={{ width: '50%', height: 14, borderRadius: 4, background: '#e5e7eb', animation: 'flopay-interim-pulse 1.5s ease-in-out infinite' }} />\n </div>\n <div style={{ flex: 1, backgroundColor: inputBg, border: `1px solid ${inputBorder}`, borderTop: 'none', borderBottomRightRadius: 8, padding: 12, height: 45 }}>\n <div style={{ width: '40%', height: 14, borderRadius: 4, background: '#e5e7eb', animation: 'flopay-interim-pulse 1.5s ease-in-out infinite' }} />\n </div>\n </div>\n <div style={{ backgroundColor: inputBg, border: `1px solid ${inputBorder}`, borderRadius: 8, marginTop: 8, padding: 12, height: 45 }}>\n <div style={{ width: '45%', height: 14, borderRadius: 4, background: '#e5e7eb', animation: 'flopay-interim-pulse 1.5s ease-in-out infinite' }} />\n </div>\n <div style={{\n height: 50, borderRadius: 8, marginTop: 16, background: '#c8c8ff',\n animation: 'flopay-interim-pulse 1.5s ease-in-out infinite',\n ...bStyles.submitButton as React.CSSProperties,\n opacity: 0.5,\n }} />\n <style>{`\n @keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }\n @keyframes flopay-interim-expand {\n 0% { opacity: 0; max-height: 0; transform: translateY(-12px); }\n 40% { opacity: 1; }\n 100% { opacity: 1; max-height: 600px; transform: translateY(0); }\n }\n `}</style>\n </div>\n );\n }\n\n return (\n <div style={{ display: 'flex', flexDirection: 'column', gap: '0.5rem' }}>\n {showPayPal && skeleton(44)}\n {(showApplePay || showGooglePay) && skeleton(44)}\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%', padding: '0.9rem 1rem',\n backgroundColor: 'white', color: '#262833',\n border: '1px solid #d1d5db', borderRadius: '8px',\n fontSize: bStyles.cardButtonFontSize ?? '0.95rem', fontWeight: 600,\n cursor: cardLoading ? 'not-allowed' : 'pointer', display: 'flex',\n alignItems: 'center', justifyContent: 'center', gap: '0.625rem',\n boxShadow: '0 1px 2px rgba(0,0,0,0.04)',\n transition: 'transform 0.1s',\n position: 'relative',\n opacity: cardLoading ? 0.6 : 1,\n ...bStyles.cardButton as React.CSSProperties,\n }}\n onMouseDown={(e) => { e.currentTarget.style.transform = 'scale(0.985)'; }}\n onMouseUp={(e) => { e.currentTarget.style.transform = 'scale(1)'; }}\n >\n <CardButtonContentSlot content={cardButtonContent} />\n </button>\n {errorMessage && (\n <div style={{\n margin: '0.25rem 0', padding: '0.625rem 0.875rem',\n background: '#FEF2F2', border: '1px solid #FECACA', borderRadius: '8px',\n color: '#991B1B', fontSize: '0.85rem', fontWeight: 600,\n display: 'flex', alignItems: 'center', gap: '0.5rem',\n ...(bStyles.errorBanner as React.CSSProperties | undefined),\n }}>\n <svg width=\"16\" height=\"16\" viewBox=\"0 0 24 24\" fill=\"none\" style={{ flexShrink: 0 }}>\n <path d=\"M12 9v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z\" stroke=\"#DC2626\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\" />\n </svg>\n {errorMessage}\n </div>\n )}\n <style>{`@keyframes flopay-interim-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }`}</style>\n </div>\n );\n}\n","import React from 'react';\n\nexport function DefaultCardButtonContent(): React.ReactElement {\n return (\n <>\n <svg\n width=\"20\"\n height=\"20\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"1.5\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n aria-hidden=\"true\"\n >\n <rect width=\"20\" height=\"14\" x=\"2\" y=\"5\" rx=\"2\" />\n <line x1=\"2\" x2=\"22\" y1=\"10\" y2=\"10\" />\n </svg>\n Credit / Debit Card\n <svg\n width=\"16\"\n height=\"16\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"#9ca3af\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n style={{ position: 'absolute', right: '1rem' }}\n aria-hidden=\"true\"\n >\n <path d=\"M9 18l6-6-6-6\" />\n </svg>\n </>\n );\n}\n\nexport function DefaultBackButtonContent(): React.ReactElement {\n return <>Go back</>;\n}\n\nexport function DefaultTitleContent(): React.ReactElement {\n return <>Secure card checkout</>;\n}\n\nexport function isEmptySlotContent(content: React.ReactNode | undefined): boolean {\n return content !== undefined && (content === '' || content === null || content === false);\n}\n\nexport function CardButtonContentSlot({\n content,\n}: {\n content?: React.ReactNode;\n}): React.ReactElement {\n return <>{content === undefined ? <DefaultCardButtonContent /> : content}</>;\n}\n\nexport function BackButtonContentSlot({\n content,\n}: {\n content?: React.ReactNode;\n}): React.ReactElement {\n return <>{content === undefined ? <DefaultBackButtonContent /> : content}</>;\n}\n\nexport function TitleContentSlot({\n content,\n}: {\n content?: React.ReactNode;\n}): React.ReactElement {\n return <>{content === undefined ? <DefaultTitleContent /> : content}</>;\n}\n","import React, { useEffect, useRef, useContext } from 'react';\nimport type { ElementType, ElementChangeEvent, ElementOptions, MountedElement } from '@flopay/shared';\nimport { FloPayContext } from './context.js';\n\n/** Common props shared by all element components. */\nexport interface ElementComponentProps {\n /** Additional CSS class for the wrapper div. */\n className?: string;\n /** Element id attribute for the wrapper div. */\n id?: string;\n /** Inline styles for the wrapper div. */\n style?: React.CSSProperties;\n /** Options forwarded to the underlying element. */\n options?: Partial<ElementOptions>;\n /** Fired when the element's value changes. */\n onChange?: (event: ElementChangeEvent) => void;\n /** Fired when the element is fully rendered and ready. */\n onReady?: () => void;\n /** Fired when the element gains focus. */\n onFocus?: () => void;\n /** Fired when the element loses focus. */\n onBlur?: () => void;\n /** Fired when the Escape key is pressed inside the element. */\n onEscape?: () => void;\n}\n\n/**\n * Generic element component factory.\n *\n * Each element component:\n * 1. Gets the Elements instance from context\n * 2. Creates the appropriate element type\n * 3. Mounts it to a ref'd container div\n * 4. Forwards events as props\n * 5. Cleans up on unmount\n *\n * TODO: In a future phase, each element will render inside an iframe\n * for PCI DSS SAQ-A compliance. For now, they wrap the provider's\n * elements directly.\n */\nfunction createElementComponent(\n elementType: ElementType,\n displayName: string,\n): React.FC<ElementComponentProps> {\n function ElementComponent({\n className,\n id,\n style,\n options,\n onChange,\n onReady,\n onFocus,\n onBlur,\n onEscape,\n }: ElementComponentProps) {\n const containerRef = useRef<HTMLDivElement>(null);\n const elementRef = useRef<MountedElement | null>(null);\n const { elements } = useContext(FloPayContext);\n\n useEffect(() => {\n if (!elements || !containerRef.current) return;\n\n let mounted = true;\n\n (async () => {\n // Reuse existing element if Stripe already created one of this type\n // (handles React Strict Mode double-mount).\n let element = elements.getElement(elementType);\n if (!element) {\n element = await elements.create(elementType, options);\n }\n\n if (!mounted || !containerRef.current) {\n return;\n }\n\n element.mount(containerRef.current);\n elementRef.current = element;\n\n if (onChange) element.on('change', onChange as (...args: unknown[]) => void);\n if (onReady) element.on('ready', onReady as (...args: unknown[]) => void);\n if (onFocus) element.on('focus', onFocus as (...args: unknown[]) => void);\n if (onBlur) element.on('blur', onBlur as (...args: unknown[]) => void);\n if (onEscape) element.on('escape', onEscape as (...args: unknown[]) => void);\n })();\n\n return () => {\n mounted = false;\n // Unmount only — don't destroy. Stripe Elements tracks elements\n // internally; destroying prevents reuse on Strict Mode remount.\n // Guard with try/catch: the element may already be destroyed if\n // the parent provider recreated the Elements group (e.g. on\n // appearance change).\n if (elementRef.current) {\n try {\n elementRef.current.unmount();\n } catch {\n // Element already destroyed — safe to ignore\n }\n elementRef.current = null;\n }\n };\n }, [elements]);\n\n return <div ref={containerRef} className={className} id={id} style={style} />;\n }\n\n ElementComponent.displayName = displayName;\n return ElementComponent;\n}\n\n/**\n * Renders the unified Payment Element — a single component that accepts\n * cards, wallets, and other payment methods.\n *\n * TODO: Will render inside an iframe for PCI compliance in a future phase.\n */\nexport const PaymentElement = createElementComponent('payment', 'PaymentElement');\n\n/**\n * Renders a combined card input (number + expiry + CVC).\n *\n * TODO: Will render inside an iframe for PCI compliance in a future phase.\n */\nexport const CardElement = createElementComponent('card', 'CardElement');\n\n/**\n * Renders a card number input field.\n *\n * TODO: Will render inside an iframe for PCI compliance in a future phase.\n */\nexport const CardNumberElement = createElementComponent('cardNumber', 'CardNumberElement');\n\n/**\n * Renders a card expiry input field.\n *\n * TODO: Will render inside an iframe for PCI compliance in a future phase.\n */\nexport const CardExpiryElement = createElementComponent('cardExpiry', 'CardExpiryElement');\n\n/**\n * Renders a card CVC input field.\n *\n * TODO: Will render inside an iframe for PCI compliance in a future phase.\n */\nexport const CardCvcElement = createElementComponent('cardCvc', 'CardCvcElement');\n\n/**\n * Renders an address input element.\n */\nexport const AddressElement = createElementComponent('address', 'AddressElement');\n","import {\n CardCvcElement,\n CardExpiryElement,\n CardNumberElement,\n} from './elements.js';\nimport {\n ExpressCheckoutElement,\n Elements as StripeElements,\n useElements as useStripeElements,\n useStripe as useStripeRaw,\n} from '@stripe/react-stripe-js';\nimport type {\n BeforeButtonClickEvent,\n CheckoutButtonMethod,\n DeclineEvent,\n InlineSessionPatch,\n PaymentResult,\n TokenizedBody,\n ButtonsLayoutStyles,\n} from '@flopay/shared';\nimport { resolveButtonsLayoutTheme, getPostalCodeLabel, COUNTRY_OPTIONS } from '@flopay/shared';\nimport React, { forwardRef, useCallback, useContext, useEffect, useImperativeHandle, useMemo, useRef, useState } from 'react';\nimport type { Stripe, StripeExpressCheckoutElementConfirmEvent } from '@stripe/stripe-js';\nimport { useBillingApiUrl, useElements, useFloPay } from './hooks.js';\nimport { CheckoutContext } from './context.js';\nimport {\n BackButtonContentSlot,\n CardButtonContentSlot,\n TitleContentSlot,\n isEmptySlotContent,\n} from './card-button-content.js';\nimport { buildDeclineEvent, mergeAccountPatch } from './checkout-utils.js';\n\nimport { FloPayError } from '@flopay/shared';\n\n/** localStorage key for persisting wallet payment state across redirects. */\nconst WALLET_RESUME_KEY = 'flopay_wallet_resume';\n\ntype MaybePromise<T> = T | Promise<T>;\n\n// ─── Global keyframes (always present — not gated behind overlay render) ────\n\nconst FLOPAY_KEYFRAMES = `\n@keyframes flopay-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }\n@keyframes flopay-fade-in { 0% { opacity: 0; } 100% { opacity: 1; } }\n@keyframes flopay-buttons-enter {\n 0% { opacity: 0; transform: translateX(-16px) scale(0.97); }\n 100% { opacity: 1; transform: translateX(0) scale(1); }\n}\n@keyframes flopay-buttons-exit {\n 0% { opacity: 1; transform: translateX(0) scale(1); }\n 100% { opacity: 0; transform: translateX(-16px) scale(0.97); }\n}\n@keyframes flopay-card-enter {\n 0% { opacity: 0; transform: translateX(16px) scale(0.97); }\n 100% { opacity: 1; transform: translateX(0) scale(1); }\n}\n@keyframes flopay-card-exit {\n 0% { opacity: 1; transform: translateX(0) scale(1); }\n 100% { opacity: 0; transform: translateX(16px) scale(0.97); }\n}\n`;\n\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// ─── Processing Overlay with animated states ─────────────────────────────────\n\ntype OverlayStatus = 'processing' | 'success' | 'error';\n\nfunction ProcessingOverlay({ status, errorMessage }: { status: OverlayStatus; errorMessage?: string | null }) {\n return (\n <div style={{\n position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.35)',\n display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 1000,\n backdropFilter: 'blur(2px)',\n }}>\n <div style={{\n background: 'white', borderRadius: 12, padding: '2rem 2.5rem',\n textAlign: 'center', boxShadow: '0 8px 32px rgba(0,0,0,0.18)', minWidth: 240,\n display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 16,\n }}>\n <div style={{ width: 48, height: 48, position: 'relative' }}>\n {status === 'processing' && (\n <svg width=\"48\" height=\"48\" viewBox=\"0 0 24 24\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\"\n style={{ animation: 'flopay-spin 0.8s linear infinite' }}>\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 d=\"M7 12.5l3 3 7-7\" stroke=\"white\" strokeWidth=\"2.5\" strokeLinecap=\"round\" strokeLinejoin=\"round\"\n style={{ strokeDasharray: 20, strokeDashoffset: 20, animation: 'flopay-draw 0.4s 0.15s ease forwards' }} />\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 d=\"M8 8l8 8M16 8l-8 8\" stroke=\"white\" strokeWidth=\"2.5\" strokeLinecap=\"round\"\n style={{ strokeDasharray: 12, strokeDashoffset: 12, animation: 'flopay-draw 0.3s 0.1s ease forwards' }} />\n </svg>\n </div>\n )}\n </div>\n <span style={{\n fontSize: 14, fontWeight: 600, letterSpacing: '0.05em',\n color: status === 'success' ? '#16a34a' : status === 'error' ? '#dc2626' : '#374151',\n }}>\n {status === 'processing' && 'PROCESSING...'}\n {status === 'success' && 'PAYMENT SUCCESSFUL'}\n {status === 'error' && 'PAYMENT FAILED'}\n </span>\n {status === 'success' && (\n <p style={{\n fontSize: 13,\n color: '#6b7280',\n fontWeight: 400,\n maxWidth: 260,\n lineHeight: 1.4,\n margin: 0,\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 style={{\n fontSize: 13, color: '#6b7280', fontWeight: 400,\n maxWidth: 260, lineHeight: 1.4, margin: 0,\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\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 first name changes (from the name input). */\n onFirstNameChange?: (value: string) => void;\n /** Callback when last name changes (from the name input). */\n onLastNameChange?: (value: string) => void;\n /**\n * Show PayPal button above card fields. Defaults to `true`.\n * Uses Stripe's ExpressCheckoutElement in a separate Elements instance,\n * matching checkout/StripeCardForm architecture.\n */\n showPayPal?: boolean;\n /** Show Apple Pay button. Defaults to `true`. Only renders on supported devices. */\n showApplePay?: boolean;\n /** Show Google Pay button. Defaults to `true`. Only renders on supported devices. */\n showGooglePay?: boolean;\n /**\n * Layout mode for the payment form.\n * - `'default'` — all payment methods + card form shown together (current behavior)\n * - `'buttons'` — PayPal, wallets, and a \"Credit / Debit Card\" button; clicking the card\n * button expands the card form with a back button to return to the button view\n */\n layout?: 'default' | 'buttons';\n /**\n * Theme preset for the `buttons` layout. Ignored when `layout` is `'default'`.\n * - `'default'` — white card button, neutral borders\n * - `'minimal'` — borderless, subtle backgrounds\n * - `'rounded'` — large border radius, soft shadows\n * - `'dark'` — dark backgrounds, light text\n */\n buttonsTheme?: import('@flopay/shared').ButtonsLayoutTheme;\n /** Custom style overrides for the `buttons` layout. Merged on top of the theme preset. */\n buttonsStyles?: import('@flopay/shared').ButtonsLayoutStyles;\n /** Custom React content rendered inside the card button when `layout=\"buttons\"`. */\n cardButtonContent?: React.ReactNode;\n /** Custom React content rendered for the buttons-layout card back button label. */\n cardBackButtonContent?: React.ReactNode;\n /** Custom React content rendered for the card-form title. */\n cardTitleContent?: React.ReactNode;\n /**\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 the credit/debit card button continues.\n * Card only: this does not run for PayPal or wallet buttons.\n */\n onBeforeButtonClick?: (\n event: BeforeButtonClickEvent,\n ) => MaybePromise<void | false | InlineSessionPatch>;\n /**\n * Enable AVS (Address Verification). Shows country dropdown + ZIP/postcode input.\n * When enabled, billing_details are passed to Stripe's createPaymentMethod for AVS checks.\n */\n enableAVS?: boolean;\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 /** Callback when AVS country changes. */\n onCountryChange?: (country: string) => void;\n /** Callback when AVS ZIP/postal code changes. */\n onZipChange?: (zip: string) => void;\n /** Total amount in cents (smallest currency unit). Used for wallet/PayPal Elements config. */\n totalAmount?: number;\n /** Currency code (used for PayPal Elements config). */\n currency?: string;\n /** Render the card form expanded on first paint when `layout=\"buttons\"`. */\n initialCardOpen?: boolean;\n}\n\n/**\n * Split card checkout form matching `checkout/StripeCardForm`:\n * PayPal button → divider → CardNumber → CardExpiry + CardCVC → Full Name → Submit.\n *\n * PayPal uses its own Stripe Elements instance (no `paymentMethodCreation`)\n * exactly like checkout does with two separate `<Elements>` wrappers.\n */\nexport const SplitCardForm = forwardRef<SplitCardFormRef, SplitCardFormProps>(\n function SplitCardForm(props, ref) {\n return <SplitCardFormInner {...props} innerRef={ref} />;\n },\n);\n\n// ─── PayPal button (own Elements instance) ──────────────────────────────────\n// Mirrors checkout/StripeCardForm's StripePayPalButtonInner exactly.\n\nfunction PayPalButtonInner({\n sessionId,\n email,\n billingApiUrl,\n onTokenizedBody,\n onErrorChange,\n isProcessing = false,\n onButtonClick,\n onDecline,\n}: {\n sessionId: string;\n email?: string;\n billingApiUrl: string;\n onTokenizedBody: (body: TokenizedBody) => void;\n onErrorChange?: (error: string | null) => void;\n isProcessing?: boolean;\n onButtonClick?: (method: CheckoutButtonMethod) => void;\n onDecline?: (decline: DeclineEvent) => void;\n}) {\n const stripe = useStripeRaw();\n const elements = useStripeElements();\n const [ready, setReady] = useState(false);\n const [submitting, setSubmitting] = useState(false);\n const paypalResumeAttempted = useRef(false);\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 (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\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 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 // PayPal confirm handler — called by ExpressCheckoutElement onConfirm\n const handlePayPalConfirm = useCallback(async (_event: StripeExpressCheckoutElementConfirmEvent) => {\n if (!stripe || !elements) return;\n\n onButtonClick?.('paypal');\n\n try {\n setSubmitting(true);\n onErrorChange?.(null);\n\n if (!sessionId || !email) {\n throw new Error('Missing sessionId or email for PayPal payment');\n }\n\n // 1. Create PayPal PaymentMethod so backend can attach it to the intent\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 console.warn('[FloPay] Could not create PayPal PM upfront:', pmError.message);\n }\n\n // 2. Create PaymentIntent via backend with pm_xxx (or 'paypal' as fallback)\n // isPaypal must be string 'true' — backend checks === 'true'\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: paymentMethod?.id ?? 'paypal',\n isPaypal: 'true',\n }),\n });\n\n if (!intentResponse.ok) throw new Error('Failed to create payment intent');\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 // 3. Confirm payment — pass payment_method if available\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 // 4. Extract pm_xxx from confirmed intent.\n // Send the PM + PI id so the backend can capture the pre-authorized PI\n // and extract the reusable PM with the PayPal billing agreement.\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 } 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]);\n\n return (\n <>\n <div>\n <ExpressCheckoutElement\n onReady={() => setReady(true)}\n onLoadError={() => { /* PayPal not available — hide gracefully */ }}\n onConfirm={handlePayPalConfirm}\n onCancel={() => {\n onDecline?.(buildDeclineEvent('paypal', 'PayPal checkout was cancelled.'));\n }}\n options={{\n buttonType: { paypal: 'paypal' } as Record<string, string>,\n paymentMethods: {\n applePay: 'never',\n googlePay: 'never',\n paypal: 'auto',\n link: 'never',\n },\n } as Parameters<typeof ExpressCheckoutElement>[0]['options']}\n />\n </div>\n {submitting && <ProcessingOverlay status=\"processing\" />}\n </>\n );\n}\n\n// ─── Wallet buttons (Apple Pay / Google Pay — own Elements instance) ────────\n// Uses raw stripe + elements from its own StripeElements context,\n// matching checkout/StripeCardForm's handleExpressCheckoutConfirm exactly.\n\nfunction WalletButtonInner({\n sessionId,\n email,\n billingApiUrl,\n showApplePay = true,\n showGooglePay = true,\n onTokenizedBody,\n onErrorChange,\n onButtonClick,\n onDecline,\n}: {\n sessionId: string;\n email?: string;\n billingApiUrl: string;\n showApplePay?: boolean;\n showGooglePay?: boolean;\n onTokenizedBody: (body: TokenizedBody) => void;\n onErrorChange?: (error: string | null) => void;\n onButtonClick?: (method: CheckoutButtonMethod) => void;\n onDecline?: (decline: DeclineEvent) => void;\n}) {\n const stripe = useStripeRaw();\n const elements = useStripeElements();\n const [ready, setReady] = useState(false);\n const [submitting, setSubmitting] = useState(false);\n const baseUrl = billingApiUrl.replace(/\\/+$/, '');\n const lastWalletMethodRef = useRef<CheckoutButtonMethod>('card');\n\n const handleWalletConfirm = useCallback(\n async (_event: StripeExpressCheckoutElementConfirmEvent) => {\n if (!stripe || !elements) return;\n\n // Detect wallet type from the express checkout event\n const walletType = (_event as unknown as { expressPaymentType?: string }).expressPaymentType;\n onButtonClick?.(walletType === 'apple_pay' ? 'apple_pay' : 'google_pay');\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 (!sessionId || !email) {\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,\n email,\n paymentMethodType: paymentMethod.id,\n isPaypal: false,\n }),\n });\n\n if (!intentResponse.ok) throw new Error('Failed to create payment intent');\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 method = walletType === 'apple_pay' ? 'apple_pay' : 'google_pay';\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 } 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],\n );\n\n return (\n <>\n <div>\n <ExpressCheckoutElement\n onReady={() => setReady(true)}\n onLoadError={() => { /* wallets not available on this device — hide */ }}\n onClick={(event) => {\n lastWalletMethodRef.current = event.expressPaymentType === 'apple_pay' ? 'apple_pay' : 'google_pay';\n event.resolve();\n }}\n onConfirm={handleWalletConfirm}\n onCancel={() => {\n onDecline?.(buildDeclineEvent(lastWalletMethodRef.current, 'Wallet checkout was cancelled.'));\n }}\n options={{\n buttonType: { applePay: 'plain', googlePay: 'plain' } as Record<string, string>,\n paymentMethods: {\n applePay: showApplePay ? 'always' : 'never',\n googlePay: showGooglePay ? 'always' : 'never',\n paypal: 'never',\n link: 'never',\n amazonPay: 'never',\n klarna: 'never',\n },\n layout: { maxColumns: 1, overflow: 'never' },\n } as Parameters<typeof ExpressCheckoutElement>[0]['options']}\n />\n </div>\n {submitting && <ProcessingOverlay status=\"processing\" />}\n </>\n );\n}\n\n// ─── Main form ──────────────────────────────────────────────────────────────\n\nfunction SplitCardFormInner({\n sessionId,\n billingApiUrl,\n email,\n userId,\n onComplete,\n onError,\n onDecline,\n onTokenizedBody,\n firstName,\n lastName,\n chv,\n submitLabel = 'CONFIRM PAYMENT',\n className,\n children,\n isProcessing: externalProcessing,\n error: externalError,\n onErrorChange,\n onFirstNameChange,\n onLastNameChange,\n showPayPal = true,\n showApplePay = true,\n showGooglePay = true,\n layout = 'default',\n buttonsTheme,\n buttonsStyles: buttonsStylesOverride,\n cardButtonContent,\n cardBackButtonContent,\n cardTitleContent,\n onButtonClick,\n onBeforeButtonClick,\n enableAVS = false,\n avsLayout: avsLayoutProp = 'row',\n country: countryProp,\n zip: zipProp,\n onCountryChange,\n onZipChange,\n totalAmount = 0,\n currency = 'usd',\n initialCardOpen = false,\n innerRef,\n}: SplitCardFormProps & { innerRef: React.Ref<SplitCardFormRef> }) {\n const flopay = useFloPay();\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 [accountPatch, setAccountPatch] = useState<InlineSessionPatch['account']>({});\n const zipCodeRef = useRef(zipProp ?? '');\n const selectedCountryRef = useRef(countryProp ?? 'US');\n\n // Buttons ↔ Card transition state machine\n type ViewState = 'buttons' | 'expanding' | 'card' | 'collapsing';\n const [viewState, setViewState] = useState<ViewState>(initialCardOpen ? 'card' : 'buttons');\n const showCardForm = viewState === 'expanding' || viewState === 'card';\n const TRANSITION_MS = 280;\n\n const expandToCard = useCallback(() => {\n setViewState('expanding');\n setTimeout(() => setViewState('card'), TRANSITION_MS);\n }, []);\n\n const collapseToButtons = useCallback(() => {\n setViewState('collapsing');\n setTimeout(() => setViewState('buttons'), TRANSITION_MS);\n }, []);\n\n useEffect(() => {\n if (layout === 'buttons' && initialCardOpen) {\n setViewState('card');\n }\n }, [layout, initialCardOpen]);\n const [fullName, setFullName] = useState('');\n const [formReady, setFormReady] = useState(false);\n const [overlayStatus, setOverlayStatus] = useState<OverlayStatus | null>(null);\n const processingRef = useRef(false);\n\n const resolvedBillingApiUrl = billingApiUrl || contextBillingUrl;\n const displayError = externalError ?? error;\n\n // Resolve buttons layout styles: theme preset merged with custom overrides\n const bStyles = useMemo<ButtonsLayoutStyles>(() => {\n const base = resolveButtonsLayoutTheme(buttonsTheme);\n if (!buttonsStylesOverride) return base;\n return {\n ...base,\n ...buttonsStylesOverride,\n cardButton: { ...base.cardButton, ...buttonsStylesOverride.cardButton },\n cardFormContainer: { ...base.cardFormContainer, ...buttonsStylesOverride.cardFormContainer },\n backButton: { ...base.backButton, ...buttonsStylesOverride.backButton },\n backButtonIcon: { ...base.backButtonIcon, ...buttonsStylesOverride.backButtonIcon },\n submitButton: { ...base.submitButton, ...buttonsStylesOverride.submitButton },\n title: { ...base.title, ...buttonsStylesOverride.title },\n };\n }, [buttonsTheme, buttonsStylesOverride]);\n const isInlineSessionPatchProcessing = checkout.inlineSessionPatchProcessing ?? false;\n const isSubmitting = (externalProcessing ?? processing) || isInlineSessionPatchProcessing;\n const isSelfContained = !onTokenizedBody;\n const baseUrl = resolvedBillingApiUrl.replace(/\\/+$/, '');\n const resolvedAccount = useMemo(() => mergeAccountPatch({\n userId,\n email,\n firstName,\n lastName,\n country: countryProp,\n zip: zipProp,\n }, accountPatch), [userId, email, firstName, lastName, countryProp, zipProp, accountPatch]);\n\n // Get raw Stripe instance for PayPal Elements provider\n const stripeInstance = useMemo(() => {\n if (!flopay) return null;\n return flopay.getRawProvider() as Stripe | null;\n }, [flopay]);\n\n // totalAmount is in cents (smallest currency unit) when passed from FloPayCheckout.\n // Stripe Elements `amount` expects cents.\n const amountInCents = totalAmount || 100; // minimum 1 cent\n\n // Wallet (Apple/Google Pay) Elements options — uses paymentMethodCreation: 'manual'\n // to match the main card Elements, allowing explicit createPaymentMethod() calls.\n const walletOptions = useMemo(() => ({\n mode: 'payment' as const,\n amount: amountInCents,\n currency: currency.toLowerCase(),\n paymentMethodCreation: 'manual' as const,\n captureMethod: 'manual' as const,\n }), [amountInCents, currency]);\n\n // PayPal Elements options — no paymentMethodCreation (matches checkout)\n const paypalOptions = useMemo(() => ({\n mode: 'payment' as const,\n amount: amountInCents,\n currency: currency.toLowerCase(),\n captureMethod: 'manual' as const,\n }), [amountInCents, currency]);\n\n const updateError = useCallback(\n (err: string | null) => {\n setError(err);\n onErrorChange?.(err);\n },\n [onErrorChange],\n );\n\n const emitDecline = useCallback(\n (\n method: CheckoutButtonMethod,\n input: string | FloPayError,\n overrides?: { code?: string; declineCode?: string },\n ) => {\n onDecline?.(buildDeclineEvent(method, input, overrides));\n },\n [onDecline],\n );\n\n const showWallets = showApplePay || showGooglePay;\n\n const handleNameChange = useCallback((value: string) => {\n setFullName(value);\n const parts = value.trim().split(/\\s+/);\n onFirstNameChange?.(parts[0] ?? '');\n onLastNameChange?.(parts.length > 1 ? parts.slice(1).join(' ') : '');\n }, [onFirstNameChange, onLastNameChange]);\n\n const runBeforeCardButtonClick = useCallback(async (): Promise<boolean> => {\n if (!onBeforeButtonClick) return true;\n\n try {\n const result = await onBeforeButtonClick({\n method: 'card',\n sessionId: sessionId || undefined,\n });\n\n if (result === false) {\n return false;\n }\n\n if (result && typeof result === 'object') {\n await checkout.applyInlineSessionPatch?.(result);\n\n if (result.account) {\n setAccountPatch((prev) => ({ ...(prev ?? {}), ...result.account }));\n }\n }\n\n return true;\n } catch (err) {\n const floPayErr = err instanceof FloPayError\n ? err\n : new FloPayError(\n err instanceof Error ? err.message : 'Card before-click hook failed.',\n 'validation_error',\n );\n updateError(floPayErr.message);\n onError?.(floPayErr);\n return false;\n }\n }, [checkout.applyInlineSessionPatch, onBeforeButtonClick, sessionId, updateError, onError]);\n\n // ── Internal processPayment + 3DS retry ──\n\n const processPaymentInternal = useCallback(\n async (tokenizedBody: TokenizedBody) => {\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 try {\n const response = await fetch(`${baseUrl}/v1/checkouts/sessions/process`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'x-user-id': resolvedAccount.userId ?? '',\n },\n body: JSON.stringify({\n sessionId,\n tokenizedData: tokenizedBody,\n accountData: {\n userId: resolvedAccount.userId ?? '',\n email: resolvedAccount.email ?? '',\n firstName: resolvedAccount.firstName ?? fullName.trim().split(/\\s+/)[0] ?? '',\n lastName: resolvedAccount.lastName ?? fullName.trim().split(/\\s+/).slice(1).join(' ') ?? '',\n ...(enableAVS ? { zip: zipCodeRef.current, country: selectedCountryRef.current } : {}),\n },\n chv,\n }),\n });\n\n if (response.ok) {\n setOverlayStatus('success');\n await new Promise((r) => setTimeout(r, 1200));\n onComplete?.({\n status: 'succeeded',\n paymentIntentId: tokenizedBody.threeDSecureActionResultTokenId,\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 const result = await flopay.confirmPayment({\n clientSecret: secret,\n returnUrl: window.location.href,\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 }\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 const stripeInstance = flopay.getRawProvider() as Stripe | null;\n if (!stripeInstance) {\n updateError('Payment provider 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 stripeInstance.confirmPayment({\n clientSecret: secret,\n confirmParams: confirmParams as { return_url: string },\n redirect: 'if_required',\n });\n\n if (confirmError) {\n setOverlayStatus('error');\n const message = confirmError.message ?? 'PayPal payment failed.';\n updateError(message);\n emitDecline('paypal', message, {\n code: confirmError.code,\n });\n }\n } catch (err) {\n setOverlayStatus('error');\n updateError(err instanceof Error ? err.message : 'PayPal authorization failed.');\n }\n return;\n }\n\n setOverlayStatus('error');\n const message = (json?.message as string) ?? 'Payment failed. Please try again.';\n updateError(message);\n emitDecline(tokenizedBody.isPaypal ? 'paypal' : 'card', message, {\n code: (json?.code ?? json?.gatewayErrorCode) as string | undefined,\n declineCode: (json?.declineCode ?? json?.gatewayDeclineReason) as string | undefined,\n });\n await new Promise((r) => setTimeout(r, 1500));\n } catch (err) {\n setOverlayStatus('error');\n updateError(err instanceof Error ? err.message : 'An unexpected error occurred');\n await new Promise((r) => setTimeout(r, 1500));\n } finally {\n setProcessing(false);\n setOverlayStatus(null);\n processingRef.current = false;\n }\n },\n [baseUrl, sessionId, resolvedAccount, fullName, chv, flopay, onComplete, onError, updateError, emitDecline],\n );\n\n const dispatchTokenizedBody = useCallback(\n (tokenizedBody: TokenizedBody) => {\n if (onTokenizedBody) {\n onTokenizedBody(tokenizedBody);\n } else {\n processPaymentInternal(tokenizedBody);\n }\n },\n [onTokenizedBody, processPaymentInternal],\n );\n\n // ── Imperative 3DS handler ──\n\n useImperativeHandle(innerRef, () => ({\n async handleNextAction(secret: string) {\n if (!flopay) return;\n\n setIs3DSActive(true);\n try {\n const result = await flopay.confirmPayment({\n clientSecret: secret,\n returnUrl: window.location.href,\n });\n\n if (result.error) {\n updateError(result.error.message);\n onError?.(result.error);\n emitDecline('card', result.error);\n } else if (result.status === 'succeeded' || result.status === 'processing') {\n dispatchTokenizedBody({\n id: result.paymentIntentId,\n type: 'card',\n threeDSecureActionResultTokenId: result.paymentIntentId,\n });\n }\n } catch (err) {\n updateError(err instanceof Error ? err.message : 'Payment authentication failed.');\n } finally {\n setIs3DSActive(false);\n }\n },\n }), [flopay, dispatchTokenizedBody, onError, updateError, emitDecline]);\n\n // ── Wallet resume ──\n\n useEffect(() => {\n if (typeof window === 'undefined') return;\n\n const stored = localStorage.getItem(WALLET_RESUME_KEY);\n if (!stored) return;\n\n try {\n const payload = JSON.parse(stored) as {\n sessionId: string;\n paymentIntentId: string;\n tokenType: string;\n tokenId: string;\n status: string;\n };\n\n if (payload.sessionId === sessionId) {\n localStorage.removeItem(WALLET_RESUME_KEY);\n dispatchTokenizedBody({\n id: payload.tokenId,\n type: payload.tokenType,\n threeDSecureActionResultTokenId: payload.paymentIntentId,\n });\n }\n } catch {\n localStorage.removeItem(WALLET_RESUME_KEY);\n }\n }, [sessionId, dispatchTokenizedBody]);\n\n // ── Card submit ──\n\n const handleSubmit = useCallback(\n async (e: React.FormEvent) => {\n e.preventDefault();\n if (!flopay || !elements || isSubmitting || processingRef.current) return;\n\n if (layout !== 'buttons') {\n onButtonClick?.('card');\n }\n setProcessing(true);\n setOverlayStatus('processing');\n updateError(null);\n\n // Track whether we handed off to processPaymentInternal (which manages its own overlay)\n let handedOff = false;\n\n try {\n // Matches checkout/StripeCardForm exactly:\n // 1. createPaymentMethod → 2. createPaymentIntent → 3. confirmCardPayment → 4. onTokenizedBody\n\n // 0. Validate AVS fields (required when enableAVS is true)\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 (enableAVS && !zipCodeRef.current.trim()) {\n updateError(getPostalCodeLabel(selectedCountryRef.current) + ' is required');\n return;\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 const billingDetails = enableAVS ? {\n name: fullName,\n address: {\n country: selectedCountryRef.current,\n postal_code: zipCodeRef.current,\n },\n } : undefined;\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) throw new FloPayError('Failed to create payment intent', 'api_error');\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, 1500));\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: pmResult.paymentMethodId,\n type: 'card',\n threeDSecureActionResultTokenId: confirmResult.paymentIntentId,\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, 1500));\n } finally {\n if (!handedOff) {\n setProcessing(false);\n setOverlayStatus(null);\n }\n }\n },\n [flopay, elements, isSubmitting, sessionId, resolvedAccount.email, baseUrl, isSelfContained, dispatchTokenizedBody, onButtonClick, onError, updateError, emitDecline, layout],\n );\n\n const isReady = flopay !== null && elements !== null;\n\n if (!isReady) {\n return <div data-testid=\"flopay-loading\" aria-busy=\"true\">Loading payment form...</div>;\n }\n\n const isButtons = layout === 'buttons';\n const resolvedBorder = isButtons ? (bStyles.cardInputBorder ?? '#e5e7eb') : '#A4A4FF';\n const cardBg = isButtons ? ((bStyles.cardFormContainer?.backgroundColor as string) ?? 'white') : '#EDEDFF';\n const cardInputBg = isButtons ? (bStyles.cardInputBackground ?? 'white') : 'white';\n const hideBackButtonLabel = isEmptySlotContent(cardBackButtonContent);\n const hideTitle = isEmptySlotContent(cardTitleContent);\n const nameInputOverrides = isButtons ? bStyles.nameInput : undefined;\n const resolvedInputFontSize = bStyles.cardInputFontSize\n ?? toCssSize(nameInputOverrides?.fontSize)\n ?? '16px';\n const resolvedInputFontFamily = typeof nameInputOverrides?.fontFamily === 'string'\n ? nameInputOverrides.fontFamily\n : 'Poppins, sans-serif';\n const resolvedInputFontWeight = toCssWeight(nameInputOverrides?.fontWeight) ?? 400;\n const resolvedInputColor = bStyles.cardInputColor\n ?? (typeof nameInputOverrides?.color === 'string' ? nameInputOverrides.color : undefined)\n ?? '#262833';\n const resolvedPlaceholderColor = bStyles.cardInputPlaceholderColor ?? '#9ca3af';\n const sharedInputTypography: React.CSSProperties = {\n fontSize: resolvedInputFontSize,\n fontFamily: resolvedInputFontFamily,\n fontWeight: resolvedInputFontWeight,\n color: resolvedInputColor,\n WebkitFontSmoothing: 'antialiased',\n MozOsxFontSmoothing: 'grayscale',\n };\n const sharedInputPlaceholderVars = {\n '--flopay-input-placeholder-color': resolvedPlaceholderColor,\n '--flopay-input-font-size': resolvedInputFontSize,\n '--flopay-input-font-family': resolvedInputFontFamily,\n '--flopay-input-font-weight': String(resolvedInputFontWeight),\n } as React.CSSProperties;\n\n // Stripe Element style — keeps the iframe typography aligned with the plain text inputs.\n const stripeElementStyle = {\n style: {\n base: {\n ...sharedInputTypography,\n fontSmoothing: 'antialiased',\n '::placeholder': {\n color: resolvedPlaceholderColor,\n fontSize: resolvedInputFontSize,\n fontFamily: resolvedInputFontFamily,\n fontWeight: resolvedInputFontWeight,\n },\n },\n invalid: { color: '#ef4444' },\n },\n };\n\n // ── Card fields block (shared between both layouts) ──\n const cardFormBlock = (\n <div style={{\n backgroundColor: cardBg, borderRadius: '8px',\n padding: isButtons ? '0' : '1rem',\n ...(isButtons ? bStyles.cardFormContainer as React.CSSProperties : {}),\n ...(isButtons ? { padding: bStyles.cardFormContainer?.padding ?? '0' } : {}),\n ...sharedInputPlaceholderVars,\n }}>\n <style>{`\n .flopay-shared-input::placeholder {\n color: var(--flopay-input-placeholder-color);\n opacity: 1;\n font-size: var(--flopay-input-font-size);\n font-family: var(--flopay-input-font-family);\n font-weight: var(--flopay-input-font-weight);\n }\n `}</style>\n {/* Header: back button + title on same row (buttons layout) */}\n {isButtons && showCardForm && (\n <div style={{\n display: 'flex', alignItems: 'center', padding: '0.75rem 0 0.625rem',\n }}>\n <button\n type=\"button\"\n onClick={collapseToButtons}\n style={{\n display: 'inline-flex', alignItems: 'center', gap: hideBackButtonLabel ? 0 : '0.5rem',\n background: 'none', border: 'none', cursor: 'pointer',\n color: '#4b5563', fontSize: bStyles.backButtonFontSize ?? '0.85rem', fontWeight: 500,\n padding: 0, transition: 'color 0.15s', flexShrink: 0,\n ...bStyles.backButton as React.CSSProperties,\n }}\n aria-label=\"Back to payment methods\"\n >\n <span style={{\n display: 'inline-flex', alignItems: 'center', justifyContent: 'center',\n width: 28, height: 28, borderRadius: '50%',\n backgroundColor: '#f3f4f6', transition: 'background-color 0.15s',\n ...bStyles.backButtonIcon as React.CSSProperties,\n }}>\n <svg width=\"14\" height=\"14\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2.5\" strokeLinecap=\"round\" strokeLinejoin=\"round\">\n <path d=\"M15 18l-6-6 6-6\" />\n </svg>\n </span>\n <BackButtonContentSlot content={cardBackButtonContent} />\n </button>\n {hideTitle ? (\n <div style={{ flex: 1 }} />\n ) : (\n <div style={{\n flex: 1, textAlign: 'center', fontWeight: 600,\n fontSize: bStyles.titleFontSize ?? '1.05rem',\n color: '#262833', paddingRight: 80,\n ...bStyles.title as React.CSSProperties,\n }}>\n <TitleContentSlot content={cardTitleContent} />\n </div>\n )}\n </div>\n )}\n\n {/* Title (default layout only) */}\n {!isButtons && !hideTitle && (\n <div style={{ textAlign: 'center', fontWeight: 600, fontSize: '1.1rem', padding: '0.5rem 0', color: '#262833' }}>\n <TitleContentSlot content={cardTitleContent} />\n </div>\n )}\n\n {/* Card Number */}\n <div style={{\n backgroundColor: cardInputBg, border: `1px solid ${resolvedBorder}`,\n borderTopLeftRadius: '8px', borderTopRightRadius: '8px', padding: '10px',\n }}>\n <CardNumberElement onReady={() => setFormReady(true)} options={stripeElementStyle} />\n </div>\n\n {/* Expiry + CVC */}\n <div style={{ display: 'flex' }}>\n <div style={{\n flex: 1, backgroundColor: cardInputBg, border: `1px solid ${resolvedBorder}`,\n borderTop: 'none', borderRight: 'none',\n borderBottomLeftRadius: '8px', padding: '10px',\n }}>\n <CardExpiryElement options={stripeElementStyle} />\n </div>\n <div style={{\n flex: 1, backgroundColor: cardInputBg, border: `1px solid ${resolvedBorder}`,\n borderTop: 'none', borderBottomRightRadius: '8px', padding: '10px',\n }}>\n <CardCvcElement options={stripeElementStyle} />\n </div>\n </div>\n\n {/* Full Name */}\n <div style={{\n backgroundColor: cardInputBg, border: `1px solid ${resolvedBorder}`,\n borderRadius: '8px', marginTop: '0.5rem', padding: '10px',\n }}>\n <input\n className=\"flopay-shared-input\"\n placeholder=\"Full Name on Card\"\n autoComplete=\"cc-name\"\n value={fullName}\n onChange={(e) => handleNameChange(e.target.value)}\n disabled={isSubmitting}\n required\n style={{\n width: '100%', border: 'none', outline: 'none', background: 'transparent',\n ...sharedInputTypography,\n ...(isButtons && bStyles.nameInput ? bStyles.nameInput as React.CSSProperties : {}),\n }}\n />\n </div>\n\n {/* AVS: Country + ZIP/Postcode */}\n {enableAVS && (\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 <div style={{\n flex: avsLayoutProp === 'row' ? 1 : undefined,\n backgroundColor: cardInputBg, border: `1px solid ${resolvedBorder}`,\n padding: '10px',\n ...(avsLayoutProp === 'row'\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 }}\n disabled={isSubmitting}\n autoComplete=\"country\"\n data-testid=\"flopay-country\"\n style={{\n width: '100%', border: 'none', outline: 'none', background: 'transparent',\n ...sharedInputTypography,\n cursor: 'pointer',\n ...(isButtons && bStyles.nameInput ? bStyles.nameInput as React.CSSProperties : {}),\n }}\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 <div style={{\n flex: avsLayoutProp === 'row' ? 1 : undefined,\n backgroundColor: cardInputBg, border: `1px solid ${resolvedBorder}`,\n padding: '10px',\n ...(avsLayoutProp === 'row'\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={{\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 </div>\n )}\n\n {displayError && (\n <div role=\"alert\" data-testid=\"flopay-error\" style={{\n margin: '0.75rem 0', padding: '0.625rem 0.875rem',\n background: '#FEF2F2', border: '1px solid #FECACA', borderRadius: '8px',\n color: '#991B1B', fontSize: '0.85rem', fontWeight: 600,\n display: 'flex', alignItems: 'center', gap: '0.5rem',\n ...(isButtons && bStyles.errorBanner ? bStyles.errorBanner as React.CSSProperties : {}),\n }}>\n <svg width=\"16\" height=\"16\" viewBox=\"0 0 24 24\" fill=\"none\" style={{ flexShrink: 0 }}>\n <path d=\"M12 9v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z\" stroke=\"#DC2626\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\" />\n </svg>\n {displayError}\n </div>\n )}\n\n {children ?? (\n <button\n type=\"submit\"\n disabled={!formReady || isSubmitting}\n data-testid=\"flopay-submit\"\n style={{\n width: '100%', padding: '0.875rem', marginTop: '1rem',\n backgroundColor: '#4A49FF', color: 'white', border: 'none',\n borderRadius: '8px',\n fontSize: (isButtons && bStyles.submitButtonFontSize) ? bStyles.submitButtonFontSize : '1rem',\n fontWeight: 600,\n cursor: !formReady || isSubmitting ? 'not-allowed' : 'pointer',\n opacity: !formReady || isSubmitting ? 0.5 : 1,\n ...((isButtons ? bStyles.submitButton : {}) as React.CSSProperties),\n }}\n >\n {isSubmitting ? 'PROCESSING...' : submitLabel}\n </button>\n )}\n\n {/* Security footer — only in default layout */}\n {!isButtons && (\n <div style={{\n backgroundColor: '#EFF9F0', borderRadius: '8px', padding: '0.75rem',\n marginTop: '0.75rem', textAlign: 'center', fontSize: '0.85rem',\n fontWeight: 600, color: '#7DAD3A',\n }}>\n Secure Card Checkout\n </div>\n )}\n </div>\n );\n\n // ── Buttons layout ──\n if (layout === 'buttons') {\n const isButtonsView = viewState === 'buttons' || viewState === 'expanding';\n const isCardView = viewState === 'expanding' || viewState === 'card' || viewState === 'collapsing';\n\n const buttonsAnim = viewState === 'expanding'\n ? `flopay-buttons-exit ${TRANSITION_MS}ms cubic-bezier(0.4, 0, 0.2, 1) both`\n : viewState === 'collapsing'\n ? `flopay-buttons-enter ${TRANSITION_MS}ms cubic-bezier(0, 0, 0.2, 1) both`\n : undefined;\n\n const cardAnim = viewState === 'expanding'\n ? `flopay-card-enter ${TRANSITION_MS}ms cubic-bezier(0, 0, 0.2, 1) both`\n : viewState === 'collapsing'\n ? `flopay-card-exit ${TRANSITION_MS}ms cubic-bezier(0.4, 0, 0.2, 1) both`\n : undefined;\n\n return (\n <form onSubmit={handleSubmit} className={className} style={{ position: 'relative' }}>\n <FloPayKeyframes />\n {overlayStatus && <ProcessingOverlay status={overlayStatus} errorMessage={displayError} />}\n\n {/* Container — uses grid overlap so both views can coexist during transition */}\n <div style={{ display: 'grid' }}>\n\n {/* Payment method buttons — always mounted to preserve PayPal/wallet Elements */}\n <div style={{\n gridArea: '1 / 1',\n display: 'flex', flexDirection: 'column', gap: '0.5rem',\n // When card form is showing (and not transitioning), hide but keep mounted\n ...(!isButtonsView && !buttonsAnim ? { visibility: 'hidden' as const, position: 'absolute' as const, pointerEvents: 'none' as const, width: '100%' } : {}),\n ...(buttonsAnim ? { animation: buttonsAnim, pointerEvents: 'none' as const } : {}),\n }}>\n {/* PayPal */}\n {showPayPal && stripeInstance ? (\n <StripeElements stripe={stripeInstance} 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 />\n </StripeElements>\n ) : showPayPal ? (\n <div style={{ height: 44, borderRadius: 8, background: '#e5e7eb', animation: 'flopay-pulse 1.5s ease-in-out infinite' }} />\n ) : null}\n\n {/* Wallets (Apple Pay / Google Pay) */}\n {showWallets && stripeInstance ? (\n <StripeElements stripe={stripeInstance} options={walletOptions}>\n <WalletButtonInner\n sessionId={sessionId}\n email={resolvedAccount.email}\n billingApiUrl={resolvedBillingApiUrl}\n showApplePay={showApplePay}\n showGooglePay={showGooglePay}\n onTokenizedBody={dispatchTokenizedBody}\n onErrorChange={updateError}\n onButtonClick={onButtonClick}\n onDecline={onDecline}\n />\n </StripeElements>\n ) : showWallets ? (\n <div style={{ height: 44, borderRadius: 8, background: '#e5e7eb', animation: 'flopay-pulse 1.5s ease-in-out infinite' }} />\n ) : null}\n\n {/* Credit / Debit Card button */}\n <button\n type=\"button\"\n onClick={async () => {\n if (isSubmitting) return;\n const shouldContinue = await runBeforeCardButtonClick();\n if (!shouldContinue) return;\n onButtonClick?.('card');\n expandToCard();\n }}\n disabled={isSubmitting}\n style={{\n width: '100%', padding: '0.9rem 1rem',\n backgroundColor: 'white', color: '#262833',\n border: '1px solid #d1d5db', borderRadius: '8px',\n fontSize: bStyles.cardButtonFontSize ?? '0.95rem', fontWeight: 600,\n cursor: isSubmitting ? 'not-allowed' : 'pointer', display: 'flex',\n alignItems: 'center', justifyContent: 'center', gap: '0.625rem',\n transition: 'border-color 0.2s, box-shadow 0.2s, transform 0.1s',\n boxShadow: '0 1px 2px rgba(0,0,0,0.04)',\n position: 'relative',\n opacity: isSubmitting ? 0.6 : 1,\n ...bStyles.cardButton as React.CSSProperties,\n }}\n onMouseDown={(e) => { e.currentTarget.style.transform = 'scale(0.985)'; }}\n onMouseUp={(e) => { e.currentTarget.style.transform = 'scale(1)'; }}\n >\n <CardButtonContentSlot content={cardButtonContent} />\n </button>\n\n {displayError && viewState === 'buttons' && (\n <div role=\"alert\" data-testid=\"flopay-error\" style={{\n margin: '0.25rem 0', padding: '0.625rem 0.875rem',\n background: '#FEF2F2', border: '1px solid #FECACA', borderRadius: '8px',\n color: '#991B1B', fontSize: '0.85rem', fontWeight: 600,\n display: 'flex', alignItems: 'center', gap: '0.5rem',\n ...(bStyles.errorBanner ? bStyles.errorBanner as React.CSSProperties : {}),\n }}>\n <svg width=\"16\" height=\"16\" viewBox=\"0 0 24 24\" fill=\"none\" style={{ flexShrink: 0 }}>\n <path d=\"M12 9v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z\" stroke=\"#DC2626\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\" />\n </svg>\n {displayError}\n </div>\n )}\n </div>\n\n {/* Card form */}\n {isCardView && (\n <div style={{\n gridArea: '1 / 1',\n ...(cardAnim ? { animation: cardAnim } : {}),\n ...(viewState === 'collapsing' ? { pointerEvents: 'none' as const } : {}),\n }}>\n {cardFormBlock}\n </div>\n )}\n </div>\n </form>\n );\n }\n\n // ── Default layout ──\n return (\n <form onSubmit={handleSubmit} className={className} style={{ position: 'relative' }}>\n <FloPayKeyframes />\n {overlayStatus && <ProcessingOverlay status={overlayStatus} errorMessage={displayError} />}\n\n {/* Wallet buttons (Apple Pay / Google Pay) — own Stripe Elements instance */}\n {showWallets && stripeInstance && (\n <StripeElements stripe={stripeInstance} options={walletOptions}>\n <WalletButtonInner\n sessionId={sessionId}\n email={resolvedAccount.email}\n billingApiUrl={resolvedBillingApiUrl}\n showApplePay={showApplePay}\n showGooglePay={showGooglePay}\n onTokenizedBody={dispatchTokenizedBody}\n onErrorChange={updateError}\n onDecline={onDecline}\n />\n </StripeElements>\n )}\n\n {/* PayPal — own Stripe Elements instance */}\n {showPayPal && stripeInstance && (\n <StripeElements stripe={stripeInstance} options={paypalOptions}>\n <PayPalButtonInner\n sessionId={sessionId}\n email={resolvedAccount.email}\n billingApiUrl={resolvedBillingApiUrl}\n onTokenizedBody={dispatchTokenizedBody}\n onErrorChange={updateError}\n isProcessing={isSubmitting}\n onDecline={onDecline}\n />\n </StripeElements>\n )}\n\n {/* Divider between wallet/PayPal buttons and card fields */}\n {((showWallets && stripeInstance) || (showPayPal && stripeInstance)) && (\n <div style={{\n display: 'flex', alignItems: 'center', gap: '0.75rem',\n margin: '0.5rem 0 0.75rem', color: '#999', fontSize: '0.85rem',\n }}>\n <div style={{ flex: 1, height: 1, backgroundColor: '#ddd' }} />\n <span>or pay with card</span>\n <div style={{ flex: 1, height: 1, backgroundColor: '#ddd' }} />\n </div>\n )}\n\n {cardFormBlock}\n </form>\n );\n}\n","import { useContext } from 'react';\nimport type { FloPay, FloPayElements } from '@flopay/js';\nimport type { CheckoutSession, FloPayError } from '@flopay/shared';\nimport { resolveBillingApiUrl } from '@flopay/shared';\nimport { FloPayContext, CheckoutContext } from './context.js';\nimport type { CheckoutContextValue } from './context.js';\n\n/**\n * Returns the current `FloPay` instance, or `null` if the provider\n * is still loading (i.e. the `loadFloPay()` promise has not resolved yet).\n *\n * Must be called within a `<FloPayProvider>`.\n */\nexport function useFloPay(): FloPay | null {\n const ctx = useContext(FloPayContext);\n return ctx.flopay;\n}\n\n/**\n * Returns the 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 type {\n CheckoutAccount,\n CheckoutButtonMethod,\n CheckoutMode,\n CheckoutSession,\n DeclineEvent,\n InlineSessionDraft,\n InlineSessionParams,\n InlineSessionPatch,\n} from '@flopay/shared';\nimport { FloPayError } from '@flopay/shared';\n\nexport function mergeInlineSessionPatches(\n base: InlineSessionPatch | undefined,\n patch: InlineSessionPatch | undefined,\n): InlineSessionPatch | undefined {\n if (!patch) return base;\n if (!base) return patch;\n\n return {\n account: { ...(base.account ?? {}), ...(patch.account ?? {}) },\n couponCodes: patch.couponCodes ?? base.couponCodes,\n tagsData: {\n ...(base.tagsData ?? {}),\n ...(patch.tagsData ?? {}),\n },\n utmMetadata: patch.utmMetadata ?? base.utmMetadata,\n };\n}\n\nexport function mergeInlineSessionPatch(\n params: InlineSessionDraft,\n patch: InlineSessionPatch | undefined,\n): InlineSessionDraft {\n if (!patch) return params;\n\n return {\n ...params,\n account: {\n ...params.account,\n ...(patch.account ?? {}),\n },\n couponCodes: patch.couponCodes ?? params.couponCodes,\n tagsData: {\n ...(params.tagsData ?? {}),\n ...(patch.tagsData ?? {}),\n },\n utmMetadata: patch.utmMetadata ?? params.utmMetadata,\n };\n}\n\nexport function buildSyntheticSession(\n params: InlineSessionDraft,\n checkoutModeOverride?: CheckoutMode,\n): CheckoutSession {\n const totalAmount = [\n ...(params.items ?? []).map((item) => (item.overrideAmount ?? item.totalAmount) ?? 0),\n ...(params.subscriptions ?? []).map((subscription) => (subscription.overrideAmount ?? subscription.totalAmount) ?? 0),\n ].reduce((sum, value) => sum + value, 0);\n const currency = params.items?.[0]?.currency\n ?? params.subscriptions?.[0]?.currency\n ?? 'USD';\n\n return {\n id: '',\n clientSecret: '',\n mode: 'payment',\n amount: Math.round(totalAmount * 100),\n currency,\n status: 'open',\n customer: {\n id: params.account.userId,\n email: params.account.email ?? '',\n firstName: params.account.firstName,\n lastName: params.account.lastName,\n gender: params.account.gender ?? undefined,\n city: params.account.city ?? undefined,\n state: params.account.state ?? undefined,\n country: params.account.country ?? undefined,\n zip: params.account.zip ?? undefined,\n },\n successUrl: params.successUrl,\n cancelUrl: params.cancelUrl,\n checkoutMode: (params.checkoutMode ?? checkoutModeOverride ?? 'full') as CheckoutMode,\n items: (params.items ?? []).map((item, idx) => ({\n uuid: `synthetic-item-${idx}`,\n checkoutSessionId: '',\n providerItemId: item.providerItemId,\n providerItemName: item.providerItemName ?? item.providerItemId,\n quantity: item.quantity ?? 1,\n totalAmount: item.totalAmount,\n overrideAmount: item.overrideAmount ?? null,\n currency: item.currency ?? currency,\n })),\n subscriptions: (params.subscriptions ?? []).map((subscription, idx) => ({\n uuid: `synthetic-sub-${idx}`,\n checkoutSessionId: '',\n providerPlanId: subscription.providerPlanId,\n providerPlanName: subscription.providerPlanName ?? subscription.providerPlanId,\n quantity: subscription.quantity ?? 1,\n totalAmount: subscription.totalAmount,\n overrideAmount: subscription.overrideAmount ?? null,\n currency: subscription.currency ?? currency,\n })),\n };\n}\n\nexport function ensureInlineSessionReady(\n params: InlineSessionDraft,\n): asserts params is InlineSessionParams {\n if (!params.account.email?.trim()) {\n throw new FloPayError(\n 'Email is required before continuing with card checkout.',\n 'validation_error',\n { param: 'createSession.account.email' },\n );\n }\n}\n\nexport function splitFullName(name: string | null | undefined): {\n firstName?: string;\n lastName?: string;\n} {\n const parts = name?.trim().split(/\\s+/).filter(Boolean) ?? [];\n if (parts.length === 0) return {};\n return {\n firstName: parts[0],\n lastName: parts.length > 1 ? parts.slice(1).join(' ') : undefined,\n };\n}\n\nexport function mergeAccountPatch<T extends {\n userId?: string;\n email?: string;\n firstName?: string;\n lastName?: string;\n country?: string | null;\n zip?: string | null;\n}>(\n base: T,\n patch: Partial<CheckoutAccount> | undefined,\n): T {\n if (!patch) return base;\n return {\n ...base,\n ...patch,\n };\n}\n\nexport function buildDeclineEvent(\n method: CheckoutButtonMethod,\n input: string | FloPayError,\n overrides?: {\n code?: string;\n declineCode?: string;\n },\n): DeclineEvent {\n const message = typeof input === 'string' ? input : input.message;\n const code = typeof input === 'string' ? overrides?.code : overrides?.code ?? input.code;\n const declineCode = typeof input === 'string'\n ? overrides?.declineCode\n : overrides?.declineCode ?? input.declineCode;\n\n return {\n method,\n message,\n ...(code ? { code } : {}),\n ...(declineCode ? { declineCode } : {}),\n };\n}\n","import type {\n DeclineEvent,\n PaymentResult,\n TokenizedBody,\n} from '@flopay/shared';\nimport { FloPayError } from '@flopay/shared';\nimport React, { forwardRef, useCallback, useEffect, useImperativeHandle, useState } from 'react';\nimport { useFloPay, useElements, useBillingApiUrl } from './hooks.js';\nimport { PaymentElement } from './elements.js';\nimport { AddressElement } from './elements.js';\nimport { buildDeclineEvent } 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 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 (tokenizedBody: TokenizedBody) => {\n setProcessing(true);\n updateError(null);\n\n try {\n const response = await fetch(`${baseUrl}/v1/checkouts/sessions/process`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'x-user-id': userId ?? '',\n },\n body: JSON.stringify({\n sessionId,\n tokenizedData: tokenizedBody,\n accountData: {\n userId: userId ?? '',\n email: email ?? '',\n firstName: firstName ?? '',\n lastName: lastName ?? '',\n },\n chv,\n }),\n });\n\n if (response.ok) {\n onComplete?.({\n status: 'succeeded',\n paymentIntentId: tokenizedBody.threeDSecureActionResultTokenId,\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 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 return;\n }\n\n if (result.status === 'succeeded' || result.status === 'processing') {\n // Resubmit with 3DS result — only send the 3DS token, not original card token\n await processPaymentInternal({\n id: result.paymentIntentId,\n type: 'card',\n threeDSecureActionResultTokenId: result.paymentIntentId,\n });\n }\n } finally {\n setIs3DSActive(false);\n }\n return;\n }\n\n // PayPal redirect required\n if (json?.type === 'paypal_redirect_required') {\n const secret = json['clientSecret'] as string;\n const pmId = json['paymentMethodId'] as string;\n if (flopay && secret) {\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 await flopay.confirmPayment({\n clientSecret: secret,\n returnUrl: window.location.href,\n });\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, onComplete, onError, 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\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 pmResult = await flopay.createPaymentMethod();\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) throw new FloPayError('Failed to create payment intent', 'api_error');\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 // 5. Send PM + PI to processPaymentInternal (or parent via onTokenizedBody)\n dispatchTokenizedBody({\n id: pmResult.paymentMethodId,\n type: 'card',\n threeDSecureActionResultTokenId: confirmResult.paymentIntentId,\n });\n } catch (err) {\n updateError(err instanceof Error ? err.message : 'An unexpected error occurred');\n } finally {\n if (isSelfContained) {\n // processing state managed by processPaymentInternal\n } else {\n setProcessing(false);\n }\n }\n },\n [flopay, elements, isSubmitting, sessionId, email, baseUrl, isSelfContained, dispatchTokenizedBody, onError, updateError, emitDecline],\n );\n\n const isReady = flopay !== null && elements !== null;\n\n return (\n <form onSubmit={handleSubmit} className={className} style={{ position: 'relative' }}>\n {(is3DSActive || isSubmitting) && (\n <div data-testid=\"flopay-overlay\" style={{\n position: 'absolute', inset: 0,\n background: 'rgba(255,255,255,0.7)',\n display: 'flex', alignItems: 'center', justifyContent: 'center',\n zIndex: 10,\n }}>\n {is3DSActive ? 'Verifying payment...' : 'Processing...'}\n </div>\n )}\n\n {!isReady && (\n <div data-testid=\"flopay-loading\" aria-busy=\"true\">\n Loading payment form...\n </div>\n )}\n\n {isReady && (\n <>\n <PaymentElement options={{ layout }} />\n\n {showAddress && (\n <AddressElement options={{ mode: showAddress === true ? 'billing' : showAddress }} />\n )}\n\n {displayError && (\n <div role=\"alert\" data-testid=\"flopay-error\" style={{ color: 'red', margin: '0.75rem 0' }}>\n {displayError}\n </div>\n )}\n\n {children ?? (\n <button\n type=\"submit\"\n disabled={isSubmitting || !isReady}\n data-testid=\"flopay-submit\"\n >\n {isSubmitting ? 'Processing...' : submitLabel}\n </button>\n )}\n </>\n )}\n </form>\n );\n}\n","import type { TokenizedBody } from '@flopay/shared';\nimport { FloPayError } from '@flopay/shared';\nimport React, { useCallback, useEffect, useRef, useState } from 'react';\nimport { useFloPay, useElements, useBillingApiUrl } from './hooks.js';\n\n/**\n * Props for the `PayPalButton` component.\n *\n * Must be rendered inside its own `FloPayProvider` with `paymentMethodCreation: undefined`\n * (not 'manual') — PayPal cannot share the same Elements instance as card fields.\n */\nexport interface PayPalButtonProps {\n /** The checkout session ID (UUID from billing API). */\n sessionId: string;\n /** Billing API base URL. Optional — defaults to the value from FloPayProvider or the shared constant. */\n billingApiUrl?: string;\n /** User's email. */\n email?: string;\n /** User ID for processing payments. */\n userId?: string;\n /** First name for billing. */\n firstName?: string;\n /** Last name for billing. */\n lastName?: string;\n /** Checkout version for tracking. */\n chv?: string;\n /**\n * Called with tokenized data after PayPal authorization.\n * If omitted, the component calls processPayment internally.\n */\n onTokenizedBody?: (body: TokenizedBody) => void;\n /** Called on successful payment (self-contained mode). */\n onComplete?: () => void;\n /** Called when an error occurs. */\n onErrorChange?: (error: string | null) => void;\n /** External processing state. */\n isProcessing?: boolean;\n}\n\n/**\n * PayPal button that handles the full PayPal payment flow.\n *\n * **Important**: PayPal requires its own `FloPayProvider` — it cannot share\n * the same Stripe Elements instance as card fields when they use\n * `paymentMethodCreation: 'manual'`. This matches `checkout/StripeCardForm`\n * which renders PayPal in a separate `<Elements>` wrapper.\n *\n * ```tsx\n * {/* Card fields provider (paymentMethodCreation: 'manual') *\\/}\n * <FloPayProvider flopay={flopay} options={{ amount, currency }}>\n * <SplitCardForm ... />\n * </FloPayProvider>\n *\n * {/* PayPal provider (no paymentMethodCreation) *\\/}\n * <FloPayProvider flopay={flopay} options={{ amount, currency, paymentMethodCreation: 'auto' }}>\n * <PayPalButton ... />\n * </FloPayProvider>\n * ```\n */\nexport function PayPalButton({\n sessionId,\n billingApiUrl,\n email,\n userId,\n firstName,\n lastName,\n chv,\n onTokenizedBody,\n onComplete,\n onErrorChange,\n isProcessing = false,\n}: PayPalButtonProps): React.ReactElement {\n const flopay = useFloPay();\n const elements = useElements();\n const contextBillingUrl = useBillingApiUrl();\n const [ready, setReady] = useState(false);\n const [submitting, setSubmitting] = useState(false);\n const paypalResumeAttempted = useRef(false);\n const baseUrl = (billingApiUrl || contextBillingUrl).replace(/\\/+$/, '');\n\n // ── Internal processPayment (self-contained mode) ──\n\n const processPaymentInternal = useCallback(\n async (tokenizedBody: TokenizedBody) => {\n try {\n const response = await fetch(`${baseUrl}/v1/checkouts/sessions/process`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'x-user-id': userId ?? '',\n },\n body: JSON.stringify({\n sessionId,\n tokenizedData: tokenizedBody,\n accountData: {\n userId: userId ?? '',\n email: email ?? '',\n firstName: firstName ?? '',\n lastName: lastName ?? '',\n },\n chv,\n }),\n });\n\n if (response.ok) {\n onComplete?.();\n return;\n }\n\n const json = await response.json().catch(() => null) as Record<string, unknown> | null;\n onErrorChange?.((json?.message as string) ?? 'Payment failed. Please try again.');\n } catch (err) {\n onErrorChange?.(err instanceof Error ? err.message : 'An unexpected error occurred');\n }\n },\n [baseUrl, sessionId, userId, email, firstName, lastName, chv, onComplete, onErrorChange],\n );\n\n const dispatchTokenizedBody = useCallback(\n (body: TokenizedBody) => {\n if (onTokenizedBody) {\n onTokenizedBody(body);\n } else {\n processPaymentInternal(body);\n }\n },\n [onTokenizedBody, processPaymentInternal],\n );\n\n // ── Resume PayPal redirect return ──\n\n useEffect(() => {\n if (!flopay || paypalResumeAttempted.current) return;\n\n const params = new URLSearchParams(window.location.search);\n const paymentIntentId = params.get('payment_intent');\n const clientSecret = params.get('payment_intent_client_secret');\n const redirectStatus = params.get('redirect_status');\n\n if (!paymentIntentId || !clientSecret) return;\n paypalResumeAttempted.current = true;\n\n (async () => {\n try {\n setSubmitting(true);\n\n if (redirectStatus === 'failed') {\n onErrorChange?.('PayPal payment was declined. Please try again.');\n return;\n }\n\n // Retrieve the PaymentIntent to check status (matches checkout/StripeCardForm resume)\n const provider = flopay.getRawProvider() as { retrievePaymentIntent?: (cs: string) => Promise<{ paymentIntent?: { id: string; status: string; payment_method: string | { id: string } }; error?: { message: string } }> } | null;\n if (!provider?.retrievePaymentIntent) {\n onErrorChange?.('Cannot retrieve PayPal payment status.');\n return;\n }\n\n const { paymentIntent, error: retrieveError } = await provider.retrievePaymentIntent(clientSecret);\n if (retrieveError) {\n onErrorChange?.(retrieveError.message ?? 'Failed to retrieve PayPal payment status.');\n return;\n }\n\n if (paymentIntent && (paymentIntent.status === 'requires_capture' || paymentIntent.status === 'succeeded')) {\n const pmId = typeof paymentIntent.payment_method === 'string'\n ? paymentIntent.payment_method\n : paymentIntent.payment_method?.id;\n\n dispatchTokenizedBody({\n id: pmId ?? paymentIntent.id,\n type: 'card',\n threeDSecureActionResultTokenId: paymentIntent.id,\n isPaypal: true,\n });\n\n // Clean up URL params\n const url = new URL(window.location.href);\n url.searchParams.delete('payment_intent');\n url.searchParams.delete('payment_intent_client_secret');\n url.searchParams.delete('redirect_status');\n window.history.replaceState({}, '', url.toString());\n } else {\n onErrorChange?.('PayPal payment was not completed. Please try again.');\n }\n } catch (err) {\n onErrorChange?.(err instanceof Error ? err.message : 'Failed to complete PayPal payment.');\n } finally {\n setSubmitting(false);\n }\n })();\n }, [flopay, dispatchTokenizedBody, onErrorChange]);\n\n // ── PayPal confirm handler ──\n\n const handlePayPalConfirm = useCallback(async () => {\n if (!flopay || !elements) return;\n\n try {\n setSubmitting(true);\n onErrorChange?.(null);\n\n if (!sessionId || !email) {\n throw new FloPayError('Missing sessionId or email for PayPal payment', 'validation_error');\n }\n\n // 1. Create PaymentIntent via billing API with PayPal flag\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: 'paypal',\n isPaypal: 'true',\n }),\n });\n\n if (!intentResponse.ok) throw new FloPayError('Failed to create payment intent', 'api_error');\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 response', 'api_error');\n\n // 2. Confirm payment — PayPal will redirect\n const result = await flopay.confirmPayment({\n clientSecret: intentClientSecret,\n returnUrl: window.location.href,\n });\n\n // If we get here without redirect, payment completed inline\n if (result.status === 'succeeded' || result.status === 'processing') {\n dispatchTokenizedBody({\n id: result.paymentIntentId,\n type: 'card',\n threeDSecureActionResultTokenId: result.paymentIntentId,\n isPaypal: true,\n });\n } else if (result.error) {\n onErrorChange?.(result.error.message);\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"],"mappings":";AAAA,SAAgB,WAAW,UAAU,eAAe;AAGpD,SAAS,4BAA4B;;;ACHrC,SAAS,qBAAqB;AA0BvB,IAAM,gBAAgB,cAAkC;AAAA,EAC7D,QAAQ;AAAA,EACR,UAAU;AAAA,EACV,eAAe;AACjB,CAAC;AAEM,IAAM,kBAAkB,cAAoC;AAAA,EACjE,SAAS;AAAA,EACT,SAAS;AAAA,EACT,OAAO;AACT,CAAC;;;AD4DG;AA1DG,SAAS,eAAe;AAAA,EAC7B,QAAQ;AAAA,EACR;AAAA,EACA;AACF,GAA4C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MAAU,WAAW;AAAA,MAA+B,OAAO;AAAA,IACxE,GAAG,0CAEH,GACF;AAAA,KAEJ;AAEJ;","names":["React","useCallback","useEffect","useMemo","useRef","useState","FloPayError","resolveBillingApiUrl","resolveButtonsLayoutTheme","jsx","useEffect","jsx","useEffect","useContext","useEffect","useMemo","useRef","useState","useContext","resolveBillingApiUrl","useContext","resolveBillingApiUrl","FloPayError","Fragment","jsx","jsxs","SplitCardForm","useState","useRef","useEffect","useContext","useMemo","stripeInstance","message","Fragment","jsx","jsxs","resolveBillingApiUrl","useState","useRef","useMemo","useEffect","useCallback","FloPayError","React","resolveButtonsLayoutTheme","FloPayError","forwardRef","useCallback","useEffect","useImperativeHandle","useState","Fragment","jsx","jsxs","WALLET_RESUME_KEY","forwardRef","CheckoutForm","useState","useCallback","useImperativeHandle","useEffect","FloPayError","FloPayError","useCallback","useEffect","useRef","useState","Fragment","jsx","jsxs","useState","useRef","useCallback","useEffect","FloPayError"]}