import { n as useAddressAutocompleteApi } from "./api-context-3GmfqvIB.mjs";
import { $ as DropdownMenuSeparator, A as Select, An as cn, En as Button, J as DropdownMenuContent, K as Label, L as Input, M as SelectItem, N as SelectTrigger, P as SelectValue, Y as DropdownMenuItem, at as DialogClose, ct as DialogFooter, ft as DialogTitle, it as Dialog, j as SelectContent, kn as useZodForm, lt as DialogHeader, ot as DialogContent, q as DropdownMenu, rt as DropdownMenuTrigger, s as Textarea } from "./src-B3W228vu.mjs";
import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from "react";
import "@tanstack/react-query";
import { Fragment as Fragment$1, jsx, jsxs } from "react/jsx-runtime";
import { Info, Trash2 } from "lucide-react";
import { Controller, useController, useWatch } from "react-hook-form";
import { z } from "zod";
//#region ../../profile/core/src/context.ts
const ProfileUIContext = createContext(null);
function useProfileUI() {
	const context = useContext(ProfileUIContext);
	if (!context) throw new Error("useProfileUI must be used within a ProfileUIProvider");
	return context;
}
//#endregion
//#region ../../profile/core/src/provider.tsx
function ProfileUIProvider({ t, children }) {
	const value = useMemo(() => ({ t }), [t]);
	return /* @__PURE__ */ jsx(ProfileUIContext.Provider, {
		value,
		children
	});
}
//#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);
			if (selectedCountryCode === "US") setStateOptions(US_STATES);
			else if (fetchStates) fetchStates(selectedCountryCode).then((states) => setStateOptions(states)).catch((error) => {
				console.error("Failed to fetch states:", error);
				setStateOptions([]);
			});
			else setStateOptions([]);
		}, []),
		stateOptions,
		config: getRegionConfig(selectedCountry),
		selectedCountry
	};
}
//#endregion
//#region ../../profile/ui/src/components/ellipses-dropdown.tsx
function EllipsesDropdown({ onDelete, onEdit, onMakeDefault, editLabel = "Edit", deleteLabel = "Delete", makeDefaultLabel = "Make Default", disabled = false }) {
	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: "h-3.5 w-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: editLabel })]
			}), /* @__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: "h-3.5 w-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: makeDefaultLabel })]
			}), /* @__PURE__ */ jsx(DropdownMenuSeparator, {})] }),
			/* @__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: "h-3.5 w-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: deleteLabel })]
			})
		]
	})] });
}
//#endregion
//#region ../../profile/ui/src/components/confirm-action-dialog.tsx
function ConfirmActionDialog({ title, description, onAction, openDialog, setOpenDialog, errorMsg, isLoading, actionText = "Delete" }) {
	const { t } = useProfileUI();
	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 space-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 h-5 w-5 animate-spin rounded-full border-4 border-t-4 border-t-transparent" }) : actionText
					})]
				}) })
			]
		})
	});
}
//#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$1({ 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 } = useProfileUI();
	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("Please enter a new email address");
			return;
		}
		if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(trimmed)) {
			setEmailError("Please enter a valid email address");
			return;
		}
		if (email && trimmed.toLowerCase() === email.toLowerCase()) {
			setEmailError("New email must be different from your current email");
			return;
		}
		try {
			await onChangeEmail?.(trimmed);
			setIsEditingEmail(false);
			setNewEmail("");
		} catch (err) {
			setEmailError(err instanceof Error ? err.message : "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$1, {
							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") || "Email"
					}), isEditingEmail ? /* @__PURE__ */ jsxs("div", {
						className: "space-y-2",
						children: [
							/* @__PURE__ */ jsx(Input, {
								type: "email",
								placeholder: "Enter your new email...",
								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 h-4 w-4 shrink-0" }), /* @__PURE__ */ jsx("p", {
									className: "text-muted-foreground text-xs",
									children: "We'll send a verification link to your new email. Click it to complete the change."
								})]
							}),
							/* @__PURE__ */ jsxs("div", {
								className: "flex gap-2",
								children: [/* @__PURE__ */ jsx(Button, {
									type: "button",
									variant: "outline",
									size: "sm",
									onClick: handleCancelEmailEdit,
									children: "Cancel"
								}), /* @__PURE__ */ jsxs(Button, {
									type: "button",
									size: "sm",
									onClick: handleEmailSubmit,
									disabled: !newEmail.trim() || isChangingEmail,
									children: [isChangingEmail && /* @__PURE__ */ jsx("div", { className: "mr-2 h-3.5 w-3.5 animate-spin rounded-full border-2 border-current/30 border-t-current" }), isChangingEmail ? "Sending..." : "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 h-4 w-4 shrink-0" }), /* @__PURE__ */ jsxs("p", {
								className: "text-muted-foreground text-xs",
								children: [
									"Changing to",
									" ",
									/* @__PURE__ */ jsx("span", {
										className: "text-foreground font-medium",
										children: pendingEmail
									}),
									". Check your new email inbox and click the verification link to complete the change."
								]
							})]
						})]
					}) : /* @__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: "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 h-4 w-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
const PAYMENT_ICON_BASE = "https://assets.fluid.app/images/payment_icons";
const GENERIC_PAYMENT_ICON = `${PAYMENT_ICON_BASE}/generic.svg`;
function brandIconUrl(brand) {
	if (!brand) return GENERIC_PAYMENT_ICON;
	return `${PAYMENT_ICON_BASE}/${brand.toLowerCase().replace(/\s+/g, "_")}.svg`;
}
function PaymentIcon({ logoUrl, brand, alt }) {
	const computedSrc = logoUrl || brandIconUrl(brand);
	const [hasError, setHasError] = useState(false);
	return /* @__PURE__ */ jsx("img", {
		src: hasError ? GENERIC_PAYMENT_ICON : computedSrc,
		alt,
		width: 40,
		height: 24,
		className: "object-contain",
		onError: () => setHasError(true)
	});
}
function getCardDisplayName(paymentMethod) {
	const lastFour = paymentMethod.details.last_four;
	if (lastFour != null || paymentMethod.payment_type === "Credit Card") return `${paymentMethod.details.card_type || "Card"} •••• ${lastFour || "••••"}`;
	return paymentMethod.payment_type;
}
function getCardExpiry(paymentMethod) {
	const { exp_month, exp_year } = paymentMethod.details;
	if (exp_month != null && exp_year != null) return `Expires ${exp_month}/${exp_year}`;
	return "";
}
//#endregion
//#region ../../profile/ui/src/components/edit-payment-method-dialog.tsx
const editPaymentMethodFormSchema = z.object({
	billing_address: z.object({
		name: z.string().min(1, "Name is required"),
		address1: z.string().min(1, "Address line 1 is required"),
		address2: z.string().optional().nullable(),
		city: z.string().min(1, "City is required"),
		state: z.string().min(1, "State is required"),
		zip: z.string().min(1, "Zip code is required"),
		country_code: z.string().min(1, "Country is required")
	}),
	set_as_default: z.boolean()
});
function EditPaymentMethodDialog({ isOpen, paymentMethod, billingAddress, onClose, onSubmit, isSubmitting, error, countries = [], onDelete, isDeleting = false }) {
	const { t } = useProfileUI();
	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(editPaymentMethodFormSchema, { 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 cardBrand = details.card_type ?? "Card";
	const lastFour = details.last_four ?? "****";
	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 space-x-3",
							children: [details.logo_url && /* @__PURE__ */ jsx("div", {
								className: "h-6 w-10 flex-shrink-0",
								children: /* @__PURE__ */ jsx("img", {
									src: details.logo_url,
									alt: cardBrand,
									width: 40,
									height: 24,
									className: "object-contain"
								})
							}), /* @__PURE__ */ jsxs("div", {
								className: "flex flex-col",
								children: [/* @__PURE__ */ jsxs("span", {
									className: "text-foreground text-sm font-medium",
									children: [
										cardBrand,
										" •••• ",
										lastFour
									]
								}), 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$1, {
								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$1, {
										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 space-x-2",
					children: [/* @__PURE__ */ jsx("input", {
						type: "checkbox",
						id: "set_as_default",
						checked: setAsDefault,
						onChange: () => setValue("set_as_default", !setAsDefault),
						className: "h-4 w-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 h-4 w-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 }) {
	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,
				"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/FormSelectField.tsx
function FormSelectField({ control, name, label, placeholder = "Select", options, containerClassName, disabled }) {
	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__ */ jsxs(Select, {
				value: value?.toString() ?? "",
				onValueChange: onChange,
				disabled,
				children: [/* @__PURE__ */ jsx(SelectTrigger, {
					id: name,
					"aria-invalid": !!error,
					className: "w-full",
					children: /* @__PURE__ */ jsx(SelectValue, { placeholder })
				}), /* @__PURE__ */ jsx(SelectContent, { children: options && options.length > 0 ? options.map((opt) => /* @__PURE__ */ jsx(SelectItem, {
					value: opt.value.toString(),
					children: opt.name
				}, opt.value.toString())) : /* @__PURE__ */ jsx(SelectItem, {
					value: "__empty",
					disabled: true,
					children: "No available options"
				}) })]
			}), 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({
	first_name: z.string().min(1, "First name is required"),
	last_name: z.string().min(1, "Last name is required"),
	address1: z.string().min(1, "Address line 1 is required"),
	address2: z.string().optional().nullable(),
	city: z.string().min(1, "City is required"),
	state: z.string().min(1, "State is required"),
	postal_code: z.string().min(1, "Postal code is required"),
	country_code: z.string().min(1, "Country is required"),
	default: z.boolean()
});
function AddressFormDialog({ isOpen, onClose, selectedAddress, onSubmit, isSubmitting, countries = [], error, renderAddressAutocomplete, fetchStates, t }) {
	const { control, handleSubmit, reset, setValue } = useZodForm(addressFormSchema, { defaultValues: {
		first_name: "",
		last_name: "",
		address1: "",
		address2: "",
		city: "",
		state: "",
		postal_code: "",
		country_code: "US",
		default: false
	} });
	const selectedCountryCode = useWatch({
		control,
		name: "country_code"
	});
	const isDefault = useWatch({
		control,
		name: "default"
	});
	const { stateOptions, config, handleCountryChange } = useCountryStates();
	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) {
			const nameParts = (selectedAddress.name ?? "").split(" ");
			reset({
				first_name: nameParts[0] ?? "",
				last_name: nameParts.slice(1).join(" "),
				address1: selectedAddress.address1,
				address2: selectedAddress.address2 ?? "",
				city: selectedAddress.city,
				state: selectedAddress.state,
				postal_code: selectedAddress.postal_code,
				country_code: selectedAddress.country_code ?? "US",
				default: selectedAddress.default
			});
			handleCountryChange(selectedAddress.country_code ?? "US", fetchStates);
		} else {
			reset({
				first_name: "",
				last_name: "",
				address1: "",
				address2: "",
				city: "",
				state: "",
				postal_code: "",
				country_code: "US",
				default: false
			});
			handleCountryChange("US", fetchStates);
		}
	}, [
		selectedAddress,
		isOpen,
		reset,
		handleCountryChange,
		fetchStates
	]);
	useEffect(() => {
		handleCountryChange(selectedCountryCode, fetchStates);
	}, [
		selectedCountryCode,
		handleCountryChange,
		fetchStates
	]);
	const handleFormSubmit = handleSubmit((data) => {
		onSubmit({ address: {
			first_name: data.first_name,
			last_name: data.last_name,
			address1: data.address1,
			address2: data.address2 ?? null,
			city: data.city,
			state: data.state,
			postal_code: data.postal_code,
			country_code: data.country_code,
			default: data.default
		} });
	});
	return /* @__PURE__ */ jsx(Dialog, {
		open: isOpen,
		onOpenChange: (open) => !open && onClose(),
		children: /* @__PURE__ */ jsxs(DialogContent, {
			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: selectedAddress !== null ? t("edit_address") : t("add_an_address")
				}) }),
				/* @__PURE__ */ jsxs("div", {
					className: "space-y-3 pt-2",
					children: [
						/* @__PURE__ */ jsx(FormSelectField, {
							control,
							name: "country_code",
							label: t("country"),
							placeholder: t("select_an_option"),
							options: countrySelectOptions,
							disabled: isSubmitting
						}),
						/* @__PURE__ */ jsxs("div", {
							className: "flex gap-3",
							children: [/* @__PURE__ */ jsx(FormTextField, {
								control,
								name: "first_name",
								label: t("first_name"),
								containerClassName: "flex-1",
								disabled: isSubmitting
							}), /* @__PURE__ */ jsx(FormTextField, {
								control,
								name: "last_name",
								label: t("last_name"),
								containerClassName: "flex-1",
								disabled: isSubmitting
							})]
						}),
						renderAddressAutocomplete ? renderAddressAutocomplete({
							control,
							setValue,
							countryCode: selectedCountryCode
						}) : /* @__PURE__ */ jsx(FormTextField, {
							control,
							name: "address1",
							label: t("address_line_1"),
							disabled: isSubmitting
						}),
						/* @__PURE__ */ jsx(FormTextField, {
							control,
							name: "address2",
							label: t("address_line_2"),
							disabled: isSubmitting
						}),
						/* @__PURE__ */ jsxs("div", {
							className: "flex gap-3",
							children: [
								/* @__PURE__ */ jsx(FormTextField, {
									control,
									name: "city",
									label: t("city"),
									containerClassName: "flex-1",
									disabled: isSubmitting
								}),
								/* @__PURE__ */ jsx(FormSelectField, {
									control,
									name: "state",
									label: config?.regionLabel ? t(config.regionLabel) : t("state"),
									placeholder: t("select_state"),
									options: stateSelectOptions,
									containerClassName: "flex-1",
									disabled: isSubmitting
								}),
								/* @__PURE__ */ jsx(FormTextField, {
									control,
									name: "postal_code",
									label: config?.postalLabel ? t(config.postalLabel) : t("zip_code"),
									containerClassName: "flex-1",
									disabled: isSubmitting
								})
							]
						})
					]
				}),
				/* @__PURE__ */ jsxs("div", {
					className: "mt-4 flex items-center justify-between",
					children: [/* @__PURE__ */ jsxs("div", {
						className: "flex items-center space-x-2",
						children: [/* @__PURE__ */ jsx("input", {
							type: "checkbox",
							id: "set_as_default_address",
							checked: isDefault,
							onChange: () => setValue("default", !isDefault),
							disabled: isSubmitting,
							className: "h-4 w-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,
						children: [isSubmitting && /* @__PURE__ */ jsx("div", { className: "mr-2 h-4 w-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
				};
				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 billingAddressSchema = z.object({
	name: z.string().min(1, "Name is required"),
	address1: z.string().min(1, "Address line 1 is required"),
	address2: z.string().optional().nullable(),
	city: z.string().min(1, "City is required"),
	state: z.string().min(1, "State is required"),
	zip: z.string().min(1, "Zip code is required"),
	country_code: z.string().min(1, "Country is required"),
	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 CreditCardFormDialog({ isOpen, onClose, onSubmit, isSubmitting, countries = [], error, jwt, renderAddressAutocomplete, t }) {
	const api = useFluidPayApi();
	const [cardError, setCardError] = useState(void 0);
	const [isVgsSubmitting, setIsVgsSubmitting] = useState(false);
	const { isFormReady, isLoading: isVgsLoading, isScriptLoaded, scriptLoadError, initializeForm, submitCard, vgsFieldState, resetVgs, onSuccessRef, onErrorRef } = useVgsCollect();
	const { control, handleSubmit, reset, setValue } = useZodForm(billingAddressSchema, { defaultValues: {
		name: "",
		address1: "",
		address2: "",
		city: "",
		state: "",
		zip: "",
		country_code: "US",
		set_as_default: false
	} });
	const billingCountry = useWatch({
		control,
		name: "country_code"
	});
	const setAsDefault = useWatch({
		control,
		name: "set_as_default"
	});
	const { stateOptions, config, handleCountryChange } = useCountryStates();
	const countrySelectOptions = [...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(() => {
		handleCountryChange(billingCountry);
	}, [billingCountry, handleCountryChange]);
	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 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) => {
			onSubmit({
				type: "credit_card",
				country_code: formData.country_code,
				default_payment_method: formData.set_as_default,
				payment_method: {
					token: response.card_number,
					cvv_token: response.card_cvc,
					exp_month: expMonth,
					exp_year: expYear,
					card_holder: cardholderName,
					billing_zip: formData.zip
				},
				billing_address: {
					name: formData.name,
					address1: formData.address1,
					address2: formData.address2 ?? void 0,
					city: formData.city,
					state: formData.state,
					zip: formData.zip,
					country_code: formData.country_code
				}
			});
			setIsVgsSubmitting(false);
		}, () => {
			setCardError("Please fix the errors in the billing address.");
			setIsVgsSubmitting(false);
		})();
	}, [handleSubmit, onSubmit]);
	const handleVgsError = useCallback((err) => {
		setCardError(err);
		setIsVgsSubmitting(false);
	}, []);
	useEffect(() => {
		onSuccessRef.current = handleVgsSuccess;
		onErrorRef.current = handleVgsError;
	}, [
		handleVgsSuccess,
		handleVgsError,
		onSuccessRef,
		onErrorRef
	]);
	const handleClose = () => {
		resetVgs();
		reset();
		setCardError(void 0);
		setIsVgsSubmitting(false);
		onClose();
	};
	const handleFormSubmit = handleSubmit(() => {
		setIsVgsSubmitting(true);
		setCardError(void 0);
		submitCard();
	});
	const isBusy = isSubmitting || isVgsSubmitting;
	return /* @__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 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 h-5 w-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")
								}),
								/* @__PURE__ */ jsx(FormSelectField, {
									control,
									name: "country_code",
									label: t("country"),
									placeholder: t("select_an_option"),
									options: countrySelectOptions,
									disabled: isBusy
								}),
								/* @__PURE__ */ jsx(FormTextField, {
									control,
									name: "name",
									label: t("name"),
									disabled: isBusy
								}),
								renderAddressAutocomplete ? renderAddressAutocomplete({
									control,
									setValue,
									countryCode: billingCountry
								}) : /* @__PURE__ */ jsx(FormTextField, {
									control,
									name: "address1",
									label: t("address_line_1"),
									disabled: isBusy
								}),
								/* @__PURE__ */ jsx(FormTextField, {
									control,
									name: "address2",
									label: t("address_line_2"),
									disabled: isBusy
								}),
								/* @__PURE__ */ jsxs("div", {
									className: "flex gap-3",
									children: [
										/* @__PURE__ */ jsx(FormTextField, {
											control,
											name: "city",
											label: t("city"),
											containerClassName: "flex-1",
											disabled: isBusy
										}),
										/* @__PURE__ */ jsx(FormSelectField, {
											control,
											name: "state",
											label: config?.regionLabel ? t(config.regionLabel) : t("state"),
											placeholder: t("select_state"),
											options: stateSelectOptions,
											containerClassName: "flex-1",
											disabled: isBusy
										}),
										/* @__PURE__ */ jsx(FormTextField, {
											control,
											name: "zip",
											label: config?.postalLabel ? t(config.postalLabel) : t("zip_code"),
											containerClassName: "flex-1",
											disabled: isBusy
										})
									]
								})
							]
						})]
					}),
					/* @__PURE__ */ jsxs("div", {
						className: "mt-4 flex items-center justify-between",
						children: [/* @__PURE__ */ jsxs("div", {
							className: "flex items-center space-x-2",
							children: [/* @__PURE__ */ jsx("input", {
								type: "checkbox",
								id: "set_as_default_cc",
								checked: setAsDefault,
								onChange: () => setValue("set_as_default", !setAsDefault),
								disabled: isBusy,
								className: "h-4 w-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 h-4 w-4 animate-spin rounded-full border-2 border-current/30 border-t-current" }), isBusy ? t("saving") : t("save_card")]
						})]
					})
				]
			})
		})
	});
}
//#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_type: raw.brand,
			card_brand: raw.brand,
			last_four: raw.last_four,
			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/components/AddressAutocompleteInput.tsx
const SET_OPTS = {
	shouldValidate: true,
	shouldDirty: true,
	shouldTouch: true
};
const DEBOUNCE_MS = 250;
function AddressAutocompleteInput({ control, setValue, countryIso, addressLineField, cityField, stateField, postalCodeField, placeholder = "Start typing your address...", disabled }) {
	const api = useAddressAutocompleteApi();
	const { field } = 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]);
	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, s.state, SET_OPTS);
		setValue(postalCodeField, s.postalCode, SET_OPTS);
	}, [
		addressLineField,
		cityField,
		postalCodeField,
		setValue,
		stateField
	]);
	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", {
		ref: containerRef,
		className: "relative",
		children: [
			/* @__PURE__ */ jsx(Input, {
				type: "text",
				ref: field.ref,
				value: field.value ?? "",
				onChange: handleChange,
				onBlur: field.onBlur,
				placeholder,
				disabled
			}),
			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-accent block w-full cursor-pointer px-3 py-2 text-left text-sm",
					children: [s.text, s.needsDetailLookup ? " →" : ""]
				}, s.id))
			})
		]
	});
}
//#endregion
export { AddressFormDialog as a, getCardDisplayName as c, ConfirmActionDialog as d, EllipsesDropdown as f, CreditCardFormDialog as i, getCardExpiry as l, ProfileUIProvider as m, createFluidPayApiAdapter as n, EditPaymentMethodDialog as o, FluidPayCoreProvider as p, mapToFluidPayPaymentMethod as r, PaymentIcon as s, AddressAutocompleteInput as t, UserInfoDialog as u };

//# sourceMappingURL=AddressAutocompleteInput-pqzSBpqP.mjs.map