@flopay/react 0.1.5 → 0.1.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +279 -92
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +10 -1
- package/dist/index.d.ts +10 -1
- package/dist/index.mjs +279 -92
- package/dist/index.mjs.map +1 -1
- package/package.json +3 -3
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/provider.tsx","../src/context.ts","../src/flopay-checkout.tsx","../src/elements.tsx","../src/split-card-form.tsx","../src/hooks.ts","../src/checkout-form.tsx","../src/paypal-button.tsx"],"sourcesContent":["// Provider\nexport { FloPayProvider } from './provider.js';\nexport type { FloPayProviderProps } from './provider.js';\n\n// FloPayCheckout (recommended — all-in-one checkout)\nexport { FloPayCheckout } from './flopay-checkout.js';\nexport type { FloPayCheckoutProps } from './flopay-checkout.js';\n\n// Hooks\nexport { useFloPay, useElements, useCheckout } from './hooks.js';\nexport type { CheckoutState } from './hooks.js';\n\n// Element Components\nexport {\n PaymentElement,\n CardElement,\n CardNumberElement,\n CardExpiryElement,\n CardCvcElement,\n AddressElement,\n} from './elements.js';\nexport type { ElementComponentProps } from './elements.js';\n\n// CheckoutForm\nexport { CheckoutForm } from './checkout-form.js';\nexport type { CheckoutFormProps, CheckoutFormRef } from './checkout-form.js';\n\n// SplitCardForm\nexport { SplitCardForm } from './split-card-form.js';\nexport type { SplitCardFormProps, SplitCardFormRef } from './split-card-form.js';\n\n// PayPalButton\nexport { PayPalButton } from './paypal-button.js';\nexport type { PayPalButtonProps } from './paypal-button.js';\n","import React, { useEffect, useState, useMemo } from 'react';\nimport type { FloPay, FloPayElements } from '@flopay/js';\nimport type { FloPayAppearance } from '@flopay/shared';\nimport { resolveBillingApiUrl } from '@flopay/shared';\nimport { FloPayContext } from './context.js';\n\n/** Props for the `FloPayProvider` component. */\nexport interface FloPayProviderProps {\n /** A `FloPay` instance or a promise that resolves to one (from `loadFloPay()`). */\n flopay: Promise<FloPay> | FloPay;\n /** 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 FloPayAppearance,\n PaymentResult,\n CheckoutSession,\n CheckoutMode,\n NormalizedCheckoutSession,\n} from '@flopay/shared';\nimport { FloPayError, resolveBillingApiUrl, buildCheckoutDisplayData } from '@flopay/shared';\nimport { FloPayProvider } from './provider.js';\nimport { SplitCardForm } from './split-card-form.js';\nimport { CheckoutContext } from './context.js';\n\n/** Props for the all-in-one `FloPayCheckout` wrapper. */\nexport interface FloPayCheckoutProps {\n /** The checkout session ID (UUID from billing API). */\n sessionId: string;\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 publishable key, used only if the session response\n * doesn't include `gatewayData.publishableKey`.\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 /** 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 /** 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,\n billingApiUrl,\n appearance,\n locale,\n fallbackPublishableKey,\n loading: loadingNode,\n error: errorNode,\n onComplete,\n onError,\n showPayPal = true,\n showApplePay = true,\n showGooglePay = true,\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 [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 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 onSessionCompletedRef = useRef(onSessionCompleted);\n onSessionCompletedRef.current = onSessionCompleted;\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,\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 },\n [resolvedBillingUrl, sessionId],\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 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 return false;\n }\n onCompleteRef.current?.({ status: 'succeeded' });\n return true;\n }\n\n return false;\n },\n [resolvedBillingUrl, sessionId],\n );\n\n // ── Fetch session + initialize ──\n\n useEffect(() => {\n let cancelled = false;\n setIsLoading(true);\n setLoadError(null);\n\n async function init() {\n try {\n const api = new PaymentAPI(resolvedBillingUrl);\n const result = await api.getUnifiedCheckoutSession(sessionId);\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 // Check if session is already completed\n if (sess.status === 'complete') {\n setIsLoading(false);\n onSessionCompletedRef.current?.(sess.successUrl ?? '');\n return;\n }\n\n // Resolve effective checkout mode\n const effectiveMode =\n checkoutModeProp ?? sess.checkoutMode ?? 'full';\n setCurrentMode(effectiveMode);\n\n // Detect PayPal redirect return — if URL has payment_intent params,\n // skip auto checkout and let the PayPal resume handler in SplitCardForm\n // pick up the redirect. Otherwise we'd loop: auto → paypal_redirect →\n // return → auto → paypal_redirect → ...\n const hasPayPalRedirectParams =\n typeof window !== 'undefined' &&\n new URLSearchParams(window.location.search).has('payment_intent');\n\n // Auto mode: attempt payment before loading Stripe\n if (\n effectiveMode === 'auto' &&\n !autoCheckoutAttempted.current &&\n !hasPayPalRedirectParams\n ) {\n autoCheckoutAttempted.current = true;\n\n // Start Stripe init in parallel (needed if auto fails)\n const stripeInitPromise = initStripe(result, sess);\n\n try {\n const redirectResult = await processPaymentForMode(sess);\n\n if (!redirectResult) {\n // Auto checkout succeeded — no need for Stripe\n if (!cancelled) setIsLoading(false);\n return;\n }\n\n // PayPal or 3DS redirect required — wait for Stripe, then handle\n if (cancelled) return;\n await stripeInitPromise;\n\n const handled = await handleRedirectResult(redirectResult, sess, { attempt3DS: true });\n if (!cancelled) {\n if (!handled) {\n setCurrentMode('full');\n }\n setIsLoading(false);\n }\n return;\n } catch {\n // Auto failed — fall back to full mode\n if (cancelled) return;\n setCurrentMode('full');\n // Await the parallel Stripe init\n await stripeInitPromise;\n if (!cancelled) setIsLoading(false);\n return;\n }\n }\n\n // Full and confirm modes: initialize Stripe\n await initStripe(result, sess);\n if (!cancelled) setIsLoading(false);\n } catch (err) {\n if (cancelled) return;\n const floPayErr =\n err instanceof FloPayError\n ? err\n : new FloPayError(\n err instanceof Error\n ? err.message\n : 'Failed to initialize checkout',\n 'api_error',\n );\n setLoadError(floPayErr);\n setIsLoading(false);\n }\n }\n\n async function initStripe(\n result: NormalizedCheckoutSession,\n _sess: CheckoutSession,\n ) {\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 // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [sessionId, resolvedBillingUrl, fallbackPublishableKey, locale, checkoutModeProp]);\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 setCurrentMode('full');\n } finally {\n setConfirmProcessing(false);\n }\n }, [confirmProcessing, session, processPaymentForMode, handleRedirectResult, onError]);\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\n // ── Loading state ──\n if (isLoading) {\n return (\n <>\n {loadingNode ?? (\n <div\n style={{\n display: 'flex',\n justifyContent: 'center',\n padding: 32,\n }}\n >\n <div\n style={{\n width: 24,\n height: 24,\n border: '2px solid #e5e7eb',\n borderTopColor: '#6b7280',\n borderRadius: '50%',\n animation: 'spin 0.6s linear infinite',\n }}\n />\n <style>{`@keyframes spin { to { transform: rotate(360deg); } }`}</style>\n </div>\n )}\n </>\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 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={sessionId}\n billingApiUrl={resolvedBillingUrl}\n session={session}\n >\n {children}\n </SessionInjector>\n ) : (\n <SplitCardForm\n sessionId={sessionId}\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 showPayPal={showPayPal}\n showApplePay={showApplePay}\n showGooglePay={showGooglePay}\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","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 PaymentResult,\n TokenizedBody,\n} 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';\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\n// ─── Processing Overlay with animated states ─────────────────────────────────\n\ntype OverlayStatus = 'processing' | 'success' | 'error';\n\nfunction ProcessingOverlay({ status }: { status: OverlayStatus }) {\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 <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 /**\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 /** 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}\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}: {\n sessionId: string;\n email?: string;\n billingApiUrl: string;\n onTokenizedBody: (body: TokenizedBody) => void;\n onErrorChange?: (error: string | null) => void;\n isProcessing?: boolean;\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 onErrorChange?.('PayPal payment was declined. Please try again.');\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 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 }, [stripe, onTokenizedBody, onErrorChange]);\n\n // PayPal confirm handler — called by ExpressCheckoutElement onConfirm\n const handlePayPalConfirm = useCallback(async (_event: StripeExpressCheckoutElementConfirmEvent) => {\n if (!stripe || !elements) return;\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 onErrorChange?.(confirmError.message ?? 'PayPal payment failed.');\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]);\n\n return (\n <>\n <div style={{ marginBottom: ready ? '0.5rem' : 0 }}>\n <ExpressCheckoutElement\n onReady={() => setReady(true)}\n onLoadError={() => { /* PayPal not available — hide gracefully */ }}\n onConfirm={handlePayPalConfirm}\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}: {\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}) {\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\n const handleWalletConfirm = useCallback(\n async (_event: StripeExpressCheckoutElementConfirmEvent) => {\n if (!stripe || !elements) return;\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 onErrorChange?.(confirmError.message ?? 'Wallet payment failed.');\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],\n );\n\n return (\n <>\n <div style={{ marginBottom: ready ? '0.5rem' : 0 }}>\n <ExpressCheckoutElement\n onReady={() => setReady(true)}\n onLoadError={() => { /* wallets not available on this device — hide */ }}\n onConfirm={handleWalletConfirm}\n options={{\n buttonType: { applePay: 'plain', googlePay: 'plain' } as Record<string, string>,\n paymentMethods: {\n applePay: showApplePay ? 'auto' : 'never',\n googlePay: showGooglePay ? 'auto' : 'never',\n paypal: 'never',\n link: 'never',\n },\n layout: { 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 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 totalAmount = 0,\n currency = 'usd',\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 [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 const isSubmitting = externalProcessing ?? processing;\n const isSelfContained = !onTokenizedBody;\n const baseUrl = resolvedBillingApiUrl.replace(/\\/+$/, '');\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 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 // ── 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': userId ?? '',\n },\n body: JSON.stringify({\n sessionId,\n tokenizedData: tokenizedBody,\n accountData: {\n userId: userId ?? '',\n email: email ?? '',\n firstName: firstName ?? fullName.trim().split(/\\s+/)[0] ?? '',\n lastName: lastName ?? fullName.trim().split(/\\s+/).slice(1).join(' ') ?? '',\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 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 updateError(confirmError.message ?? 'PayPal payment failed.');\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 updateError((json?.message as string) ?? 'Payment failed. Please try again.');\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, userId, email, firstName, lastName, fullName, chv, flopay, onComplete, onError, updateError],\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 } 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]);\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 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 // 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)\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 setOverlayStatus('error');\n updateError(confirmResult.error.message);\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, email, baseUrl, isSelfContained, dispatchTokenizedBody, onError, updateError],\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 return (\n <form onSubmit={handleSubmit} className={className} style={{ position: 'relative' }}>\n {overlayStatus && <ProcessingOverlay status={overlayStatus} />}\n\n {/* Wallet buttons (Apple Pay / Google Pay) — own Stripe Elements instance\n with paymentMethodCreation: 'manual', matching checkout's ExpressCheckoutElement. */}\n {showWallets && stripeInstance && (\n <StripeElements stripe={stripeInstance} options={walletOptions}>\n <WalletButtonInner\n sessionId={sessionId}\n email={email}\n billingApiUrl={resolvedBillingApiUrl}\n showApplePay={showApplePay}\n showGooglePay={showGooglePay}\n onTokenizedBody={dispatchTokenizedBody}\n onErrorChange={updateError}\n />\n </StripeElements>\n )}\n\n {/* PayPal — own Stripe Elements instance (no paymentMethodCreation).\n Matches checkout/StripeCardForm which renders PayPal in separate <Elements>.\n Note: PayPal will only render if enabled on the Stripe account. */}\n {showPayPal && stripeInstance && (\n <StripeElements stripe={stripeInstance} options={paypalOptions}>\n <PayPalButtonInner\n sessionId={sessionId}\n email={email}\n billingApiUrl={resolvedBillingApiUrl}\n onTokenizedBody={dispatchTokenizedBody}\n onErrorChange={updateError}\n isProcessing={isSubmitting}\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 <div style={{ backgroundColor: '#EDEDFF', borderRadius: '8px', padding: '1rem' }}>\n <div style={{ textAlign: 'center', fontWeight: 600, fontSize: '1.1rem', padding: '0.5rem 0', color: '#262833' }}>\n Secure card checkout\n </div>\n\n {/* Card Number */}\n <div style={{\n backgroundColor: 'white', border: '1px solid #A4A4FF',\n borderTopLeftRadius: '8px', borderTopRightRadius: '8px', padding: '10px',\n }}>\n <CardNumberElement onReady={() => setFormReady(true)} />\n </div>\n\n {/* Expiry + CVC */}\n <div style={{ display: 'flex' }}>\n <div style={{\n flex: 1, backgroundColor: 'white', border: '1px solid #A4A4FF',\n borderTop: 'none', borderRight: 'none',\n borderBottomLeftRadius: '8px', padding: '10px',\n }}>\n <CardExpiryElement />\n </div>\n <div style={{\n flex: 1, backgroundColor: 'white', border: '1px solid #A4A4FF',\n borderTop: 'none', borderBottomRightRadius: '8px', padding: '10px',\n }}>\n <CardCvcElement />\n </div>\n </div>\n\n {/* Full Name */}\n <div style={{\n backgroundColor: 'white', border: '1px solid #A4A4FF',\n borderRadius: '8px', marginTop: '0.5rem', padding: '10px',\n }}>\n <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',\n fontSize: '16px', fontFamily: 'Poppins, sans-serif', color: '#262833',\n }}\n />\n </div>\n\n {displayError && (\n <div role=\"alert\" data-testid=\"flopay-error\" style={{ color: 'red', margin: '0.75rem 0', fontSize: '0.9rem' }}>\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', fontSize: '1rem', fontWeight: 600,\n cursor: !formReady || isSubmitting ? 'not-allowed' : 'pointer',\n opacity: !formReady || isSubmitting ? 0.5 : 1,\n }}\n >\n {isSubmitting ? 'PROCESSING...' : submitLabel}\n </button>\n )}\n\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 </div>\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 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';\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 /**\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 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 // ── 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 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 } 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],\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 } 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]);\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 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],\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;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,IAAAA,gBAAoD;AAGpD,oBAAqC;;;ACHrC,mBAA8B;AAmBvB,IAAM,oBAAgB,4BAAkC;AAAA,EAC7D,QAAQ;AAAA,EACR,UAAU;AAAA,EACV,eAAe;AACjB,CAAC;AAEM,IAAM,sBAAkB,4BAAoC;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,QAAI;AAAA,IAC1B,sBAAsB,UAAU,OAAO;AAAA,EACzC;AACA,QAAM,CAAC,UAAU,WAAW,QAAI,wBAAgC,IAAI;AAGpE,+BAAU,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,kBA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,6CAAC,SAAI,OAAO,QAAQ,CAAC,IAAI,EAAE,SAAS,OAAO,GACzC;AAAA,MAAC;AAAA;AAAA,QACC,MAAK;AAAA,QACL,SAAS;AAAA,QACT,UAAU,cAAc;AAAA,QACxB,OAAO;AAAA,UACL,OAAO;AAAA,UACP,QAAQ;AAAA,UACR,iBAAiB;AAAA,UACjB,OAAO;AAAA,UACP,QAAQ;AAAA,UACR,cAAc;AAAA,UACd,UAAU;AAAA,UACV,YAAY;AAAA,UACZ,QAAQ,cAAc,eAAe,gBAAgB;AAAA,UACrD,SAAS,cAAc,eAAe,MAAM;AAAA,QAC9C;AAAA,QACA,KAAK,MAAM,SAAS,IAAI;AAAA,QAEvB,uBAAa,kBAAkB;AAAA;AAAA,IAClC,GACF;AAAA,KAEE,cAAc,iBACd,6CAAC,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,uDAAC,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":["import_react","import_react","import_shared","import_react","import_jsx_runtime","import_react","import_react","import_shared","import_shared","import_jsx_runtime","SplitCardForm","useStripeRaw","useStripeElements","stripeInstance","StripeElements","import_jsx_runtime","React","import_shared","import_react","import_jsx_runtime","WALLET_RESUME_KEY","CheckoutForm","import_shared","import_react","import_jsx_runtime"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/provider.tsx","../src/context.ts","../src/flopay-checkout.tsx","../src/elements.tsx","../src/split-card-form.tsx","../src/hooks.ts","../src/checkout-form.tsx","../src/paypal-button.tsx"],"sourcesContent":["// Provider\nexport { FloPayProvider } from './provider.js';\nexport type { FloPayProviderProps } from './provider.js';\n\n// FloPayCheckout (recommended — all-in-one checkout)\nexport { FloPayCheckout } from './flopay-checkout.js';\nexport type { FloPayCheckoutProps } from './flopay-checkout.js';\n\n// Hooks\nexport { useFloPay, useElements, useCheckout } from './hooks.js';\nexport type { CheckoutState } from './hooks.js';\n\n// Element Components\nexport {\n PaymentElement,\n CardElement,\n CardNumberElement,\n CardExpiryElement,\n CardCvcElement,\n AddressElement,\n} from './elements.js';\nexport type { ElementComponentProps } from './elements.js';\n\n// CheckoutForm\nexport { CheckoutForm } from './checkout-form.js';\nexport type { CheckoutFormProps, CheckoutFormRef } from './checkout-form.js';\n\n// SplitCardForm\nexport { SplitCardForm } from './split-card-form.js';\nexport type { SplitCardFormProps, SplitCardFormRef } from './split-card-form.js';\n\n// PayPalButton\nexport { PayPalButton } from './paypal-button.js';\nexport type { PayPalButtonProps } from './paypal-button.js';\n","import React, { useEffect, useState, useMemo } from 'react';\nimport type { FloPay, FloPayElements } from '@flopay/js';\nimport type { FloPayAppearance } from '@flopay/shared';\nimport { resolveBillingApiUrl } from '@flopay/shared';\nimport { FloPayContext } from './context.js';\n\n/** Props for the `FloPayProvider` component. */\nexport interface FloPayProviderProps {\n /** A `FloPay` instance or a promise that resolves to one (from `loadFloPay()`). */\n flopay: Promise<FloPay> | FloPay;\n /** 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 FloPayAppearance,\n PaymentResult,\n CheckoutSession,\n CheckoutMode,\n NormalizedCheckoutSession,\n} from '@flopay/shared';\nimport { FloPayError, resolveBillingApiUrl, buildCheckoutDisplayData } from '@flopay/shared';\nimport { FloPayProvider } from './provider.js';\nimport { SplitCardForm } from './split-card-form.js';\nimport { CheckoutContext } from './context.js';\n\n/** Props for the all-in-one `FloPayCheckout` wrapper. */\nexport interface FloPayCheckoutProps {\n /** The checkout session ID (UUID from billing API). */\n sessionId: string;\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 publishable key, used only if the session response\n * doesn't include `gatewayData.publishableKey`.\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 /** 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 /** 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,\n billingApiUrl,\n appearance,\n locale,\n fallbackPublishableKey,\n loading: loadingNode,\n error: errorNode,\n onComplete,\n onError,\n showPayPal = true,\n showApplePay = true,\n showGooglePay = true,\n layout,\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 [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 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 onSessionCompletedRef = useRef(onSessionCompleted);\n onSessionCompletedRef.current = onSessionCompleted;\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,\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 },\n [resolvedBillingUrl, sessionId],\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 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 return false;\n }\n onCompleteRef.current?.({ status: 'succeeded' });\n return true;\n }\n\n return false;\n },\n [resolvedBillingUrl, sessionId],\n );\n\n // ── Fetch session + initialize ──\n\n useEffect(() => {\n let cancelled = false;\n setIsLoading(true);\n setLoadError(null);\n\n async function init() {\n try {\n const api = new PaymentAPI(resolvedBillingUrl);\n const result = await api.getUnifiedCheckoutSession(sessionId);\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 // Check if session is already completed\n if (sess.status === 'complete') {\n setIsLoading(false);\n onSessionCompletedRef.current?.(sess.successUrl ?? '');\n return;\n }\n\n // Resolve effective checkout mode\n const effectiveMode =\n checkoutModeProp ?? sess.checkoutMode ?? 'full';\n setCurrentMode(effectiveMode);\n\n // Detect PayPal redirect return — if URL has payment_intent params,\n // skip auto checkout and let the PayPal resume handler in SplitCardForm\n // pick up the redirect. Otherwise we'd loop: auto → paypal_redirect →\n // return → auto → paypal_redirect → ...\n const hasPayPalRedirectParams =\n typeof window !== 'undefined' &&\n new URLSearchParams(window.location.search).has('payment_intent');\n\n // Auto mode: attempt payment before loading Stripe\n if (\n effectiveMode === 'auto' &&\n !autoCheckoutAttempted.current &&\n !hasPayPalRedirectParams\n ) {\n autoCheckoutAttempted.current = true;\n\n // Start Stripe init in parallel (needed if auto fails)\n const stripeInitPromise = initStripe(result, sess);\n\n try {\n const redirectResult = await processPaymentForMode(sess);\n\n if (!redirectResult) {\n // Auto checkout succeeded — no need for Stripe\n if (!cancelled) setIsLoading(false);\n return;\n }\n\n // PayPal or 3DS redirect required — wait for Stripe, then handle\n if (cancelled) return;\n await stripeInitPromise;\n\n const handled = await handleRedirectResult(redirectResult, sess, { attempt3DS: true });\n if (!cancelled) {\n if (!handled) {\n setCurrentMode('full');\n }\n setIsLoading(false);\n }\n return;\n } catch {\n // Auto failed — fall back to full mode\n if (cancelled) return;\n setCurrentMode('full');\n // Await the parallel Stripe init\n await stripeInitPromise;\n if (!cancelled) setIsLoading(false);\n return;\n }\n }\n\n // Full and confirm modes: initialize Stripe\n await initStripe(result, sess);\n if (!cancelled) setIsLoading(false);\n } catch (err) {\n if (cancelled) return;\n const floPayErr =\n err instanceof FloPayError\n ? err\n : new FloPayError(\n err instanceof Error\n ? err.message\n : 'Failed to initialize checkout',\n 'api_error',\n );\n setLoadError(floPayErr);\n setIsLoading(false);\n }\n }\n\n async function initStripe(\n result: NormalizedCheckoutSession,\n _sess: CheckoutSession,\n ) {\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 // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [sessionId, resolvedBillingUrl, fallbackPublishableKey, locale, checkoutModeProp]);\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 setCurrentMode('full');\n } finally {\n setConfirmProcessing(false);\n }\n }, [confirmProcessing, session, processPaymentForMode, handleRedirectResult, onError]);\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\n // ── Loading state ──\n if (isLoading) {\n return (\n <>\n {loadingNode ?? (\n <div\n style={{\n display: 'flex',\n justifyContent: 'center',\n padding: 32,\n }}\n >\n <div\n style={{\n width: 24,\n height: 24,\n border: '2px solid #e5e7eb',\n borderTopColor: '#6b7280',\n borderRadius: '50%',\n animation: 'spin 0.6s linear infinite',\n }}\n />\n <style>{`@keyframes spin { to { transform: rotate(360deg); } }`}</style>\n </div>\n )}\n </>\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 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={sessionId}\n billingApiUrl={resolvedBillingUrl}\n session={session}\n >\n {children}\n </SessionInjector>\n ) : (\n <SplitCardForm\n sessionId={sessionId}\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 showPayPal={showPayPal}\n showApplePay={showApplePay}\n showGooglePay={showGooglePay}\n layout={layout}\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","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 PaymentResult,\n TokenizedBody,\n} 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';\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\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 === '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 @keyframes flopay-expand { 0% { opacity: 0; clip-path: inset(0 0 100% 0); transform: translateY(-8px); } 100% { opacity: 1; clip-path: inset(0 0 0 0); transform: translateY(0); } }\n @keyframes flopay-fade-in { 0% { opacity: 0; } 100% { opacity: 1; } }\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 /**\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 /** 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}\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}: {\n sessionId: string;\n email?: string;\n billingApiUrl: string;\n onTokenizedBody: (body: TokenizedBody) => void;\n onErrorChange?: (error: string | null) => void;\n isProcessing?: boolean;\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 onErrorChange?.('PayPal payment was declined. Please try again.');\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 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 }, [stripe, onTokenizedBody, onErrorChange]);\n\n // PayPal confirm handler — called by ExpressCheckoutElement onConfirm\n const handlePayPalConfirm = useCallback(async (_event: StripeExpressCheckoutElementConfirmEvent) => {\n if (!stripe || !elements) return;\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 onErrorChange?.(confirmError.message ?? 'PayPal payment failed.');\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]);\n\n return (\n <>\n <div style={{ marginBottom: ready ? '0.5rem' : 0 }}>\n <ExpressCheckoutElement\n onReady={() => setReady(true)}\n onLoadError={() => { /* PayPal not available — hide gracefully */ }}\n onConfirm={handlePayPalConfirm}\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}: {\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}) {\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\n const handleWalletConfirm = useCallback(\n async (_event: StripeExpressCheckoutElementConfirmEvent) => {\n if (!stripe || !elements) return;\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 onErrorChange?.(confirmError.message ?? 'Wallet payment failed.');\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],\n );\n\n return (\n <>\n <div style={{ marginBottom: ready ? '0.5rem' : 0 }}>\n <ExpressCheckoutElement\n onReady={() => setReady(true)}\n onLoadError={() => { /* wallets not available on this device — hide */ }}\n onConfirm={handleWalletConfirm}\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: { 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 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 totalAmount = 0,\n currency = 'usd',\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 [showCardForm, setShowCardForm] = useState(false);\n const [is3DSActive, setIs3DSActive] = useState(false);\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 const isSubmitting = externalProcessing ?? processing;\n const isSelfContained = !onTokenizedBody;\n const baseUrl = resolvedBillingApiUrl.replace(/\\/+$/, '');\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 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 // ── 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': userId ?? '',\n },\n body: JSON.stringify({\n sessionId,\n tokenizedData: tokenizedBody,\n accountData: {\n userId: userId ?? '',\n email: email ?? '',\n firstName: firstName ?? fullName.trim().split(/\\s+/)[0] ?? '',\n lastName: lastName ?? fullName.trim().split(/\\s+/).slice(1).join(' ') ?? '',\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 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 updateError(confirmError.message ?? 'PayPal payment failed.');\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 updateError((json?.message as string) ?? 'Payment failed. Please try again.');\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, userId, email, firstName, lastName, fullName, chv, flopay, onComplete, onError, updateError],\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 } 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]);\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 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 // 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)\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 setOverlayStatus('error');\n updateError(confirmResult.error.message);\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, email, baseUrl, isSelfContained, dispatchTokenizedBody, onError, updateError],\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 cardBorderColor = isButtons ? '#e5e7eb' : '#A4A4FF';\n const cardBg = isButtons ? 'white' : '#EDEDFF';\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 && showCardForm ? {\n animation: 'flopay-expand 0.4s cubic-bezier(0.16,1,0.3,1) both',\n } : {}),\n }}>\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={() => setShowCardForm(false)}\n style={{\n display: 'inline-flex', alignItems: 'center', gap: '0.5rem',\n background: 'none', border: 'none', cursor: 'pointer',\n color: '#4b5563', fontSize: '0.85rem', fontWeight: 500,\n padding: 0, transition: 'color 0.15s', flexShrink: 0,\n }}\n onMouseOver={(e) => { e.currentTarget.style.color = '#1f2937'; }}\n onMouseOut={(e) => { e.currentTarget.style.color = '#4b5563'; }}\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 }}>\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 Go back\n </button>\n <div style={{ flex: 1, textAlign: 'center', fontWeight: 600, fontSize: '1.05rem', color: '#262833', paddingRight: 80 }}>\n Secure card checkout\n </div>\n </div>\n )}\n\n {/* Title (default layout only) */}\n {!isButtons && (\n <div style={{ textAlign: 'center', fontWeight: 600, fontSize: '1.1rem', padding: '0.5rem 0', color: '#262833' }}>\n Secure card checkout\n </div>\n )}\n\n {/* Card Number */}\n <div style={{\n backgroundColor: 'white', border: `1px solid ${cardBorderColor}`,\n borderTopLeftRadius: '8px', borderTopRightRadius: '8px', padding: '10px',\n }}>\n <CardNumberElement onReady={() => setFormReady(true)} />\n </div>\n\n {/* Expiry + CVC */}\n <div style={{ display: 'flex' }}>\n <div style={{\n flex: 1, backgroundColor: 'white', border: `1px solid ${cardBorderColor}`,\n borderTop: 'none', borderRight: 'none',\n borderBottomLeftRadius: '8px', padding: '10px',\n }}>\n <CardExpiryElement />\n </div>\n <div style={{\n flex: 1, backgroundColor: 'white', border: `1px solid ${cardBorderColor}`,\n borderTop: 'none', borderBottomRightRadius: '8px', padding: '10px',\n }}>\n <CardCvcElement />\n </div>\n </div>\n\n {/* Full Name */}\n <div style={{\n backgroundColor: 'white', border: `1px solid ${cardBorderColor}`,\n borderRadius: '8px', marginTop: '0.5rem', padding: '10px',\n }}>\n <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',\n fontSize: '16px', fontFamily: 'Poppins, sans-serif', color: '#262833',\n }}\n />\n </div>\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 }}>\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', fontSize: '1rem', fontWeight: 600,\n cursor: !formReady || isSubmitting ? 'not-allowed' : 'pointer',\n opacity: !formReady || isSubmitting ? 0.5 : 1,\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 return (\n <form onSubmit={handleSubmit} className={className} style={{ position: 'relative' }}>\n {overlayStatus && <ProcessingOverlay status={overlayStatus} errorMessage={displayError} />}\n\n {/* Payment method buttons — always mounted, hidden via display:none to prevent re-render */}\n <div style={{\n display: showCardForm ? 'none' : 'flex',\n flexDirection: 'column', gap: '0.5rem',\n }}>\n {/* PayPal */}\n {showPayPal && stripeInstance && (\n <StripeElements stripe={stripeInstance} options={paypalOptions}>\n <PayPalButtonInner\n sessionId={sessionId}\n email={email}\n billingApiUrl={resolvedBillingApiUrl}\n onTokenizedBody={dispatchTokenizedBody}\n onErrorChange={updateError}\n isProcessing={isSubmitting}\n />\n </StripeElements>\n )}\n\n {/* Wallets (Apple Pay / Google Pay) */}\n {showWallets && stripeInstance && (\n <StripeElements stripe={stripeInstance} options={walletOptions}>\n <WalletButtonInner\n sessionId={sessionId}\n email={email}\n billingApiUrl={resolvedBillingApiUrl}\n showApplePay={showApplePay}\n showGooglePay={showGooglePay}\n onTokenizedBody={dispatchTokenizedBody}\n onErrorChange={updateError}\n />\n </StripeElements>\n )}\n\n {/* Credit / Debit Card button */}\n <button\n type=\"button\"\n onClick={() => setShowCardForm(true)}\n style={{\n width: '100%', padding: '0.9rem 1rem',\n backgroundColor: 'white', color: '#262833',\n border: '1px solid #d1d5db', borderRadius: '8px',\n fontSize: '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 }}\n onMouseOver={(e) => {\n e.currentTarget.style.borderColor = '#A4A4FF';\n e.currentTarget.style.boxShadow = '0 0 0 1px #A4A4FF, 0 2px 8px rgba(74,73,255,0.08)';\n }}\n onMouseOut={(e) => {\n e.currentTarget.style.borderColor = '#d1d5db';\n e.currentTarget.style.boxShadow = '0 1px 2px rgba(0,0,0,0.04)';\n }}\n onMouseDown={(e) => { e.currentTarget.style.transform = 'scale(0.985)'; }}\n onMouseUp={(e) => { e.currentTarget.style.transform = 'scale(1)'; }}\n >\n <svg width=\"20\" height=\"20\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.5\" strokeLinecap=\"round\" strokeLinejoin=\"round\">\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 width=\"16\" height=\"16\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"#9ca3af\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\" style={{ marginLeft: 'auto' }}>\n <path d=\"M9 18l6-6-6-6\" />\n </svg>\n </button>\n\n {displayError && !showCardForm && (\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 }}>\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 — shown when expanded */}\n {showCardForm && cardFormBlock}\n </form>\n );\n }\n\n // ── Default layout ──\n return (\n <form onSubmit={handleSubmit} className={className} style={{ position: 'relative' }}>\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={email}\n billingApiUrl={resolvedBillingApiUrl}\n showApplePay={showApplePay}\n showGooglePay={showGooglePay}\n onTokenizedBody={dispatchTokenizedBody}\n onErrorChange={updateError}\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={email}\n billingApiUrl={resolvedBillingApiUrl}\n onTokenizedBody={dispatchTokenizedBody}\n onErrorChange={updateError}\n isProcessing={isSubmitting}\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 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';\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 /**\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 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 // ── 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 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 } 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],\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 } 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]);\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 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],\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;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,IAAAA,gBAAoD;AAGpD,oBAAqC;;;ACHrC,mBAA8B;AAmBvB,IAAM,oBAAgB,4BAAkC;AAAA,EAC7D,QAAQ;AAAA,EACR,UAAU;AAAA,EACV,eAAe;AACjB,CAAC;AAEM,IAAM,sBAAkB,4BAAoC;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,QAAI;AAAA,IAC1B,sBAAsB,UAAU,OAAO;AAAA,EACzC;AACA,QAAM,CAAC,UAAU,WAAW,QAAI,wBAAgC,IAAI;AAGpE,+BAAU,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,U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B;AAAA,UACjB,OAAO;AAAA,UACP,QAAQ;AAAA,UACR,cAAc;AAAA,UACd,UAAU;AAAA,UACV,YAAY;AAAA,UACZ,QAAQ,cAAc,eAAe,gBAAgB;AAAA,UACrD,SAAS,cAAc,eAAe,MAAM;AAAA,QAC9C;AAAA,QACA,KAAK,MAAM,SAAS,IAAI;AAAA,QAEvB,uBAAa,kBAAkB;AAAA;AAAA,IAClC,GACF;AAAA,KAEE,cAAc,iBACd,6CAAC,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,uDAAC,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":["import_react","import_react","import_shared","import_react","import_jsx_runtime","import_react","import_react","import_shared","import_shared","import_jsx_runtime","SplitCardForm","useStripeRaw","useStripeElements","stripeInstance","StripeElements","import_jsx_runtime","React","import_shared","import_react","import_jsx_runtime","WALLET_RESUME_KEY","CheckoutForm","import_shared","import_react","import_jsx_runtime"]}
|