import { o as createProfileTranslationAdapter, s as profileDomain, v as useAddressFieldsApiOptional, y as useAddressAutocompleteApi } from "./FluidProvider-hztxEA9v.mjs";
import { a as useActiveLocale, r as useDomainDict } from "./static-dict-adapter-BlNdg7r8.mjs";
import { t as createTranslationContext } from "./translation-api-context-factory-oSEnOBmb.mjs";
import { $ as DialogClose, B as Label, Cn as Button, D as SelectTrigger, E as SelectItem, H as DropdownMenuContent, In as useZodForm, Ln as cn, O as SelectValue, Q as Dialog, T as SelectContent, U as DropdownMenuItem, V as DropdownMenu, Z as DropdownMenuTrigger, a as Textarea, et as DialogContent, j as Input, nt as DialogFooter, ot as DialogTitle, q as DropdownMenuSeparator, rt as DialogHeader, w as Select } from "./src-v1U7mjgR.mjs";
import { a as paymentDescriptorLabel, d as normalizeCardBrand, i as normalizePaymentDescriptor, o as resolvePaymentLogo, s as resolvePaymentMethodDisplay, t as isCardPaymentDescriptor } from "./display-nScoMx87.mjs";
import { createContext, useCallback, useContext, useEffect, useEffectEvent, useId, useMemo, useRef, useState } from "react";
import "@tanstack/react-query";
import { Fragment as Fragment$1, jsx, jsxs } from "react/jsx-runtime";
import { z } from "zod";
import { Info, Lock, Trash2 } from "lucide-react";
import { Controller, useController, useWatch } from "react-hook-form";
import { Combobox } from "@fluid-app/ui-components/components/Combobox";
import { PhoneInput } from "@fluid-app/ui-components/components/PhoneInput";
//#region ../../profile/core/src/translation-api-context.ts
const { Provider: ProfileProvider, useTranslation } = createTranslationContext("Profile");
const ProfileTranslationProvider = ProfileProvider;
const useProfileTranslation = useTranslation;
//#endregion
//#region src/providers/ProfileTranslationBridge.tsx
function ProfileTranslationBridge({ children }) {
	const { locale } = useActiveLocale();
	const dict = useDomainDict(profileDomain, locale);
	return /* @__PURE__ */ jsx(ProfileTranslationProvider, {
		value: useMemo(() => createProfileTranslationAdapter(locale, dict), [locale, dict]),
		children
	});
}
//#endregion
//#region ../../profile/ui/src/components/ellipses-dropdown.tsx
function EllipsesDropdown({ onDelete, onEdit, onMakeDefault, editLabel, deleteLabel, makeDefaultLabel, disabled = false }) {
	const { t } = useProfileTranslation();
	const resolvedEditLabel = editLabel ?? t("edit");
	const resolvedDeleteLabel = deleteLabel ?? t("delete");
	const resolvedMakeDefaultLabel = makeDefaultLabel ?? t("make_default");
	if (disabled) return /* @__PURE__ */ jsx(Button, {
		variant: "ghost",
		disabled: true,
		children: /* @__PURE__ */ jsx("svg", {
			xmlns: "http://www.w3.org/2000/svg",
			viewBox: "0 0 128 512",
			className: "fill-muted-foreground h-4 w-1",
			children: /* @__PURE__ */ jsx("path", { d: "M64 360a56 56 0 1 0 0 112 56 56 0 1 0 0-112zm0-160a56 56 0 1 0 0 112 56 56 0 1 0 0-112zM120 96A56 56 0 1 0 8 96a56 56 0 1 0 112 0z" })
		})
	});
	return /* @__PURE__ */ jsxs(DropdownMenu, { children: [/* @__PURE__ */ jsx(DropdownMenuTrigger, {
		asChild: true,
		children: /* @__PURE__ */ jsx(Button, {
			variant: "ghost",
			children: /* @__PURE__ */ jsx("svg", {
				xmlns: "http://www.w3.org/2000/svg",
				viewBox: "0 0 128 512",
				className: "fill-muted-foreground h-4 w-1",
				children: /* @__PURE__ */ jsx("path", { d: "M64 360a56 56 0 1 0 0 112 56 56 0 1 0 0-112zm0-160a56 56 0 1 0 0 112 56 56 0 1 0 0-112zM120 96A56 56 0 1 0 8 96a56 56 0 1 0 112 0z" })
			})
		})
	}), /* @__PURE__ */ jsxs(DropdownMenuContent, {
		className: "text-foreground min-w-28 space-y-1 text-sm",
		children: [
			onEdit && /* @__PURE__ */ jsxs(Fragment$1, { children: [/* @__PURE__ */ jsxs(DropdownMenuItem, {
				className: "hover:bg-muted flex cursor-pointer flex-row items-center gap-x-2 rounded px-2",
				onClick: (e) => {
					e.stopPropagation();
					onEdit();
				},
				children: [/* @__PURE__ */ jsx("svg", {
					xmlns: "http://www.w3.org/2000/svg",
					fill: "none",
					viewBox: "0 0 24 24",
					strokeWidth: 1.5,
					stroke: "currentColor",
					className: "size-3.5 flex-shrink-0",
					children: /* @__PURE__ */ jsx("path", {
						strokeLinecap: "round",
						strokeLinejoin: "round",
						d: "m16.862 4.487 1.687-1.688a1.875 1.875 0 1 1 2.652 2.652L10.582 16.07a4.5 4.5 0 0 1-1.897 1.13L6 18l.8-2.685a4.5 4.5 0 0 1 1.13-1.897l8.932-8.931Zm0 0L19.5 7.125M18 14v4.75A2.25 2.25 0 0 1 15.75 21H5.25A2.25 2.25 0 0 1 3 18.75V8.25A2.25 2.25 0 0 1 5.25 6H10"
					})
				}), /* @__PURE__ */ jsx("span", { children: resolvedEditLabel })]
			}), (onMakeDefault || onDelete) && /* @__PURE__ */ jsx(DropdownMenuSeparator, {})] }),
			onMakeDefault && /* @__PURE__ */ jsxs(Fragment$1, { children: [/* @__PURE__ */ jsxs(DropdownMenuItem, {
				className: "hover:bg-muted flex cursor-pointer flex-row items-center gap-x-2 rounded px-2",
				onClick: (e) => {
					e.stopPropagation();
					onMakeDefault();
				},
				children: [/* @__PURE__ */ jsx("svg", {
					xmlns: "http://www.w3.org/2000/svg",
					fill: "none",
					viewBox: "0 0 24 24",
					strokeWidth: 1.5,
					stroke: "currentColor",
					className: "size-3.5 flex-shrink-0",
					children: /* @__PURE__ */ jsx("path", {
						strokeLinecap: "round",
						strokeLinejoin: "round",
						d: "m4.5 12.75 6 6 9-13.5"
					})
				}), /* @__PURE__ */ jsx("span", { children: resolvedMakeDefaultLabel })]
			}), onDelete && /* @__PURE__ */ jsx(DropdownMenuSeparator, {})] }),
			onDelete && /* @__PURE__ */ jsxs(DropdownMenuItem, {
				className: "text-destructive hover:bg-destructive/10 flex cursor-pointer flex-row items-center gap-x-2 rounded px-2",
				onClick: (e) => {
					e.stopPropagation();
					onDelete();
				},
				children: [/* @__PURE__ */ jsx("svg", {
					xmlns: "http://www.w3.org/2000/svg",
					fill: "none",
					viewBox: "0 0 24 24",
					strokeWidth: 1.5,
					stroke: "currentColor",
					className: "size-3.5 flex-shrink-0",
					children: /* @__PURE__ */ jsx("path", {
						strokeLinecap: "round",
						strokeLinejoin: "round",
						d: "m14.74 9-.346 9m-4.788 0L9.26 9m9.968-3.21c.342.052.682.107 1.022.166m-1.022-.165L18.16 19.673a2.25 2.25 0 0 1-2.244 2.077H8.084a2.25 2.25 0 0 1-2.244-2.077L4.772 5.79m14.456 0a48.108 48.108 0 0 0-3.478-.397m-12 .562c.34-.059.68-.114 1.022-.165m0 0a48.11 48.11 0 0 1 3.478-.397m7.5 0v-.916c0-1.18-.91-2.164-2.09-2.201a51.964 51.964 0 0 0-3.32 0c-1.18.037-2.09 1.022-2.09 2.201v.916m7.5 0a48.667 48.667 0 0 0-7.5 0"
					})
				}), /* @__PURE__ */ jsx("span", { children: resolvedDeleteLabel })]
			})
		]
	})] });
}
//#endregion
//#region ../../profile/ui/src/components/confirm-action-dialog.tsx
function ConfirmActionDialog({ title, description, onAction, openDialog, setOpenDialog, errorMsg, isLoading, actionText }) {
	const { t } = useProfileTranslation();
	const resolvedActionText = actionText ?? t("delete");
	return /* @__PURE__ */ jsx(Dialog, {
		open: openDialog,
		onOpenChange: setOpenDialog,
		children: /* @__PURE__ */ jsxs(DialogContent, {
			className: "max-w-sm md:w-90",
			children: [
				/* @__PURE__ */ jsx(DialogHeader, {
					className: "flex flex-row justify-between",
					children: /* @__PURE__ */ jsx(DialogTitle, {
						className: "w-full text-left",
						children: title
					})
				}),
				/* @__PURE__ */ jsx("div", {
					className: "space-y-4",
					children: /* @__PURE__ */ jsx("p", {
						className: "text-muted-foreground text-left text-sm",
						children: description
					})
				}),
				errorMsg && /* @__PURE__ */ jsx("p", {
					className: "text-destructive text-sm",
					children: errorMsg
				}),
				/* @__PURE__ */ jsx(DialogFooter, { children: /* @__PURE__ */ jsxs("div", {
					className: "flex w-full flex-row justify-between gap-x-2",
					children: [/* @__PURE__ */ jsx(DialogClose, {
						asChild: true,
						children: /* @__PURE__ */ jsx(Button, {
							variant: "secondary",
							className: "min-w-[70px]",
							onClick: () => setOpenDialog(false),
							children: t("cancel")
						})
					}), /* @__PURE__ */ jsx(Button, {
						type: "button",
						variant: "destructive",
						className: "min-w-[70px]",
						onClick: onAction,
						disabled: isLoading,
						children: isLoading ? /* @__PURE__ */ jsx("div", { className: "border-primary-foreground size-5 animate-spin rounded-full border-4 border-t-4 border-t-transparent" }) : resolvedActionText
					})]
				}) })
			]
		})
	});
}
//#endregion
//#region ../../profile/ui/src/components/form-fields.tsx
function FormTextField$1({ control, name, label, containerClassName, ...props }) {
	const { field, fieldState: { error } } = useController({
		name,
		control
	});
	return /* @__PURE__ */ jsxs("div", {
		className: cn("space-y-1", containerClassName),
		children: [
			label && /* @__PURE__ */ jsx(Label, {
				htmlFor: name,
				className: "mb-1.5 block text-sm font-medium",
				children: label
			}),
			/* @__PURE__ */ jsx(Input, {
				...field,
				...props,
				id: name,
				value: field.value ?? "",
				className: cn(error && "ring-destructive ring-1", props.className)
			}),
			error && /* @__PURE__ */ jsx("p", {
				className: "text-destructive text-sm",
				children: error.message
			})
		]
	});
}
function FormTextareaField({ control, name, label, containerClassName, ...props }) {
	const { field, fieldState: { error } } = useController({
		name,
		control
	});
	return /* @__PURE__ */ jsxs("div", {
		className: cn("space-y-1", containerClassName),
		children: [
			label && /* @__PURE__ */ jsx(Label, {
				htmlFor: name,
				className: "mb-1.5 block text-sm font-medium",
				children: label
			}),
			/* @__PURE__ */ jsx(Textarea, {
				...field,
				...props,
				id: name,
				value: field.value ?? "",
				className: cn(error && "ring-destructive ring-1", props.className)
			}),
			error && /* @__PURE__ */ jsx("p", {
				className: "text-destructive text-sm",
				children: error.message
			})
		]
	});
}
function FormSelectField({ control, name, label, options, placeholder, containerClassName, onChange }) {
	const { field, fieldState: { error } } = useController({
		name,
		control
	});
	return /* @__PURE__ */ jsxs("div", {
		className: cn("space-y-1", containerClassName),
		children: [
			label && /* @__PURE__ */ jsx(Label, {
				htmlFor: name,
				className: "block text-sm font-medium",
				children: label
			}),
			/* @__PURE__ */ jsxs(Select, {
				value: field.value?.toString() ?? "",
				onValueChange: (val) => {
					field.onChange(val);
					onChange?.(val);
				},
				children: [/* @__PURE__ */ jsx(SelectTrigger, {
					id: name,
					className: cn("w-full", error && "ring-destructive ring-1"),
					children: /* @__PURE__ */ jsx(SelectValue, { placeholder })
				}), /* @__PURE__ */ jsx(SelectContent, { children: options?.map((opt) => /* @__PURE__ */ jsx(SelectItem, {
					value: opt.value.toString(),
					children: opt.name
				}, `${opt.name}-${opt.value}`)) })]
			}),
			error && /* @__PURE__ */ jsx("p", {
				className: "text-destructive text-sm",
				children: error.message
			})
		]
	});
}
//#endregion
//#region ../../profile/ui/src/components/user-info-dialog.tsx
function UserInfoDialog({ control, isOpen, onSubmit, handleClose, languageOptions, errorMsg, isSubmitting, email, onChangeEmail, isChangingEmail, pendingEmail }) {
	const { t } = useProfileTranslation();
	const [isEditingEmail, setIsEditingEmail] = useState(false);
	const [newEmail, setNewEmail] = useState("");
	const [emailError, setEmailError] = useState(void 0);
	const handleEmailSubmit = async () => {
		setEmailError(void 0);
		const trimmed = newEmail.trim();
		if (!trimmed) {
			setEmailError(t("please_enter_new_email"));
			return;
		}
		if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(trimmed)) {
			setEmailError(t("please_enter_valid_email"));
			return;
		}
		if (email && trimmed.toLowerCase() === email.toLowerCase()) {
			setEmailError(t("new_email_must_be_different"));
			return;
		}
		try {
			await onChangeEmail?.(trimmed);
			setIsEditingEmail(false);
			setNewEmail("");
		} catch (err) {
			setEmailError(err instanceof Error ? err.message : t("failed_to_initiate_email_change"));
		}
	};
	const handleCancelEmailEdit = () => {
		setIsEditingEmail(false);
		setNewEmail("");
		setEmailError(void 0);
	};
	const handleDialogClose = () => {
		handleCancelEmailEdit();
		handleClose();
	};
	return /* @__PURE__ */ jsx(Dialog, {
		open: isOpen,
		onOpenChange: (open) => !open && handleDialogClose(),
		children: /* @__PURE__ */ jsxs(DialogContent, {
			className: "max-w-sm md:max-w-lg",
			children: [
				/* @__PURE__ */ jsx(DialogHeader, { children: /* @__PURE__ */ jsx(DialogTitle, { children: t("edit_profile") }) }),
				/* @__PURE__ */ jsxs("div", {
					className: "space-y-4",
					children: [
						/* @__PURE__ */ jsx(FormTextField$1, {
							control,
							name: "first_name",
							label: t("first_name")
						}),
						/* @__PURE__ */ jsx(FormTextField$1, {
							control,
							name: "last_name",
							label: t("last_name")
						}),
						/* @__PURE__ */ jsx(FormTextField$1, {
							control,
							name: "phone_number",
							label: t("phone_number"),
							type: "tel"
						}),
						/* @__PURE__ */ jsx(FormTextareaField, {
							control,
							name: "bio",
							label: t("bio"),
							rows: 3,
							placeholder: t("add_a_short_bio")
						}),
						/* @__PURE__ */ jsx(FormSelectField, {
							control,
							name: "language",
							label: t("language"),
							options: languageOptions,
							placeholder: t("select_an_option")
						})
					]
				}),
				email && /* @__PURE__ */ jsxs("div", {
					className: "space-y-2",
					children: [/* @__PURE__ */ jsx("label", {
						className: "text-foreground text-sm font-medium",
						children: t("email")
					}), isEditingEmail ? /* @__PURE__ */ jsxs("div", {
						className: "space-y-2",
						children: [
							/* @__PURE__ */ jsx(Input, {
								type: "email",
								placeholder: t("enter_new_email_placeholder"),
								value: newEmail,
								onChange: (e) => {
									setNewEmail(e.target.value);
									setEmailError(void 0);
								},
								onKeyDown: (e) => {
									if (e.key === "Enter") {
										e.preventDefault();
										handleEmailSubmit();
									}
									if (e.key === "Escape") handleCancelEmailEdit();
								},
								"aria-invalid": !!emailError || void 0,
								autoFocus: true
							}),
							emailError && /* @__PURE__ */ jsx("p", {
								className: "text-destructive text-xs",
								children: emailError
							}),
							/* @__PURE__ */ jsxs("div", {
								className: "bg-muted flex items-start gap-2.5 rounded-md px-3 py-2.5",
								children: [/* @__PURE__ */ jsx(Info, { className: "text-primary mt-0.5 size-4 shrink-0" }), /* @__PURE__ */ jsx("p", {
									className: "text-muted-foreground text-xs",
									children: t("email_verification_hint")
								})]
							}),
							/* @__PURE__ */ jsxs("div", {
								className: "flex gap-2",
								children: [/* @__PURE__ */ jsx(Button, {
									type: "button",
									variant: "outline",
									size: "sm",
									onClick: handleCancelEmailEdit,
									children: t("cancel")
								}), /* @__PURE__ */ jsxs(Button, {
									type: "button",
									size: "sm",
									onClick: handleEmailSubmit,
									disabled: !newEmail.trim() || isChangingEmail,
									children: [isChangingEmail && /* @__PURE__ */ jsx("div", { className: "mr-2 size-3.5 animate-spin rounded-full border-2 border-current/30 border-t-current" }), isChangingEmail ? t("sending") : t("send_verification")]
								})]
							})
						]
					}) : pendingEmail ? /* @__PURE__ */ jsxs("div", {
						className: "space-y-2",
						children: [/* @__PURE__ */ jsx("div", {
							className: "bg-muted text-muted-foreground min-w-0 rounded-md px-3 py-2 text-sm",
							children: email
						}), /* @__PURE__ */ jsxs("div", {
							className: "bg-muted flex items-start gap-2.5 rounded-md px-3 py-2.5",
							children: [/* @__PURE__ */ jsx(Info, { className: "text-primary mt-0.5 size-4 shrink-0" }), /* @__PURE__ */ jsxs("p", {
								className: "text-muted-foreground text-xs",
								children: [
									t("changing_email_to"),
									" ",
									/* @__PURE__ */ jsx("span", {
										className: "text-foreground font-medium",
										children: pendingEmail
									}),
									". ",
									t("check_new_email_verification")
								]
							})]
						})]
					}) : /* @__PURE__ */ jsxs("div", {
						className: "flex items-center gap-2",
						children: [/* @__PURE__ */ jsx("div", {
							className: "bg-muted text-muted-foreground min-w-0 flex-1 rounded-md px-3 py-2 text-sm",
							children: email
						}), onChangeEmail && /* @__PURE__ */ jsx(Button, {
							type: "button",
							variant: "outline",
							size: "sm",
							onClick: () => setIsEditingEmail(true),
							className: "shrink-0",
							children: t("change")
						})]
					})]
				}),
				errorMsg && /* @__PURE__ */ jsx("p", {
					className: "text-destructive text-sm",
					children: errorMsg
				}),
				/* @__PURE__ */ jsx(DialogFooter, {
					className: "flex flex-row items-center justify-end",
					children: /* @__PURE__ */ jsx("div", {
						className: "flex-1 text-right",
						children: /* @__PURE__ */ jsxs(Button, {
							type: "button",
							onClick: onSubmit,
							children: [isSubmitting && /* @__PURE__ */ jsx("div", { className: "mr-2 size-4 animate-spin rounded-full border-2 border-current/30 border-t-current" }), isSubmitting ? t("saving") : t("save_changes")]
						})
					})
				})
			]
		})
	});
}
//#endregion
//#region ../../profile/ui/src/components/payment-method-card-internals.tsx
function PaymentIcon({ logoUrl, brand, alt }) {
	const logo = resolvePaymentLogo({
		brand,
		logoUrl,
		alt
	});
	const [hasError, setHasError] = useState(false);
	return /* @__PURE__ */ jsx("img", {
		src: hasError ? logo.fallbackUrl : logo.primaryUrl,
		alt: logo.alt,
		width: 40,
		height: 24,
		className: "object-contain",
		onError: () => setHasError(true)
	});
}
function getPaymentMethodLogoBrand(paymentMethod) {
	if (isCardPaymentMethod(paymentMethod)) return normalizeCardBrand(paymentMethod.details.card_brand) ?? normalizeCardBrand(paymentMethod.details.card_network);
	return paymentDescriptorLabel(paymentMethod.payment_type, paymentMethod.source);
}
function getCardDisplayName(paymentMethod, cardFallback = "Card") {
	if (isCardPaymentMethod(paymentMethod)) return resolvePaymentMethodDisplay({
		kind: "card",
		brand: getPaymentMethodLogoBrand(paymentMethod) ?? cardFallback,
		last4: paymentMethod.details.last_four,
		logoUrl: paymentMethod.details.logo_url
	}).label;
	const fallbackLabel = paymentDescriptorLabel(paymentMethod.payment_type, paymentMethod.source);
	return resolvePaymentMethodDisplay({
		kind: "non_card",
		brand: fallbackLabel,
		fallbackLabel,
		logoUrl: paymentMethod.details.logo_url
	}).label;
}
function getCardExpiry(paymentMethod, expiresLabel = "Expires") {
	const { exp_month, exp_year } = paymentMethod.details;
	if (exp_month != null && exp_year != null) return `${expiresLabel} ${exp_month}/${exp_year}`;
	return "";
}
function isCardPaymentMethod(paymentMethod) {
	return paymentMethod.source === "card" || isCardPaymentDescriptor(paymentMethod.payment_type) || isCardPaymentDescriptor(paymentMethod.source) || normalizePaymentDescriptor(paymentMethod.details.card_brand) != null || normalizePaymentDescriptor(paymentMethod.details.card_network) != null || paymentMethod.details.last_four != null;
}
createContext(null);
//#endregion
//#region ../../fluid-pay/core/src/context.ts
const FluidPayApiContext = createContext(null);
const FluidPayApiProvider = FluidPayApiContext.Provider;
function useFluidPayApi() {
	const api = useContext(FluidPayApiContext);
	if (!api) throw new Error("useFluidPayApi must be used within a FluidPayCoreProvider");
	return api;
}
//#endregion
//#region ../../fluid-pay/core/src/provider.tsx
function FluidPayCoreProvider({ api, children }) {
	return /* @__PURE__ */ jsx(FluidPayApiProvider, {
		value: api,
		children
	});
}
//#endregion
//#region ../../fluid-pay/core/src/utils/country-config.ts
const US_STATES = [
	{
		name: "Alabama",
		isoCode: "AL"
	},
	{
		name: "Alaska",
		isoCode: "AK"
	},
	{
		name: "Arizona",
		isoCode: "AZ"
	},
	{
		name: "Arkansas",
		isoCode: "AR"
	},
	{
		name: "California",
		isoCode: "CA"
	},
	{
		name: "Colorado",
		isoCode: "CO"
	},
	{
		name: "Connecticut",
		isoCode: "CT"
	},
	{
		name: "Delaware",
		isoCode: "DE"
	},
	{
		name: "Florida",
		isoCode: "FL"
	},
	{
		name: "Georgia",
		isoCode: "GA"
	},
	{
		name: "Hawaii",
		isoCode: "HI"
	},
	{
		name: "Idaho",
		isoCode: "ID"
	},
	{
		name: "Illinois",
		isoCode: "IL"
	},
	{
		name: "Indiana",
		isoCode: "IN"
	},
	{
		name: "Iowa",
		isoCode: "IA"
	},
	{
		name: "Kansas",
		isoCode: "KS"
	},
	{
		name: "Kentucky",
		isoCode: "KY"
	},
	{
		name: "Louisiana",
		isoCode: "LA"
	},
	{
		name: "Maine",
		isoCode: "ME"
	},
	{
		name: "Maryland",
		isoCode: "MD"
	},
	{
		name: "Massachusetts",
		isoCode: "MA"
	},
	{
		name: "Michigan",
		isoCode: "MI"
	},
	{
		name: "Minnesota",
		isoCode: "MN"
	},
	{
		name: "Mississippi",
		isoCode: "MS"
	},
	{
		name: "Missouri",
		isoCode: "MO"
	},
	{
		name: "Montana",
		isoCode: "MT"
	},
	{
		name: "Nebraska",
		isoCode: "NE"
	},
	{
		name: "Nevada",
		isoCode: "NV"
	},
	{
		name: "New Hampshire",
		isoCode: "NH"
	},
	{
		name: "New Jersey",
		isoCode: "NJ"
	},
	{
		name: "New Mexico",
		isoCode: "NM"
	},
	{
		name: "New York",
		isoCode: "NY"
	},
	{
		name: "North Carolina",
		isoCode: "NC"
	},
	{
		name: "North Dakota",
		isoCode: "ND"
	},
	{
		name: "Ohio",
		isoCode: "OH"
	},
	{
		name: "Oklahoma",
		isoCode: "OK"
	},
	{
		name: "Oregon",
		isoCode: "OR"
	},
	{
		name: "Pennsylvania",
		isoCode: "PA"
	},
	{
		name: "Rhode Island",
		isoCode: "RI"
	},
	{
		name: "South Carolina",
		isoCode: "SC"
	},
	{
		name: "South Dakota",
		isoCode: "SD"
	},
	{
		name: "Tennessee",
		isoCode: "TN"
	},
	{
		name: "Texas",
		isoCode: "TX"
	},
	{
		name: "Utah",
		isoCode: "UT"
	},
	{
		name: "Vermont",
		isoCode: "VT"
	},
	{
		name: "Virginia",
		isoCode: "VA"
	},
	{
		name: "Washington",
		isoCode: "WA"
	},
	{
		name: "West Virginia",
		isoCode: "WV"
	},
	{
		name: "Wisconsin",
		isoCode: "WI"
	},
	{
		name: "Wyoming",
		isoCode: "WY"
	},
	{
		name: "District of Columbia",
		isoCode: "DC"
	}
];
const COUNTRY_CONFIGS = {
	US: {
		regionLabel: "State",
		postalLabel: "ZIP Code"
	},
	JP: {
		regionLabel: "Prefecture",
		postalLabel: "Postal Code"
	}
};
const DEFAULT_REGION_CONFIG = {
	regionLabel: "Province",
	postalLabel: "Postal Code"
};
function getRegionConfig(countryCode) {
	return COUNTRY_CONFIGS[countryCode] ?? DEFAULT_REGION_CONFIG;
}
//#endregion
//#region ../../fluid-pay/core/src/hooks/use-country-states.ts
function useCountryStates() {
	const [selectedCountry, setSelectedCountry] = useState("US");
	const [stateOptions, setStateOptions] = useState(US_STATES);
	return {
		handleCountryChange: useCallback((selectedCountryCode, fetchStates) => {
			setSelectedCountry(selectedCountryCode);
			const fallbackStates = selectedCountryCode === "US" ? US_STATES : [];
			if (fetchStates) fetchStates(selectedCountryCode).then((states) => setStateOptions(states.length > 0 ? states : fallbackStates)).catch((error) => {
				console.error("Failed to fetch states:", error);
				setStateOptions(fallbackStates);
			});
			else if (selectedCountryCode === "US") setStateOptions(US_STATES);
			else setStateOptions([]);
		}, []),
		stateOptions,
		config: getRegionConfig(selectedCountry),
		selectedCountry
	};
}
//#endregion
//#region ../../profile/ui/src/components/edit-payment-method-dialog.tsx
function createEditPaymentMethodFormSchema(t) {
	return z.object({
		billing_address: z.object({
			name: z.string().min(1, t("name_is_required")),
			address1: z.string().min(1, t("address_line_1_is_required")),
			address2: z.string().optional().nullable(),
			city: z.string().min(1, t("city_is_required")),
			state: z.string().min(1, t("state_is_required")),
			zip: z.string().min(1, t("zip_code_is_required")),
			country_code: z.string().min(1, t("country_is_required"))
		}),
		set_as_default: z.boolean()
	});
}
function EditPaymentMethodDialog({ isOpen, paymentMethod, billingAddress, onClose, onSubmit, isSubmitting, error, countries = [], onDelete, isDeleting = false }) {
	const { t } = useProfileTranslation();
	const [confirmDelete, setConfirmDelete] = useState(false);
	useEffect(() => {
		if (!isOpen) setConfirmDelete(false);
	}, [isOpen]);
	useEffect(() => {
		if (!confirmDelete) return;
		const timeoutId = setTimeout(() => setConfirmDelete(false), 3e3);
		return () => clearTimeout(timeoutId);
	}, [confirmDelete]);
	const { control, handleSubmit, reset, setValue } = useZodForm(useMemo(() => createEditPaymentMethodFormSchema((key) => t(key)), [t]), { defaultValues: {
		billing_address: {
			name: "",
			address1: "",
			address2: "",
			city: "",
			state: "",
			zip: "",
			country_code: "US"
		},
		set_as_default: false
	} });
	const billingCountry = useWatch({
		control,
		name: "billing_address.country_code"
	});
	const setAsDefault = useWatch({
		control,
		name: "set_as_default"
	});
	const { stateOptions, config, handleCountryChange } = useCountryStates();
	const countryOptions = [...countries].map((country) => ({
		name: country.name,
		value: country.iso
	})).sort((a, b) => {
		if (a.value === billingCountry) return -1;
		if (b.value === billingCountry) return 1;
		return a.name.localeCompare(b.name);
	});
	const stateSelectOptions = stateOptions.map((state) => ({
		name: state.name,
		value: state.isoCode
	}));
	useEffect(() => {
		if (paymentMethod && isOpen) reset({
			billing_address: {
				name: billingAddress?.name ?? "",
				address1: billingAddress?.address1 ?? "",
				address2: billingAddress?.address2 ?? "",
				city: billingAddress?.city ?? "",
				state: billingAddress?.state ?? "",
				zip: billingAddress?.zip ?? "",
				country_code: billingAddress?.country_code ?? "US"
			},
			set_as_default: paymentMethod.default
		});
	}, [
		paymentMethod,
		billingAddress,
		isOpen,
		reset
	]);
	const handleCountrySelect = (countryCode) => {
		handleCountryChange(countryCode);
		setValue("billing_address.country_code", countryCode, { shouldValidate: true });
	};
	const handleFormSubmit = handleSubmit((data) => {
		onSubmit(data);
	});
	const deleteButtonLabel = useMemo(() => {
		if (isDeleting) return t("deleting");
		if (confirmDelete) return t("tap_to_confirm");
		return t("delete_card");
	}, [
		isDeleting,
		confirmDelete,
		t
	]);
	if (!paymentMethod) return null;
	const { details } = paymentMethod;
	const displayName = getCardDisplayName(paymentMethod, t("card_fallback"));
	const expMonth = details.exp_month;
	const expYear = details.exp_year;
	return /* @__PURE__ */ jsx(Dialog, {
		open: isOpen,
		onOpenChange: (open) => !open && onClose(),
		children: /* @__PURE__ */ jsxs(DialogContent, {
			className: "max-h-[90vh] max-w-sm overflow-y-auto md:max-w-lg",
			children: [
				/* @__PURE__ */ jsx(DialogHeader, { children: /* @__PURE__ */ jsx(DialogTitle, { children: t("edit_card") }) }),
				/* @__PURE__ */ jsxs("div", {
					className: "space-y-4",
					children: [/* @__PURE__ */ jsx("div", {
						className: "bg-muted rounded-lg p-4",
						children: /* @__PURE__ */ jsxs("div", {
							className: "flex items-center gap-x-3",
							children: [/* @__PURE__ */ jsx("div", {
								className: "h-6 w-10 flex-shrink-0",
								children: /* @__PURE__ */ jsx(PaymentIcon, {
									logoUrl: details.logo_url,
									brand: getPaymentMethodLogoBrand(paymentMethod),
									alt: displayName
								})
							}), /* @__PURE__ */ jsxs("div", {
								className: "flex flex-col",
								children: [/* @__PURE__ */ jsx("span", {
									className: "text-foreground text-sm font-medium",
									children: displayName
								}), expMonth != null && expYear != null && /* @__PURE__ */ jsxs("span", {
									className: "text-muted-foreground text-sm",
									children: [
										t("card_expires"),
										" ",
										expMonth,
										"/",
										expYear
									]
								})]
							})]
						})
					}), /* @__PURE__ */ jsxs("div", { children: [/* @__PURE__ */ jsx("h3", {
						className: "text-foreground mb-3 text-sm font-medium",
						children: t("billing_address")
					}), /* @__PURE__ */ jsxs("div", {
						className: "space-y-3",
						children: [
							/* @__PURE__ */ jsx(FormSelectField, {
								control,
								name: "billing_address.country_code",
								label: t("country"),
								options: countryOptions,
								placeholder: t("select_an_option"),
								onChange: (val) => {
									handleCountrySelect(val);
								}
							}),
							/* @__PURE__ */ jsx(FormTextField$1, {
								control,
								name: "billing_address.name",
								label: t("name")
							}),
							/* @__PURE__ */ jsx(FormTextField$1, {
								control,
								name: "billing_address.address1",
								label: t("address_line_1")
							}),
							/* @__PURE__ */ jsx(FormTextField$1, {
								control,
								name: "billing_address.address2",
								label: t("address_line_2")
							}),
							/* @__PURE__ */ jsxs("div", {
								className: "grid grid-cols-1 gap-3 sm:grid-cols-3",
								children: [
									/* @__PURE__ */ jsx(FormTextField$1, {
										control,
										name: "billing_address.city",
										label: t("city")
									}),
									/* @__PURE__ */ jsx(FormSelectField, {
										control,
										name: "billing_address.state",
										label: config?.regionLabel ? t(config.regionLabel) : t("state"),
										options: stateSelectOptions,
										placeholder: t("select_state")
									}),
									/* @__PURE__ */ jsx(FormTextField$1, {
										control,
										name: "billing_address.zip",
										label: config?.postalLabel ? t(config.postalLabel) : t("zip_code")
									})
								]
							})
						]
					})] })]
				}),
				/* @__PURE__ */ jsxs("div", {
					className: "mt-2 flex items-center gap-x-2",
					children: [/* @__PURE__ */ jsx("input", {
						type: "checkbox",
						id: "set_as_default",
						checked: setAsDefault,
						onChange: () => setValue("set_as_default", !setAsDefault),
						className: "size-4"
					}), /* @__PURE__ */ jsx("label", {
						htmlFor: "set_as_default",
						className: "text-sm",
						children: t("set_as_default_payment_method")
					})]
				}),
				error && /* @__PURE__ */ jsx("div", {
					className: "text-destructive text-sm",
					children: error
				}),
				/* @__PURE__ */ jsxs(DialogFooter, {
					className: "flex flex-row items-center justify-between gap-2",
					children: [onDelete ? /* @__PURE__ */ jsxs(Button, {
						type: "button",
						variant: "ghost",
						onClick: () => {
							if (confirmDelete) onDelete();
							else setConfirmDelete(true);
						},
						disabled: isSubmitting || isDeleting,
						className: "text-destructive hover:bg-destructive/10 hover:text-destructive",
						children: [/* @__PURE__ */ jsx(Trash2, { className: "size-4" }), deleteButtonLabel]
					}) : /* @__PURE__ */ jsx("span", {}), /* @__PURE__ */ jsxs("div", {
						className: "flex items-center gap-2",
						children: [/* @__PURE__ */ jsx(Button, {
							type: "button",
							variant: "secondary",
							onClick: onClose,
							disabled: isSubmitting || isDeleting,
							children: t("cancel")
						}), /* @__PURE__ */ jsxs(Button, {
							type: "button",
							onClick: handleFormSubmit,
							disabled: isSubmitting || isDeleting,
							children: [isSubmitting && /* @__PURE__ */ jsx("div", { className: "mr-2 size-4 animate-spin rounded-full border-2 border-current/30 border-t-current" }), isSubmitting ? t("saving") : t("save_changes")]
						})]
					})]
				})
			]
		})
	});
}
//#endregion
//#region ../../profile/ui/src/components/my-site-profile-section.tsx
function normalizeUrl(value) {
	const trimmed = value.trim();
	if (!trimmed) return "";
	if (/^https?:\/\//i.test(trimmed)) return trimmed;
	return `https://${trimmed}`;
}
const urlField = z.string().transform(normalizeUrl).pipe(z.string().url().or(z.literal("")));
z.object({
	bio: z.string().optional(),
	linkedin: urlField,
	facebook: urlField,
	twitter: urlField,
	instagram: urlField,
	youtube: urlField,
	pinterest: urlField,
	tiktok: urlField,
	whatsapp: z.string().optional(),
	wechat: z.string().optional()
});
//#endregion
//#region ../../fluid-pay/ui/src/components/form-fields/FormTextField.tsx
function FormTextField({ control, name, label, placeholder, containerClassName, type, disabled, inputMode, autoComplete }) {
	const { field, fieldState: { error } } = useController({
		name,
		control
	});
	return /* @__PURE__ */ jsxs("div", {
		className: cn("space-y-1", containerClassName),
		children: [
			label && /* @__PURE__ */ jsx(Label, {
				htmlFor: name,
				className: "mb-1.5 block text-sm font-medium",
				children: label
			}),
			/* @__PURE__ */ jsx(Input, {
				...field,
				value: field.value ?? "",
				id: name,
				type,
				disabled,
				inputMode,
				placeholder,
				autoComplete,
				"aria-invalid": !!error
			}),
			error?.message && /* @__PURE__ */ jsx("p", {
				className: "text-destructive text-sm",
				children: error.message
			})
		]
	});
}
//#endregion
//#region ../../fluid-pay/ui/src/components/form-fields/FormComboboxField.tsx
function FormComboboxField({ control, name, label, placeholder = "Select", emptyText = "No results found.", options, containerClassName, disabled }) {
	const comboboxOptions = useMemo(() => options?.map((opt) => ({
		label: opt.name,
		value: opt.value.toString()
	})) ?? [], [options]);
	return /* @__PURE__ */ jsxs("div", {
		className: cn("space-y-1", containerClassName),
		children: [label && /* @__PURE__ */ jsx(Label, {
			htmlFor: name,
			className: "mb-1.5 block text-sm font-medium",
			children: label
		}), /* @__PURE__ */ jsx(Controller, {
			control,
			name,
			render: ({ field: { onChange, value }, fieldState: { error } }) => /* @__PURE__ */ jsxs(Fragment$1, { children: [/* @__PURE__ */ jsx(Combobox, {
				options: comboboxOptions,
				value: value?.toString() ?? "",
				onValueChange: onChange,
				placeholder,
				emptyText,
				disabled
			}), error?.message && /* @__PURE__ */ jsx("p", {
				className: "text-destructive text-sm",
				children: error.message
			})] })
		})]
	});
}
//#endregion
//#region ../../fluid-pay/ui/src/components/AddressFormDialog.tsx
const addressFormSchema = z.object({
	name: z.string(),
	address1: z.string(),
	address2: z.string().optional().nullable(),
	city: z.string(),
	state: z.string(),
	postal_code: z.string(),
	phone: z.string().optional().nullable(),
	country_code: z.string().min(1, "Country is required"),
	default: z.boolean()
});
const STATIC_FIELD_ORDER = [
	"name",
	"address1",
	"address2",
	"city",
	"state",
	"postal_code",
	"phone"
];
const STATIC_LABELS = {
	name: "name",
	address1: "address_line_1",
	address2: "address_line_2",
	city: "city",
	state: "state",
	postal_code: "zip_code",
	phone: "phone_number"
};
const DEFAULT_HIDDEN_FIELDS = new Set(["phone"]);
const STATIC_REQUIRED_FIELDS = new Set([
	"name",
	"address1",
	"city",
	"state",
	"postal_code"
]);
const REQUIRED_FIELD_MESSAGES = {
	name: "Name is required",
	address1: "Address line 1 is required",
	address2: "Address line 2 is required",
	city: "City is required",
	state: "State is required",
	postal_code: "Postal code is required",
	phone: "Phone is required"
};
const AUTOCOMPLETE_FIELD_PREFIX = [
	"name",
	"address1",
	"address2"
];
function isAddressFieldName(value) {
	return STATIC_FIELD_ORDER.includes(value);
}
function prioritizeAutocompleteFields(fields) {
	const prefix = AUTOCOMPLETE_FIELD_PREFIX.filter((field) => fields.includes(field));
	const rest = fields.filter((field) => !AUTOCOMPLETE_FIELD_PREFIX.includes(field));
	return [...prefix, ...rest];
}
function groupFields(fields) {
	const groups = [];
	let i = 0;
	while (i < fields.length) {
		const current = fields[i];
		const locationFields = new Set([
			"city",
			"state",
			"postal_code"
		]);
		if (locationFields.has(current)) {
			const group = [current];
			while (i + group.length < fields.length && locationFields.has(fields[i + group.length])) group.push(fields[i + group.length]);
			if (group.length > 1) {
				groups.push(group);
				i += group.length;
				continue;
			}
		}
		groups.push([current]);
		i++;
	}
	return groups;
}
function isFieldRequired(bffFields, fieldName) {
	if (!bffFields) return STATIC_REQUIRED_FIELDS.has(fieldName);
	return bffFields.find((field) => field.field === fieldName)?.required ?? false;
}
function isBlank(value) {
	return value == null || value.trim().length === 0;
}
function AddressFormDialog({ isOpen, onClose, selectedAddress, onSubmit, isSubmitting, countries = [], error, renderAddressAutocomplete, fetchStates, t, onDelete, isDeleting = false, defaultCountry = "US", languageIso }) {
	const [confirmDelete, setConfirmDelete] = useState(false);
	const phoneInputId = useId();
	const addressFieldsApi = useAddressFieldsApiOptional();
	const [bffFields, setBffFields] = useState(null);
	useEffect(() => {
		if (!isOpen) setConfirmDelete(false);
	}, [isOpen]);
	useEffect(() => {
		if (!confirmDelete) return;
		const timeoutId = setTimeout(() => setConfirmDelete(false), 3e3);
		return () => clearTimeout(timeoutId);
	}, [confirmDelete]);
	const deleteButtonLabel = useMemo(() => {
		if (isDeleting) return t("deleting");
		if (confirmDelete) return t("tap_to_confirm");
		return t("delete_address");
	}, [
		isDeleting,
		confirmDelete,
		t
	]);
	const { control, handleSubmit, reset, setValue, setError, clearErrors } = useZodForm(addressFormSchema, { defaultValues: {
		name: "",
		address1: "",
		address2: "",
		city: "",
		state: "",
		postal_code: "",
		phone: "",
		country_code: defaultCountry,
		default: false
	} });
	const selectedCountryCode = useWatch({
		control,
		name: "country_code"
	});
	const isDefault = useWatch({
		control,
		name: "default"
	});
	const { stateOptions, config, handleCountryChange } = useCountryStates();
	const hasAddressAutocomplete = Boolean(renderAddressAutocomplete);
	useEffect(() => {
		if (!addressFieldsApi || !selectedCountryCode) return;
		let cancelled = false;
		setBffFields(null);
		addressFieldsApi.fetchAddressFields(selectedCountryCode, languageIso).then((response) => {
			if (!cancelled) setBffFields([...response.address_fields.fields]);
		}).catch(() => {
			if (!cancelled) setBffFields(null);
		});
		return () => {
			cancelled = true;
		};
	}, [
		addressFieldsApi,
		selectedCountryCode,
		languageIso
	]);
	const fieldOrder = useMemo(() => {
		if (!bffFields) return STATIC_FIELD_ORDER.filter((f) => !DEFAULT_HIDDEN_FIELDS.has(f));
		const fieldOrder = bffFields.map((f) => f.field).filter(isAddressFieldName);
		return hasAddressAutocomplete ? prioritizeAutocompleteFields(fieldOrder) : fieldOrder;
	}, [bffFields, hasAddressAutocomplete]);
	const fieldGroups = useMemo(() => groupFields(fieldOrder), [fieldOrder]);
	const getFieldLabel = (fieldName) => {
		if (bffFields) {
			const bffField = bffFields.find((f) => f.field === fieldName);
			if (bffField) return bffField.label;
		}
		if (fieldName === "state" && config?.regionLabel) return t(config.regionLabel);
		if (fieldName === "postal_code" && config?.postalLabel) return t(config.postalLabel);
		const key = STATIC_LABELS[fieldName];
		return key ? t(key) : fieldName;
	};
	const countrySelectOptions = [...countries].map((country) => ({
		name: country.name,
		value: country.iso
	})).sort((a, b) => {
		if (a.value === selectedCountryCode) return -1;
		if (b.value === selectedCountryCode) return 1;
		return a.name.localeCompare(b.name);
	});
	const stateSelectOptions = stateOptions.map((state) => ({
		name: state.name,
		value: state.isoCode
	}));
	useEffect(() => {
		if (isOpen) if (selectedAddress) {
			reset({
				name: selectedAddress.name ?? "",
				address1: selectedAddress.address1,
				address2: selectedAddress.address2 ?? "",
				city: selectedAddress.city,
				state: selectedAddress.state,
				postal_code: selectedAddress.postal_code,
				phone: selectedAddress.phone ?? "",
				country_code: selectedAddress.country_code ?? defaultCountry,
				default: selectedAddress.default
			});
			handleCountryChange(selectedAddress.country_code ?? defaultCountry, fetchStates);
		} else {
			reset({
				name: "",
				address1: "",
				address2: "",
				city: "",
				state: "",
				postal_code: "",
				phone: "",
				country_code: defaultCountry,
				default: false
			});
			handleCountryChange(defaultCountry, fetchStates);
		}
	}, [
		selectedAddress,
		isOpen,
		reset,
		handleCountryChange,
		fetchStates
	]);
	useEffect(() => {
		handleCountryChange(selectedCountryCode, fetchStates);
	}, [
		selectedCountryCode,
		handleCountryChange,
		fetchStates
	]);
	const handleFormSubmit = handleSubmit((data) => {
		clearErrors(STATIC_FIELD_ORDER);
		const missingRequiredFields = fieldOrder.filter((fieldName) => isFieldRequired(bffFields, fieldName) && isBlank(data[fieldName]));
		if (missingRequiredFields.length > 0) {
			for (const fieldName of missingRequiredFields) setError(fieldName, {
				type: "manual",
				message: REQUIRED_FIELD_MESSAGES[fieldName]
			});
			return;
		}
		const city = bffFields && !fieldOrder.includes("city") ? "" : data.city;
		const state = bffFields && !fieldOrder.includes("state") ? "" : data.state;
		onSubmit({ address: {
			name: data.name,
			address1: data.address1,
			address2: data.address2 ?? null,
			city,
			state,
			postal_code: data.postal_code,
			phone: data.phone || null,
			country_code: data.country_code,
			default: data.default
		} });
	});
	const renderField = (fieldName, containerClassName) => {
		const label = getFieldLabel(fieldName);
		if (fieldName === "state" && stateSelectOptions.length > 0) return /* @__PURE__ */ jsx(FormComboboxField, {
			control,
			name: "state",
			label,
			placeholder: t("select_state"),
			options: stateSelectOptions,
			containerClassName,
			disabled: isSubmitting
		}, fieldName);
		if (fieldName === "address1" && renderAddressAutocomplete) return /* @__PURE__ */ jsxs("div", {
			className: cn("space-y-1", containerClassName),
			children: [/* @__PURE__ */ jsx(Label, {
				htmlFor: fieldName,
				className: "mb-1.5 block text-sm font-medium",
				children: label
			}), renderAddressAutocomplete({
				control,
				setValue,
				countryCode: selectedCountryCode,
				stateOptions
			})]
		}, fieldName);
		if (fieldName === "phone") return /* @__PURE__ */ jsx("div", {
			className: containerClassName,
			children: /* @__PURE__ */ jsx(Controller, {
				control,
				name: "phone",
				render: ({ field: { value, onChange }, fieldState: { error } }) => /* @__PURE__ */ jsxs("div", {
					className: "space-y-1",
					children: [
						/* @__PURE__ */ jsx(Label, {
							htmlFor: phoneInputId,
							className: "mb-1.5 block text-sm font-medium",
							children: label
						}),
						/* @__PURE__ */ jsx(PhoneInput, {
							id: phoneInputId,
							value: value ?? "",
							onChange,
							defaultCountry: selectedCountryCode,
							error: !!error,
							disabled: isSubmitting,
							searchPlaceholder: t("search_country"),
							emptyText: t("no_results_found")
						}),
						error?.message && /* @__PURE__ */ jsx("p", {
							className: "text-destructive text-sm",
							children: error.message
						})
					]
				})
			})
		}, fieldName);
		return /* @__PURE__ */ jsx(FormTextField, {
			control,
			name: fieldName,
			label,
			containerClassName,
			disabled: isSubmitting,
			autoComplete: fieldName === "name" ? "name" : void 0
		}, fieldName);
	};
	const isEditMode = selectedAddress !== null;
	return /* @__PURE__ */ jsx(Dialog, {
		open: isOpen,
		onOpenChange: (open) => !open && onClose(),
		children: /* @__PURE__ */ jsxs(DialogContent, {
			"aria-describedby": void 0,
			className: "max-h-[90vh] max-w-md overflow-y-auto rounded md:max-w-xl",
			children: [
				/* @__PURE__ */ jsx(DialogHeader, { children: /* @__PURE__ */ jsx(DialogTitle, {
					className: "text-lg font-medium",
					children: isEditMode ? t("edit_address") : t("add_an_address")
				}) }),
				/* @__PURE__ */ jsxs("div", {
					className: "space-y-3 pt-2",
					children: [/* @__PURE__ */ jsx(FormComboboxField, {
						control,
						name: "country_code",
						label: t("country"),
						placeholder: t("select_an_option"),
						options: countrySelectOptions,
						disabled: isSubmitting
					}), fieldGroups.map((group) => {
						if (group.length === 1) return renderField(group[0]);
						return /* @__PURE__ */ jsx("div", {
							className: "flex gap-3",
							children: group.map((fieldName) => renderField(fieldName, "flex-1"))
						}, group.join("-"));
					})]
				}),
				/* @__PURE__ */ jsxs("div", {
					className: "mt-4 flex flex-wrap items-center justify-between gap-3",
					children: [onDelete ? /* @__PURE__ */ jsxs(Button, {
						type: "button",
						variant: "ghost",
						onClick: () => {
							if (confirmDelete) onDelete();
							else setConfirmDelete(true);
						},
						disabled: isSubmitting || isDeleting,
						className: "text-destructive hover:bg-destructive/10 hover:text-destructive",
						children: [/* @__PURE__ */ jsx(Trash2, { className: "size-4" }), deleteButtonLabel]
					}) : /* @__PURE__ */ jsx("span", {}), /* @__PURE__ */ jsxs("div", {
						className: "flex items-center gap-3",
						children: [/* @__PURE__ */ jsxs("div", {
							className: "flex items-center gap-x-2",
							children: [/* @__PURE__ */ jsx("input", {
								type: "checkbox",
								id: "set_as_default_address",
								checked: isDefault,
								onChange: () => setValue("default", !isDefault),
								disabled: isSubmitting || isDeleting,
								className: "size-4"
							}), /* @__PURE__ */ jsx("label", {
								htmlFor: "set_as_default_address",
								className: "text-sm",
								children: t("set_as_default_address")
							})]
						}), /* @__PURE__ */ jsxs(Button, {
							type: "submit",
							onClick: handleFormSubmit,
							disabled: isSubmitting || isDeleting,
							children: [isSubmitting && /* @__PURE__ */ jsx("div", { className: "mr-2 size-4 animate-spin rounded-full border-2 border-current/30 border-t-current" }), isSubmitting ? t("saving") : t("save_address")]
						})]
					})]
				}),
				error && /* @__PURE__ */ jsx("div", {
					className: "text-destructive mt-2 text-sm",
					children: error
				})
			]
		})
	});
}
//#endregion
//#region ../../fluid-pay/ui/src/hooks/use-vgs-collect.ts
const getVGSCollect = () => {
	if (typeof window !== "undefined") return window.VGSCollect || null;
	return null;
};
const DEFAULT_FIELD_STATE = {
	card_number: {
		isFocused: false,
		isValid: false,
		isEmpty: true
	},
	card_exp: {
		isFocused: false,
		isValid: false,
		isEmpty: true
	},
	card_cvc: {
		isFocused: false,
		isValid: false,
		isEmpty: true
	},
	card_holder: {
		isFocused: false,
		isValid: false,
		isEmpty: true
	}
};
function useVgsCollect() {
	const [isFormReady, setIsFormReady] = useState(false);
	const [isLoading, setIsLoading] = useState(false);
	const [isScriptLoaded, setIsScriptLoaded] = useState(false);
	const [scriptLoadError, setScriptLoadError] = useState(void 0);
	const [vgsFieldState, setVgsFieldState] = useState(DEFAULT_FIELD_STATE);
	const formRef = useRef(null);
	const onSuccessRef = useRef(null);
	const onErrorRef = useRef(null);
	useEffect(() => {
		if (typeof window === "undefined") return;
		if (getVGSCollect()) {
			const timeoutId = window.setTimeout(() => {
				setIsScriptLoaded(true);
			}, 0);
			return () => window.clearTimeout(timeoutId);
		}
		if (isScriptLoaded) return;
		const script = document.createElement("script");
		script.src = "https://js.verygoodvault.com/vgs-collect/3.3.0/vgs-collect.js";
		script.async = true;
		script.onload = () => setIsScriptLoaded(true);
		script.onerror = () => {
			const message = "Failed to load payment form";
			setScriptLoadError(message);
			onErrorRef.current?.(message);
		};
		document.head.appendChild(script);
	}, [isScriptLoaded]);
	const updateFieldState = useCallback((state) => {
		if (!state) return;
		setVgsFieldState((prev) => {
			const newState = { ...prev };
			let hasChanges = false;
			Object.keys(state).forEach((key) => {
				const field = state[key];
				if (!field) return;
				const next = {
					isFocused: !!field.isFocused,
					isValid: !!field.isValid,
					isEmpty: !!field.isEmpty,
					cardType: field.cardType,
					bin: field.bin,
					last4: field.last4
				};
				if (!newState[key] || JSON.stringify(newState[key]) !== JSON.stringify(next)) {
					newState[key] = next;
					hasChanges = true;
				}
			});
			return hasChanges ? newState : prev;
		});
	}, []);
	const resetVgs = useCallback(() => {
		if (formRef.current) {
			try {
				formRef.current.unmount();
			} catch (e) {
				console.warn("VGS unmount error", e);
			}
			formRef.current = null;
		}
		setIsFormReady(false);
		setVgsFieldState({ ...DEFAULT_FIELD_STATE });
	}, []);
	const initializeForm = useCallback(async (credentials) => {
		if (!isScriptLoaded) return;
		const VGSCollect = getVGSCollect();
		if (!VGSCollect) {
			onErrorRef.current?.("Payment script not loaded");
			return;
		}
		try {
			setIsLoading(true);
			const vgsEnvironment = credentials.vault.environment === "sandbox" ? "sandbox" : "live-eu-1";
			const form = VGSCollect.create(credentials.vault.vault_id, vgsEnvironment, (state) => updateFieldState(state));
			if (credentials.vault.route_id) form.setRouteId(credentials.vault.route_id);
			formRef.current = form;
			let retries = 0;
			const maxRetries = 20;
			const retryDelay = 200;
			const waitForDom = async () => {
				if ([
					"vgs-card-number",
					"vgs-expiration-date",
					"vgs-cvc",
					"vgs-card-holder"
				].every((id) => {
					const el = document.getElementById(id);
					return el && el.isConnected;
				})) return true;
				if (retries >= maxRetries) return false;
				retries++;
				await new Promise((resolve) => setTimeout(resolve, retryDelay));
				return waitForDom();
			};
			if (!await waitForDom()) throw new Error("Payment form elements not ready");
			const themedNode = document.getElementById("vgs-card-number");
			const probeStyle = themedNode ? getComputedStyle(themedNode) : null;
			const foregroundColor = probeStyle?.getPropertyValue("--color-foreground").trim() || "#0a0a0a";
			const mutedForegroundColor = probeStyle?.getPropertyValue("--color-muted-foreground").trim() || "#737373";
			const css = {
				fontSize: "14px",
				fontFamily: "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif",
				color: foregroundColor,
				background: "transparent",
				paddingTop: "0px",
				paddingBottom: "0px",
				paddingLeft: "0px",
				paddingRight: "0px",
				boxSizing: "border-box",
				lineHeight: "26px",
				height: "100%",
				width: "100%",
				"&::placeholder": {
					color: mutedForegroundColor,
					opacity: 1
				},
				"&:focus": { outline: "none" }
			};
			form.field("#vgs-card-number", {
				type: "card-number",
				name: "card_number",
				placeholder: "0000 0000 0000 0000",
				showCardIcon: true,
				css: {
					...css,
					paddingRight: "40px"
				},
				autoComplete: "cc-number",
				validations: ["required", "validCardNumber"]
			});
			form.field("#vgs-expiration-date", {
				type: "card-expiration-date",
				name: "card_exp",
				yearLength: 2,
				placeholder: "MM / YY",
				css,
				autoComplete: "cc-exp",
				validations: ["required", "validCardExpirationDate"]
			});
			form.field("#vgs-cvc", {
				type: "card-security-code",
				name: "card_cvc",
				placeholder: "123",
				css,
				autoComplete: "cc-csc",
				validations: ["required", "validCardSecurityCode"]
			});
			form.field("#vgs-card-holder", {
				type: "text",
				name: "card_holder",
				placeholder: "Full Name",
				css,
				autoComplete: "cc-name",
				validations: ["required"]
			});
			setIsFormReady(true);
		} catch (error) {
			console.error("Failed to initialize VGS:", error);
			onErrorRef.current?.("Failed to initialize payment form");
		} finally {
			setIsLoading(false);
		}
	}, [isScriptLoaded, updateFieldState]);
	const submitCard = useCallback(() => {
		if (!formRef.current) {
			onErrorRef.current?.("Form not initialized");
			return;
		}
		formRef.current.submit(`/post`, {}, (status, response) => {
			if (status >= 200 && status < 400) onSuccessRef.current?.(response);
			else onErrorRef.current?.("Payment failed");
		}, (errors) => {
			const allErrors = Object.values(errors).flat().filter((msg) => typeof msg === "string" && msg.trim().length > 0 && msg !== "Required");
			const uniqueErrors = Array.from(new Set(allErrors));
			let errorMsg = "Please verify your payment details.";
			if (uniqueErrors.length > 0) errorMsg = uniqueErrors.join(", ");
			else if (Object.values(errors).flat().length > 0) errorMsg = "Please fill in all required fields.";
			onErrorRef.current?.(errorMsg);
		});
	}, []);
	useEffect(() => {
		return () => {
			if (formRef.current) {
				try {
					formRef.current.unmount();
				} catch (e) {
					console.warn("VGS unmount error", e);
				}
				formRef.current = null;
			}
		};
	}, []);
	return {
		isFormReady,
		isLoading,
		isScriptLoaded,
		scriptLoadError,
		initializeForm,
		submitCard,
		vgsFieldState,
		resetVgs,
		onSuccessRef,
		onErrorRef
	};
}
//#endregion
//#region ../../fluid-pay/ui/src/components/CreditCardFormDialog.tsx
const SENTINEL_CREATE_NEW = "__create_new__";
const formSchema = z.object({
	billing_address_selection: z.string().refine((value) => value !== "" && value !== SENTINEL_CREATE_NEW, { message: "Please select a billing address" }),
	set_as_default: z.boolean()
});
function VgsInputWrapper({ id, label, fieldState, className }) {
	const isInvalid = fieldState?.isValid === false && !fieldState?.isFocused && !fieldState?.isEmpty;
	const isFocused = !!fieldState?.isFocused;
	return /* @__PURE__ */ jsx("div", {
		id,
		role: "group",
		"aria-label": label,
		"data-invalid": isInvalid ? "" : void 0,
		className: cn("border-input selection:bg-primary selection:text-primary-foreground file:text-foreground placeholder:text-muted-foreground h-9 w-full min-w-0 rounded-md border bg-transparent px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm", "focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]", "data-[invalid]:border-destructive data-[invalid]:ring-destructive/20", "[&_iframe]:block! [&_iframe]:h-full! [&_iframe]:w-full! [&_iframe]:border-0!", isFocused && "border-ring ring-ring/50 ring-[3px]", isFocused && isInvalid && "border-destructive ring-destructive/20", className)
	});
}
function VgsCardForm({ vgsFieldState, networkError }) {
	return /* @__PURE__ */ jsxs("div", {
		className: "space-y-4",
		"aria-label": "Credit card form",
		children: [
			/* @__PURE__ */ jsx(VgsInputWrapper, {
				id: "vgs-card-number",
				label: "Card number",
				fieldState: vgsFieldState["card_number"]
			}),
			/* @__PURE__ */ jsxs("div", {
				className: "flex gap-3",
				children: [/* @__PURE__ */ jsx("div", {
					className: "flex-1",
					children: /* @__PURE__ */ jsx(VgsInputWrapper, {
						id: "vgs-expiration-date",
						label: "Expiration date",
						fieldState: vgsFieldState["card_exp"]
					})
				}), /* @__PURE__ */ jsx("div", {
					className: "flex-1",
					children: /* @__PURE__ */ jsx(VgsInputWrapper, {
						id: "vgs-cvc",
						label: "CVC",
						fieldState: vgsFieldState["card_cvc"]
					})
				})]
			}),
			/* @__PURE__ */ jsx(VgsInputWrapper, {
				id: "vgs-card-holder",
				label: "Cardholder name",
				fieldState: vgsFieldState["card_holder"]
			}),
			networkError && networkError.trim().length > 0 && /* @__PURE__ */ jsx("div", {
				className: "bg-destructive/10 text-destructive rounded-md p-3 text-sm",
				children: networkError
			})
		]
	});
}
function formatAddressOneLine(addr) {
	const cityStateZip = [
		addr.city,
		addr.state,
		addr.postal_code
	].filter((p) => Boolean(p && p.trim().length > 0)).join(", ");
	return [
		addr.address1,
		addr.address2,
		cityStateZip,
		addr.country_code
	].filter((p) => Boolean(p && p.trim().length > 0)).join(" • ");
}
function AddressSummaryCard({ address }) {
	return /* @__PURE__ */ jsxs("div", {
		className: "border-input bg-muted/30 rounded-md border p-3 text-sm break-words",
		children: [
			address.name && /* @__PURE__ */ jsx("div", {
				className: "font-medium",
				children: address.name
			}),
			/* @__PURE__ */ jsx("div", {
				className: "text-muted-foreground",
				children: address.address1
			}),
			address.address2 && /* @__PURE__ */ jsx("div", {
				className: "text-muted-foreground",
				children: address.address2
			}),
			/* @__PURE__ */ jsxs("div", {
				className: "text-muted-foreground",
				children: [[address.city, address.state].filter(Boolean).join(", "), address.postal_code ? ` ${address.postal_code}` : ""]
			}),
			address.country_code && /* @__PURE__ */ jsx("div", {
				className: "text-muted-foreground",
				children: address.country_code
			})
		]
	});
}
function CreditCardFormDialog({ isOpen, onClose, onSubmit, isSubmitting, error, jwt, shippingAddress, savedAddresses = [], defaultBillingAddressId, renderAddressFormDialog, t }) {
	const api = useFluidPayApi();
	const [cardError, setCardError] = useState(void 0);
	const [isVgsSubmitting, setIsVgsSubmitting] = useState(false);
	const [createdAddresses, setCreatedAddresses] = useState([]);
	const [isAddressDialogOpen, setIsAddressDialogOpen] = useState(false);
	const { isFormReady, isLoading: isVgsLoading, isScriptLoaded, scriptLoadError, initializeForm, submitCard, vgsFieldState, resetVgs, onSuccessRef, onErrorRef } = useVgsCollect();
	const shippingId = shippingAddress?.id ?? null;
	const dedupedSavedAddresses = useMemo(() => shippingId === null ? savedAddresses : savedAddresses.filter((a) => a.id !== shippingId), [savedAddresses, shippingId]);
	const allAddresses = useMemo(() => {
		const list = [];
		if (shippingAddress) list.push(shippingAddress);
		list.push(...dedupedSavedAddresses);
		list.push(...createdAddresses);
		return list;
	}, [
		shippingAddress,
		dedupedSavedAddresses,
		createdAddresses
	]);
	const hasRealAddresses = allAddresses.length > 0;
	const initialSelection = useMemo(() => {
		if (shippingAddress) return shippingAddress.id.toString();
		if (defaultBillingAddressId && dedupedSavedAddresses.some((a) => a.id === defaultBillingAddressId)) return defaultBillingAddressId.toString();
		const first = dedupedSavedAddresses[0];
		if (first) return first.id.toString();
		return SENTINEL_CREATE_NEW;
	}, [
		shippingAddress,
		defaultBillingAddressId,
		dedupedSavedAddresses
	]);
	const { control, handleSubmit, reset, setValue, watch } = useZodForm(formSchema, { defaultValues: {
		billing_address_selection: initialSelection,
		set_as_default: false
	} });
	useEffect(() => {
		if (isOpen) {
			reset({
				billing_address_selection: initialSelection,
				set_as_default: false
			});
			setCreatedAddresses([]);
		}
	}, [
		isOpen,
		initialSelection,
		reset
	]);
	const currentSelection = watch("billing_address_selection");
	const setAsDefault = watch("set_as_default");
	const selectedAddress = useMemo(() => {
		if (!currentSelection || currentSelection === SENTINEL_CREATE_NEW) return null;
		const id = Number(currentSelection);
		if (!Number.isFinite(id)) return null;
		return allAddresses.find((a) => a.id === id) ?? null;
	}, [currentSelection, allAddresses]);
	const selectOptions = useMemo(() => {
		const options = [];
		if (shippingAddress) options.push({
			name: t("same_as_shipping"),
			value: shippingAddress.id.toString()
		});
		for (const addr of dedupedSavedAddresses) options.push({
			name: formatAddressOneLine(addr),
			value: addr.id.toString()
		});
		for (const addr of createdAddresses) options.push({
			name: formatAddressOneLine(addr),
			value: addr.id.toString()
		});
		options.push({
			name: t("use_a_different_address"),
			value: SENTINEL_CREATE_NEW
		});
		return options;
	}, [
		shippingAddress,
		dedupedSavedAddresses,
		createdAddresses,
		t
	]);
	const handleSelectionChange = useCallback((value) => {
		if (value === SENTINEL_CREATE_NEW) {
			setIsAddressDialogOpen(true);
			return;
		}
		setValue("billing_address_selection", value, { shouldValidate: true });
	}, [setValue]);
	const handleAddressCreated = useCallback((address) => {
		setCreatedAddresses((list) => [...list, address]);
		setValue("billing_address_selection", address.id.toString(), { shouldValidate: true });
		setIsAddressDialogOpen(false);
	}, [setValue]);
	const handleVgsSuccess = useCallback((response) => {
		const expValue = response?.card_exp;
		if (!expValue) {
			setCardError("Missing expiration date from payment form");
			setIsVgsSubmitting(false);
			return;
		}
		const [expMonth, expYearShort] = expValue.replace(/\s+/g, "").split("/");
		if (!expMonth || !expYearShort) {
			setCardError("Invalid expiration date format");
			setIsVgsSubmitting(false);
			return;
		}
		const expYear = expYearShort.length === 2 ? `20${expYearShort}` : expYearShort;
		const cardholderName = response?.card_holder?.trim();
		if (!cardholderName) {
			setCardError("Cardholder name is required");
			setIsVgsSubmitting(false);
			return;
		}
		handleSubmit((formData) => {
			const billingAddressId = Number(formData.billing_address_selection);
			if (!Number.isFinite(billingAddressId)) {
				setCardError("Please select a billing address.");
				setIsVgsSubmitting(false);
				return;
			}
			const cardMeta = vgsFieldState["card_number"];
			onSubmit({
				set_as_default: formData.set_as_default,
				payment_method: {
					token: response.card_number,
					cvv_token: response.card_cvc,
					exp_month: expMonth,
					exp_year: expYear,
					card_holder: cardholderName,
					...cardMeta?.bin ? { bin: cardMeta.bin } : {},
					...cardMeta?.last4 ? { last_four: cardMeta.last4 } : {},
					...cardMeta?.cardType ? { card_network: cardMeta.cardType } : {}
				},
				billing_address_id: billingAddressId
			});
			setIsVgsSubmitting(false);
		}, () => {
			setCardError("Please select a billing address.");
			setIsVgsSubmitting(false);
		})();
	}, [
		handleSubmit,
		onSubmit,
		vgsFieldState
	]);
	const handleVgsError = useCallback((err) => {
		setCardError(err);
		setIsVgsSubmitting(false);
	}, []);
	useEffect(() => {
		onSuccessRef.current = handleVgsSuccess;
		onErrorRef.current = handleVgsError;
	}, [
		handleVgsSuccess,
		handleVgsError,
		onSuccessRef,
		onErrorRef
	]);
	useEffect(() => {
		if (!isOpen || !isScriptLoaded) return;
		let cancelled = false;
		const init = async () => {
			try {
				const credentials = await api.vault.fetchCredentials(jwt);
				if (!cancelled) await initializeForm(credentials);
			} catch (err) {
				console.error("Failed to fetch vault credentials:", err);
				if (!cancelled) setCardError("Failed to initialize payment form");
			}
		};
		init();
		return () => {
			cancelled = true;
		};
	}, [
		isOpen,
		isScriptLoaded,
		jwt,
		api,
		initializeForm
	]);
	const handleClose = () => {
		resetVgs();
		reset();
		setCardError(void 0);
		setIsVgsSubmitting(false);
		setIsAddressDialogOpen(false);
		onClose();
	};
	const handleFormSubmit = handleSubmit(() => {
		setIsVgsSubmitting(true);
		setCardError(void 0);
		submitCard();
	});
	const isBusy = isSubmitting || isVgsSubmitting;
	return /* @__PURE__ */ jsxs(Fragment$1, { children: [/* @__PURE__ */ jsx(Dialog, {
		open: isOpen,
		onOpenChange: (open) => !open && handleClose(),
		children: /* @__PURE__ */ jsx(DialogContent, {
			className: "max-h-[90vh] max-w-md overflow-y-auto p-0 md:max-w-xl",
			children: /* @__PURE__ */ jsxs("div", {
				className: "relative min-w-0 p-6",
				children: [
					(isVgsLoading || !isFormReady) && !scriptLoadError && /* @__PURE__ */ jsx("div", {
						className: "bg-background/80 absolute inset-0 z-10 flex items-center justify-center rounded backdrop-blur-[1px]",
						children: /* @__PURE__ */ jsxs("div", {
							className: "flex items-center justify-center",
							children: [/* @__PURE__ */ jsx("div", { className: "border-primary mr-3 size-5 animate-spin rounded-full border-2 border-t-2 border-t-transparent" }), /* @__PURE__ */ jsx("p", {
								className: "text-muted-foreground text-sm font-medium",
								children: t("securing")
							})]
						})
					}),
					/* @__PURE__ */ jsx(DialogHeader, { children: /* @__PURE__ */ jsx(DialogTitle, { children: t("add_credit_card") }) }),
					/* @__PURE__ */ jsxs("div", {
						className: "space-y-4 pt-6",
						children: [/* @__PURE__ */ jsx(VgsCardForm, {
							vgsFieldState,
							networkError: cardError ?? scriptLoadError ?? error
						}), /* @__PURE__ */ jsxs("div", {
							className: "space-y-3 pt-2",
							children: [
								/* @__PURE__ */ jsx("h3", {
									className: "text-muted-foreground text-sm font-medium",
									children: t("billing_address")
								}),
								hasRealAddresses ? /* @__PURE__ */ jsx(Controller, {
									control,
									name: "billing_address_selection",
									render: ({ field: { value }, fieldState: { error: fieldError } }) => /* @__PURE__ */ jsxs("div", {
										className: "space-y-1",
										children: [
											/* @__PURE__ */ jsx(Label, {
												htmlFor: "billing-address-selection",
												className: "mb-1.5 block text-sm font-medium",
												children: t("billing_address")
											}),
											/* @__PURE__ */ jsxs(Select, {
												value,
												onValueChange: handleSelectionChange,
												disabled: isBusy,
												children: [/* @__PURE__ */ jsx(SelectTrigger, {
													id: "billing-address-selection",
													"aria-invalid": !!fieldError,
													className: "w-full min-w-0 [&>span]:block! [&>span]:min-w-0 [&>span]:truncate",
													children: /* @__PURE__ */ jsx(SelectValue, { placeholder: t("select_an_option") })
												}), /* @__PURE__ */ jsx(SelectContent, { children: selectOptions.map((opt) => /* @__PURE__ */ jsx(SelectItem, {
													value: opt.value,
													onClick: opt.value === SENTINEL_CREATE_NEW ? () => setIsAddressDialogOpen(true) : void 0,
													children: opt.name
												}, opt.value)) })]
											}),
											fieldError?.message && /* @__PURE__ */ jsx("p", {
												className: "text-destructive text-sm",
												children: fieldError.message
											})
										]
									})
								}) : /* @__PURE__ */ jsx(Button, {
									type: "button",
									variant: "outline",
									onClick: () => setIsAddressDialogOpen(true),
									disabled: isBusy,
									className: "w-full",
									children: t("add_billing_address")
								}),
								selectedAddress && /* @__PURE__ */ jsx(AddressSummaryCard, { address: selectedAddress })
							]
						})]
					}),
					/* @__PURE__ */ jsxs("div", {
						className: "mt-4 flex items-center justify-between",
						children: [/* @__PURE__ */ jsxs("div", {
							className: "flex items-center gap-x-2",
							children: [/* @__PURE__ */ jsx("input", {
								type: "checkbox",
								id: "set_as_default_cc",
								checked: setAsDefault,
								onChange: () => setValue("set_as_default", !setAsDefault),
								disabled: isBusy,
								className: "size-4"
							}), /* @__PURE__ */ jsx("label", {
								htmlFor: "set_as_default_cc",
								className: "text-sm",
								children: t("set_as_default_payment_method")
							})]
						}), /* @__PURE__ */ jsxs(Button, {
							type: "button",
							onClick: handleFormSubmit,
							disabled: isBusy,
							children: [isBusy && /* @__PURE__ */ jsx("div", { className: "mr-2 size-4 animate-spin rounded-full border-2 border-current/30 border-t-current" }), isBusy ? t("saving") : t("save_card")]
						})]
					})
				]
			})
		})
	}), renderAddressFormDialog?.({
		isOpen: isAddressDialogOpen,
		onClose: () => setIsAddressDialogOpen(false),
		onAddressCreated: handleAddressCreated
	})] });
}
//#endregion
//#region ../../fluid-pay/ui/src/components/VgsThreeDSModal.tsx
function escapeAttr(s) {
	return (s ?? "").replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
}
/**
* Parse the challenge HTML to extract the form action URL and hidden fields.
* This lets us POST directly to the bank ACS, bypassing intermediary pages
* (e.g. Entersekt's red.js auto-submit) that cause extra iframe loads.
*/
function parseDirectPostHtml(challengeHtml, challengeUrl) {
	try {
		const form = new DOMParser().parseFromString(challengeHtml, "text/html").querySelector("form");
		if (!form) return null;
		const action = challengeUrl || form.getAttribute("action");
		if (!action) return null;
		const hiddenInputs = form.querySelectorAll("input[type=\"hidden\"]");
		if (hiddenInputs.length === 0) return null;
		const fieldsHtml = Array.from(hiddenInputs).map((input) => `<input type="hidden" name="${escapeAttr(input.getAttribute("name"))}" value="${escapeAttr(input.getAttribute("value"))}">`).join("\n");
		return `<!DOCTYPE html>
<html>
<body>
<form id="acsForm" method="POST" action="${escapeAttr(action)}">
${fieldsHtml}
</form>
<script>document.getElementById("acsForm").submit();<\/script>
</body>
</html>`;
	} catch {
		return null;
	}
}
/**
* Pure iframe container for the 3DS challenge.
*
* The modal does NOT try to detect challenge completion via load-counting or
* postMessage — that was fragile across different bank ACS implementations.
* Instead, `useVgs3DSCompletion` subscribes to the realtime transport as soon
* as the modal opens and receives the authoritative result from the backend.
*
* This modal only handles:
* - Rendering the ACS challenge iframe
* - User cancellation (Cancel button in header band)
* - Hard timeout (6.5 min) as a safety net
*/
function VgsThreeDSModal({ isOpen, challengeHtml, challengeUrl, onClose, labels }) {
	const iframeRef = useRef(null);
	const onCloseRef = useRef(onClose);
	const labelsRef = useRef(labels);
	useEffect(() => {
		onCloseRef.current = onClose;
	});
	useEffect(() => {
		labelsRef.current = labels;
	});
	const iframeSrcDoc = useMemo(() => parseDirectPostHtml(challengeHtml, challengeUrl) ?? challengeHtml, [challengeHtml, challengeUrl]);
	useEffect(() => {
		if (!isOpen) return;
		const timeoutId = setTimeout(() => {
			onCloseRef.current(labelsRef.current.timedOut);
		}, 39e4);
		return () => {
			clearTimeout(timeoutId);
		};
	}, [isOpen]);
	const handleCancel = () => {
		onClose();
	};
	return /* @__PURE__ */ jsx(Dialog, {
		open: isOpen,
		onOpenChange: handleCancel,
		children: /* @__PURE__ */ jsx(DialogContent, {
			className: "z-[110] h-[600px] max-w-2xl p-0 sm:max-w-2xl",
			overlayClassName: "z-[110]",
			showCloseButton: false,
			children: /* @__PURE__ */ jsxs("div", {
				className: "flex h-full w-full flex-col",
				children: [
					/* @__PURE__ */ jsxs("div", {
						className: "flex items-center justify-between border-b border-gray-200 px-4 py-3",
						children: [/* @__PURE__ */ jsxs("div", {
							className: "flex items-center gap-2",
							children: [/* @__PURE__ */ jsx(Lock, {
								className: "h-4 w-4 text-gray-600",
								"aria-hidden": "true"
							}), /* @__PURE__ */ jsx(DialogTitle, {
								className: "text-sm font-semibold text-gray-900",
								children: labels.title
							})]
						}), /* @__PURE__ */ jsx("button", {
							type: "button",
							onClick: handleCancel,
							className: "rounded text-xs text-indigo-600 hover:text-indigo-700 focus-visible:ring-2 focus-visible:ring-indigo-500 focus-visible:ring-offset-2 focus-visible:outline-none",
							children: labels.cancel
						})]
					}),
					/* @__PURE__ */ jsx("div", {
						className: "relative flex-1",
						children: challengeHtml && /* @__PURE__ */ jsx("iframe", {
							ref: iframeRef,
							srcDoc: iframeSrcDoc,
							className: "h-full w-full border-0",
							title: "VGS 3DS Challenge",
							sandbox: "allow-same-origin allow-scripts allow-forms allow-top-navigation allow-popups"
						})
					}),
					/* @__PURE__ */ jsxs("div", {
						className: "border-t border-gray-200 px-4 py-3",
						children: [/* @__PURE__ */ jsx("div", {
							"data-testid": "threeds-progress-bar",
							role: "progressbar",
							"aria-label": labels.stillWorking,
							className: "relative h-1 overflow-hidden rounded-full bg-indigo-100",
							children: /* @__PURE__ */ jsx("div", { className: "threeds-progress-pill absolute top-0 h-full w-[30%] rounded-full bg-indigo-500" })
						}), /* @__PURE__ */ jsxs("div", {
							className: "mt-2 flex items-center justify-between text-xs",
							children: [/* @__PURE__ */ jsx("span", {
								className: "text-gray-600",
								children: labels.stillWorking
							}), /* @__PURE__ */ jsx("span", {
								className: "text-gray-400",
								children: labels.dontRefresh
							})]
						})]
					})
				]
			})
		})
	});
}
//#endregion
//#region ../../fluid-pay/ui/src/hooks/three-ds-attempt.ts
function belongsToActiveAttempt(activeMerchantTxId, resultMerchantTxId) {
	if (!activeMerchantTxId || !resultMerchantTxId) return true;
	return resultMerchantTxId === activeMerchantTxId;
}
//#endregion
//#region ../../fluid-pay/ui/src/hooks/use-vgs-3ds-completion.ts
const POLL_INTERVAL_MS = 3e3;
const TIMEOUT_MS = 39e4;
/**
* Subscribes to the realtime transport and polls the injected status check
* for the 3DS challenge result.
*
* Activated by `enabled` — pass `vgsThreeDSModal.isOpen` so the subscription
* starts as soon as the challenge modal opens. No URL-param dance needed.
*/
function useVgs3DSCompletion({ channelName, transport, checkStatus, onComplete, onError, enabled = false, merchantTxId, onCanceled }) {
	const hasHandledRef = useRef(false);
	const isSubscribedRef = useRef(false);
	const transportRef = useRef(transport);
	useEffect(() => {
		transportRef.current = transport;
	});
	const handleComplete = useEffectEvent((result) => {
		onComplete(result);
	});
	const handleError = useEffectEvent((error) => {
		onError(error);
	});
	const handleCanceled = useEffectEvent(() => {
		onCanceled?.();
	});
	const performStatusCheck = useEffectEvent(() => checkStatus());
	const handleResult = useEffectEvent((result) => {
		if (hasHandledRef.current) return;
		hasHandledRef.current = true;
		if (result.status === "success") handleComplete({
			success: true,
			transactionId: result.transactionId ?? "",
			status: result.status
		});
		else handleError(result.errorMessage || "3DS verification failed");
	});
	useEffect(() => {
		if (!enabled && hasHandledRef.current) hasHandledRef.current = false;
	}, [enabled]);
	useEffect(() => {
		if (!enabled || !channelName || hasHandledRef.current) return;
		if (isSubscribedRef.current) return;
		let cancelled = false;
		const activeTransport = transportRef.current;
		isSubscribedRef.current = true;
		const channel = activeTransport.subscribe(channelName);
		const hasPusher = !!channel;
		if (!hasPusher) {
			console.error("[VGS 3DS] Pusher subscribe returned null — using status polling only");
			isSubscribedRef.current = false;
		}
		const handleVgs3DSChallenge = (data) => {
			if (cancelled) return;
			if (!belongsToActiveAttempt(merchantTxId, data.merchant_transaction_id)) return;
			handleResult({
				status: data.status,
				errorMessage: data.error_message,
				transactionId: data.merchant_transaction_id
			});
		};
		if (hasPusher) channel.bind("vgs_3ds_challenge", handleVgs3DSChallenge);
		const pollInterval = setInterval(async () => {
			if (hasHandledRef.current || cancelled) return;
			const status = await performStatusCheck();
			if (cancelled || !status) return;
			if (!belongsToActiveAttempt(merchantTxId, status.merchantTxId)) return;
			if (status.completed) handleResult({ status: "success" });
			else if (status.failed) handleResult({
				status: "failed",
				errorMessage: status.errorMessage || `3DS verification ${status.status || "failed"}`
			});
			else if (status.canceled) {
				if (!hasHandledRef.current) {
					hasHandledRef.current = true;
					handleCanceled();
				}
			}
		}, POLL_INTERVAL_MS);
		const timeout = setTimeout(() => {
			if (hasHandledRef.current || cancelled) return;
			console.error("[VGS 3DS] Timed out waiting for 3DS result");
			handleResult({
				status: "failed",
				errorMessage: "Payment verification timed out. Please try again."
			});
		}, TIMEOUT_MS);
		return () => {
			cancelled = true;
			clearTimeout(timeout);
			clearInterval(pollInterval);
			if (hasPusher) {
				channel.unbind("vgs_3ds_challenge", handleVgs3DSChallenge);
				activeTransport.unsubscribe(channelName);
			}
			isSubscribedRef.current = false;
		};
	}, [
		enabled,
		channelName,
		merchantTxId
	]);
}
z.object({
	color_depth: z.number().optional(),
	screen_height: z.number().optional(),
	screen_width: z.number().optional(),
	time_zone: z.number().optional(),
	java_enabled: z.boolean().optional(),
	java_script_enabled: z.boolean().optional(),
	language: z.string().optional(),
	user_agent: z.string().optional(),
	accept_header: z.string().optional()
});
function getBrowserInfo() {
	if (typeof window === "undefined") {
		console.warn("getBrowserInfo called in non-browser environment");
		return;
	}
	try {
		const { screen, navigator } = window;
		if (!screen || !navigator) {
			console.warn("Missing screen or navigator objects");
			return;
		}
		const browserInfo = {
			color_depth: screen.colorDepth || void 0,
			screen_height: screen.height || void 0,
			screen_width: screen.width || void 0,
			time_zone: (/* @__PURE__ */ new Date()).getTimezoneOffset(),
			java_enabled: typeof navigator.javaEnabled === "function" ? navigator.javaEnabled() : false,
			java_script_enabled: true,
			language: navigator.language || void 0,
			user_agent: navigator.userAgent || void 0,
			accept_header: "*/*"
		};
		if (!browserInfo.screen_height || !browserInfo.screen_width || !browserInfo.user_agent) console.warn("Missing essential browser info fields");
		return browserInfo;
	} catch (error) {
		console.error("Error getting browser info:", error);
		return;
	}
}
//#endregion
//#region ../core/src/pay-types.ts
function isThreeDsRequiredCreate(r) {
	return "three_ds" in r && r.three_ds.status === "three_ds_required";
}
//#endregion
//#region src/adapters/fluid-pay-api-adapter.ts
/**
* Maps a portal-tenant PayPaymentMethod to the fluidPay shape consumed by
* profile-ui components (PaymentMethodDropdown, CreditCardFormDialog, etc.).
* Co-located with the adapter because both speak the portal-tenant ↔ fluid-pay
* boundary.
*/
function mapToFluidPayPaymentMethod(raw) {
	return {
		id: raw.id,
		created_at: raw.created_at ?? "",
		default: raw.default,
		details: {
			card_network: raw.brand,
			card_brand: raw.brand,
			card_holder: raw.card_holder,
			last_four: raw.last_four,
			logo_url: raw.logo_url ?? void 0,
			exp_month: raw.exp_month ?? void 0,
			exp_year: raw.exp_year ?? void 0
		},
		billing_address: raw.billing_address ? {
			name: raw.billing_address.name,
			address1: raw.billing_address.street1,
			address2: raw.billing_address.street2,
			city: raw.billing_address.city,
			state: raw.billing_address.state,
			zip: raw.billing_address.zip,
			country_code: raw.billing_address.country
		} : null,
		payment_type: raw.type,
		source: "",
		updated_at: raw.updated_at ?? ""
	};
}
const notImplemented = () => {
	throw new Error("Not available in portal-tenant context");
};
/**
* Adapts the portal-tenant PayApi to the FluidPayApi shape required by
* FluidPayCoreProvider. Only `vault.fetchCredentials` is implemented —
* the rest of the FluidPayApi surface is not used by the profile-ui
* components that consume this provider in the portal context.
*/
function createFluidPayApiAdapter(payApi) {
	return {
		customers: {
			fetchAccount: notImplemented,
			update: notImplemented
		},
		addresses: {
			fetchAll: notImplemented,
			create: notImplemented,
			update: notImplemented,
			delete: notImplemented
		},
		paymentMethods: {
			fetchAll: notImplemented,
			addCreditCard: notImplemented,
			delete: notImplemented,
			updateDefault: notImplemented,
			update: notImplemented
		},
		vault: { fetchCredentials: async () => {
			const response = await payApi.fetchVaultCredentials();
			return {
				vault: {
					vault_id: response.vault.vault_id,
					environment: response.vault.environment,
					route_id: response.vault.route_id ?? "",
					requires_3ds: false
				},
				meta: {
					request_id: response.meta?.request_id ?? "",
					timestamp: response.meta?.timestamp ?? ""
				}
			};
		} }
	};
}
//#endregion
//#region ../../platform/address-autocomplete/src/administrative-area.ts
function normalize(value) {
	return value.trim().toLowerCase();
}
function firstPresent(...values) {
	return values.find((value) => value && value.trim() !== "") ?? "";
}
function findStateByIsoCode(stateOptions, value) {
	const normalizedValue = normalize(value);
	if (!normalizedValue) return void 0;
	return stateOptions.find((state) => normalize(state.isoCode) === normalizedValue);
}
function findStateByName(stateOptions, value) {
	const normalizedValue = normalize(value);
	if (!normalizedValue) return void 0;
	return stateOptions.find((state) => normalize(state.name) === normalizedValue);
}
function resolveAdministrativeAreaState(details, stateOptions = []) {
	const displayValue = firstPresent(details.state, details.administrativeAreaLong, details.administrativeAreaShort);
	if (stateOptions.length === 0) return displayValue;
	const candidates = [
		details.administrativeAreaShort,
		details.state,
		details.administrativeAreaLong
	].filter((value) => Boolean(value));
	for (const candidate of candidates) {
		const state = findStateByIsoCode(stateOptions, candidate) ?? findStateByName(stateOptions, candidate);
		if (state) return state.isoCode;
	}
	return displayValue;
}
//#endregion
//#region ../../platform/address-autocomplete/src/components/AddressAutocompleteInput.tsx
const SET_OPTS = {
	shouldValidate: true,
	shouldDirty: true,
	shouldTouch: true
};
const DEBOUNCE_MS = 250;
const EMPTY_STATE_OPTIONS = [];
function AddressAutocompleteInput({ control, setValue, countryIso, addressLineField, cityField, stateField, postalCodeField, stateOptions = EMPTY_STATE_OPTIONS, id, label, placeholder, disabled }) {
	const api = useAddressAutocompleteApi();
	const { field, fieldState: { error } } = useController({
		name: addressLineField,
		control
	});
	const [suggestions, setSuggestions] = useState([]);
	const [isOpen, setIsOpen] = useState(false);
	const [needsCountry, setNeedsCountry] = useState(false);
	const containerRef = useRef(null);
	const requestIdRef = useRef(0);
	const debounceTimerRef = useRef(null);
	const isCountrySelected = useMemo(() => Boolean(countryIso && countryIso.trim() !== ""), [countryIso]);
	const inputId = id ?? addressLineField;
	useEffect(() => {
		function onClickOutside(e) {
			if (containerRef.current && !containerRef.current.contains(e.target)) {
				setIsOpen(false);
				setNeedsCountry(false);
			}
		}
		document.addEventListener("mousedown", onClickOutside);
		return () => document.removeEventListener("mousedown", onClickOutside);
	}, []);
	useEffect(() => () => {
		if (debounceTimerRef.current !== null) clearTimeout(debounceTimerRef.current);
	}, []);
	const populate = useCallback((s) => {
		setValue(addressLineField, s.streetLine, SET_OPTS);
		setValue(cityField, s.city, SET_OPTS);
		setValue(stateField, resolveAdministrativeAreaState(s, stateOptions), SET_OPTS);
		setValue(postalCodeField, s.postalCode, SET_OPTS);
	}, [
		addressLineField,
		cityField,
		postalCodeField,
		setValue,
		stateField,
		stateOptions
	]);
	const handleChange = useCallback((e) => {
		const value = e.target.value;
		field.onChange(value);
		if (debounceTimerRef.current !== null) {
			clearTimeout(debounceTimerRef.current);
			debounceTimerRef.current = null;
		}
		if (value.length < 1) {
			setIsOpen(false);
			setNeedsCountry(false);
			setSuggestions([]);
			return;
		}
		if (!isCountrySelected) {
			setNeedsCountry(true);
			setIsOpen(true);
			return;
		}
		setNeedsCountry(false);
		const requestId = ++requestIdRef.current;
		debounceTimerRef.current = setTimeout(() => {
			debounceTimerRef.current = null;
			api.fetchSuggestions({
				query: value,
				countryIso
			}).then((next) => {
				if (requestId !== requestIdRef.current) return;
				setSuggestions(next);
				setIsOpen(true);
			});
		}, DEBOUNCE_MS);
	}, [
		api,
		countryIso,
		field,
		isCountrySelected
	]);
	const handleClick = useCallback(async (suggestion) => {
		if (debounceTimerRef.current !== null) {
			clearTimeout(debounceTimerRef.current);
			debounceTimerRef.current = null;
		}
		const clickId = ++requestIdRef.current;
		if (!suggestion.needsDetailLookup) {
			populate({
				streetLine: suggestion.streetLine ?? suggestion.text,
				city: suggestion.city ?? "",
				state: suggestion.state ?? "",
				postalCode: suggestion.postalCode ?? ""
			});
			setIsOpen(false);
			return;
		}
		const { details, drilldownSuggestions } = await api.fetchDetails({
			suggestion,
			countryIso
		});
		if (clickId !== requestIdRef.current) return;
		if (details) {
			populate(details);
			setIsOpen(false);
			return;
		}
		setSuggestions(drilldownSuggestions);
		setIsOpen(true);
	}, [
		api,
		countryIso,
		populate
	]);
	return /* @__PURE__ */ jsxs("div", {
		className: "space-y-1",
		children: [
			label && /* @__PURE__ */ jsx(Label, {
				htmlFor: inputId,
				className: "mb-1.5 block text-sm font-medium",
				children: label
			}),
			/* @__PURE__ */ jsxs("div", {
				ref: containerRef,
				className: "relative",
				children: [
					/* @__PURE__ */ jsx(Input, {
						id: inputId,
						type: "text",
						ref: field.ref,
						value: field.value ?? "",
						onChange: handleChange,
						onBlur: field.onBlur,
						placeholder,
						disabled,
						"aria-invalid": !!error
					}),
					isOpen && needsCountry && /* @__PURE__ */ jsx("div", {
						className: "bg-muted text-foreground absolute z-50 mt-1 w-full rounded-md px-3 py-2 text-sm shadow-lg",
						children: "Please select a country first to enable address suggestions"
					}),
					isOpen && !needsCountry && suggestions.length > 0 && /* @__PURE__ */ jsx("div", {
						className: "bg-background text-foreground border-border absolute z-50 mt-1 max-h-60 w-full overflow-y-auto rounded-md border shadow-lg",
						children: suggestions.map((s) => /* @__PURE__ */ jsxs("button", {
							type: "button",
							onClick: () => {
								handleClick(s).catch((err) => {
									console.error("Address autocomplete click failed:", err);
								});
							},
							className: "hover:bg-muted block w-full cursor-pointer px-3 py-2 text-left text-sm",
							children: [s.text, s.needsDetailLookup ? " →" : ""]
						}, s.id))
					})
				]
			}),
			error?.message && /* @__PURE__ */ jsx("p", {
				className: "text-destructive text-sm",
				children: error.message
			})
		]
	});
}
//#endregion
//#region ../../fluid-pay/core/src/utils/fingerprinting.ts
const renderFingerprintingIframe = (html) => {
	return new Promise((resolve) => {
		const iframe = document.createElement("iframe");
		iframe.srcdoc = html;
		iframe.style.display = "none";
		document.body.appendChild(iframe);
		setTimeout(() => {
			document.body.removeChild(iframe);
			resolve();
		}, 1e4);
	});
};
//#endregion
//#region src/hooks/three-ds-card-add-helpers.ts
/**
* Polling-only realtime transport. A no-op channel keeps useVgs3DSCompletion's
* `hasPusher` true so it does not log the misleading "subscribe returned null"
* error; the 3s status poll is the sole resolver. The Pusher fast-follow
* replaces this constant with a real pusher-js client.
*/
const POLLING_ONLY_TRANSPORT = {
	subscribe: () => ({
		bind: () => {},
		unbind: () => {}
	}),
	unsubscribe: () => {}
};
/**
* Map the BFF 3ds_status session state -> the FE-A hook's ThreeDSStatus. Only
* the known terminal states resolve the poll (approved/skipped -> completed,
* denied/timed_out/expired -> failed, cancelled -> canceled); any other value
* (initialized/pending or a future backend state) stays non-terminal so the
* poll keeps running until the EMVCo timeout, rather than being mis-classified.
*/
function mapSessionStateToThreeDSStatus(state, expired) {
	return {
		completed: state === "approved" || state === "skipped",
		failed: state === "denied" || state === "timed_out" || expired === true,
		canceled: state === "cancelled",
		status: state
	};
}
/**
* Dig the portal BFF error code off a thrown ApiError. Structural and
* self-validating: a non-ApiError simply yields undefined (no instanceof gate).
*/
function cardAdd3DSErrorCode(error) {
	const code = ((error?.data)?.meta)?.error_code;
	return typeof code === "string" ? code : void 0;
}
/**
* Customer-facing message off a thrown portal ApiError. The client lifts the
* portal `{ error: { message } }` onto ApiError.message; fall back to the
* nested field, then the supplied generic. (`data.error_message` is the
* storefront shape and is always undefined here.)
*/
function cardAdd3DSErrorMessage(error, fallback) {
	if (error instanceof Error && error.message) return error.message;
	const nested = (error?.data)?.error?.message;
	return typeof nested === "string" ? nested : fallback;
}
//#endregion
//#region src/hooks/use-portal-card-add-3ds-flow.tsx
const PENDING_RETRY_DELAY_MS = 2e3;
const waitFor = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
function usePortalCardAdd3DSFlow({ payApi, onApproved, onFailed, onCanceled, t }) {
	const [session, setSession] = useState(null);
	const [challenge, setChallenge] = useState(null);
	const activeSessionRef = useRef(null);
	const emitApproved = useEffectEvent((approved) => onApproved(approved));
	const emitFailed = useEffectEvent((message) => onFailed(message));
	const emitCanceled = useEffectEvent(() => onCanceled());
	const resetFlow = () => {
		activeSessionRef.current = null;
		setSession(null);
		setChallenge(null);
	};
	const finishApproved = async (approved) => {
		if (!activeSessionRef.current) return;
		resetFlow();
		await emitApproved(approved);
	};
	const finishFailed = (message) => {
		if (!activeSessionRef.current) return;
		resetFlow();
		emitFailed(message);
	};
	const finishCanceled = () => {
		if (!activeSessionRef.current) return;
		resetFlow();
		emitCanceled();
	};
	const failureMessageFrom = (error) => {
		if (cardAdd3DSErrorCode(error) === "three_ds_session_not_found") return t("payment_verification_timed_out");
		return cardAdd3DSErrorMessage(error, t("payment_verification_didnt_complete"));
	};
	const begin = async (created) => {
		if (activeSessionRef.current) return;
		const { session_token, merchant_tx_id, fingerprinting_required, tds_method_content } = created.three_ds;
		if (!session_token) {
			emitFailed(t("payment_verification_didnt_complete"));
			return;
		}
		const active = {
			sessionToken: session_token,
			merchantTxId: merchant_tx_id ?? void 0
		};
		activeSessionRef.current = active;
		setSession(active);
		try {
			if (fingerprinting_required !== false && typeof tds_method_content === "string" && tds_method_content.length > 0) await renderFingerprintingIframe(tds_method_content);
			const confirmation = await payApi.confirmPaymentMethod3DS({ session_token: active.sessionToken });
			if (confirmation.status === "approved") {
				await finishApproved(confirmation);
				return;
			}
			if (!confirmation.challenge_form) {
				finishFailed(t("payment_verification_didnt_complete"));
				return;
			}
			setChallenge({
				html: confirmation.challenge_form,
				url: confirmation.challenge_url ?? void 0
			});
		} catch (error) {
			finishFailed(failureMessageFrom(error));
		}
	};
	const reconfirmAfterSignal = async (allowPendingRetry) => {
		const active = activeSessionRef.current;
		if (!active) return;
		try {
			const confirmation = await payApi.confirmPaymentMethod3DS({ session_token: active.sessionToken });
			if (activeSessionRef.current !== active) return;
			if (confirmation.status === "approved") {
				await finishApproved(confirmation);
				return;
			}
			finishFailed(t("payment_verification_didnt_complete"));
		} catch (error) {
			if (activeSessionRef.current !== active) return;
			if (allowPendingRetry && cardAdd3DSErrorCode(error) === "three_ds_pending") {
				await waitFor(PENDING_RETRY_DELAY_MS);
				if (activeSessionRef.current !== active) return;
				await reconfirmAfterSignal(false);
				return;
			}
			finishFailed(failureMessageFrom(error));
		}
	};
	const sessionStatusSnapshot = async () => {
		const active = activeSessionRef.current;
		if (!active) return null;
		try {
			const snapshot = await payApi.fetchPaymentMethod3DSStatus({ session_token: active.sessionToken });
			return mapSessionStateToThreeDSStatus(snapshot.state, snapshot.expired);
		} catch {
			return null;
		}
	};
	useVgs3DSCompletion({
		channelName: session ? `private-3ds-session-${session.sessionToken}` : "",
		transport: POLLING_ONLY_TRANSPORT,
		checkStatus: sessionStatusSnapshot,
		merchantTxId: session?.merchantTxId,
		enabled: challenge !== null,
		onComplete: () => {
			reconfirmAfterSignal(true);
		},
		onError: (message) => finishFailed(message),
		onCanceled: finishCanceled
	});
	const closeChallengeModal = (timeoutError) => {
		const active = activeSessionRef.current;
		if (active) payApi.cancelPaymentMethod3DS({ session_token: active.sessionToken }).catch(() => {});
		if (timeoutError) finishFailed(timeoutError);
		else finishCanceled();
	};
	return {
		begin,
		modal: /* @__PURE__ */ jsx(VgsThreeDSModal, {
			isOpen: challenge !== null,
			challengeHtml: challenge?.html ?? "",
			challengeUrl: challenge?.url,
			onClose: closeChallengeModal,
			labels: {
				title: t("verify_your_payment"),
				cancel: t("cancel"),
				timedOut: t("payment_verification_timed_out"),
				stillWorking: t("still_working_with_your_bank"),
				dontRefresh: t("dont_refresh_this_tab")
			}
		}),
		isActive: session !== null
	};
}
//#endregion
export { EllipsesDropdown as _, isThreeDsRequiredCreate as a, AddressFormDialog as c, PaymentIcon as d, getCardDisplayName as f, ConfirmActionDialog as g, UserInfoDialog as h, mapToFluidPayPaymentMethod as i, EditPaymentMethodDialog as l, getPaymentMethodLogoBrand as m, AddressAutocompleteInput as n, getBrowserInfo as o, getCardExpiry as p, createFluidPayApiAdapter as r, CreditCardFormDialog as s, usePortalCardAdd3DSFlow as t, FluidPayCoreProvider as u, ProfileTranslationBridge as v, useProfileTranslation as y };

//# sourceMappingURL=use-portal-card-add-3ds-flow-Ddn35rRp.mjs.map