import { vt as __exportAll } from "./PortalTenantClientProvider-BmRtQAbi.mjs";
import { n as useCountriesApi } from "./countries-api-context-DScC_39w.mjs";
import { a as contactsKeys, c as useContactsTranslation, d as useGroupsApi, f as useNotesApi, i as CONTACTS_QUERY_KEYS, m as parseApiErrors, n as startOfLocalDay, o as parseTaskBody, p as useTasksApi, r as useInfiniteContacts, t as TaskComposerForm, u as useContactsCrud } from "./task-composer-form-D_Pbl6qk.mjs";
import { B as DropdownMenuContent, C as SelectContent, Cn as AlertDialogTitle, E as SelectValue, F as FormItem, I as FormLabel, L as FormMessage, N as FormControl, On as useZodForm, P as FormField, Q as DialogContent, S as Select, Sn as AlertDialogHeader, T as SelectTrigger, V as DropdownMenuItem, X as Dialog, Y as DropdownMenuTrigger, _ as SheetContent, _n as AlertDialogAction, b as SheetTitle, bn as AlertDialogDescription, d as Spinner, dn as BreadcrumbLink, et as DialogFooter, f as fluidToast, fn as BreadcrumbList, g as Sheet, gn as AlertDialog, it as DialogTitle, k as Input, kn as cn, ln as Breadcrumb, mn as BreadcrumbSeparator, pn as BreadcrumbPage, tt as DialogHeader, un as BreadcrumbItem, v as SheetFooter, vn as AlertDialogCancel, w as SelectItem, wn as Button, xn as AlertDialogFooter, y as SheetHeader, yn as AlertDialogContent, z as DropdownMenu } from "./src-CJw6JbdS.mjs";
import { n as ScreenHeaderBreadcrumbs, t as ScreenHeaderActions } from "./ScreenHeaderContext-BjpQOCck.mjs";
import { r as storeKeys } from "./query-keys-xJy_fapN.mjs";
import { t as Combobox } from "./Combobox-D8LKqQ19.mjs";
import { a as useEditor, n as Heading, o as Placeholder, r as EditorContent, t as StarterKit } from "./dist-CCN3CBrB.mjs";
import { n as TextAlign, t as Underline } from "./dist-C6tFikje.mjs";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { Fragment as Fragment$1, jsx, jsxs } from "react/jsx-runtime";
import { AlignCenter, AlignJustify, AlignLeft, AlignRight, Calendar, Check, ChevronLeft, ChevronRight, CircleCheck, Copy, EllipsisVertical, List, ListOrdered, ListTodo, Mail, MapPin, MoreHorizontal, Paperclip, Pencil, Phone, Plus, Search, StickyNote, Trash2, Users, X } from "lucide-react";
import { FormProvider, useFormContext, useWatch } from "react-hook-form";
import { z } from "zod";
//#region ../../contacts/ui/src/screens/ContactCreateScreen.tsx
function ContactCreateScreen({ onNavigateToList, onSubmit, isPending, children }) {
	const { t } = useContactsTranslation();
	return /* @__PURE__ */ jsxs(Fragment$1, { children: [
		/* @__PURE__ */ jsxs(ScreenHeaderActions, { children: [/* @__PURE__ */ jsx(Button, {
			variant: "outline",
			onClick: onNavigateToList,
			disabled: isPending,
			children: t("cancel")
		}), /* @__PURE__ */ jsx(Button, {
			onClick: onSubmit,
			disabled: isPending,
			children: isPending ? t("adding") : t("add_contact")
		})] }),
		/* @__PURE__ */ jsx(ScreenHeaderBreadcrumbs, { children: /* @__PURE__ */ jsx(Breadcrumb, { children: /* @__PURE__ */ jsxs(BreadcrumbList, {
			className: "text-lg",
			children: [
				/* @__PURE__ */ jsx(BreadcrumbItem, { children: /* @__PURE__ */ jsx(BreadcrumbLink, {
					href: "#",
					onClick: (e) => {
						e.preventDefault();
						onNavigateToList();
					},
					children: t("breadcrumb")
				}) }),
				/* @__PURE__ */ jsx(BreadcrumbSeparator, {}),
				/* @__PURE__ */ jsx(BreadcrumbItem, { children: /* @__PURE__ */ jsx(BreadcrumbPage, {
					className: "font-semibold",
					children: t("breadcrumb_new")
				}) })
			]
		}) }) }),
		children
	] });
}
//#endregion
//#region ../../contacts/ui/src/portal/hooks/groups/use-groups.ts
function useGroups() {
	const api = useGroupsApi();
	return useQuery({
		queryKey: contactsKeys.groups(),
		queryFn: () => api.listGroups(),
		enabled: !!api,
		select: (data) => data.groups
	});
}
//#endregion
//#region ../../contacts/ui/src/portal/components/contacts/rep-layout/utils.ts
function getDisplayName(contact) {
	if (contact.full_name && contact.full_name.trim().length > 0) return contact.full_name;
	const parts = [contact.first_name, contact.last_name].filter(Boolean);
	if (parts.length > 0) return parts.join(" ");
	if (contact.email) return contact.email;
	return "Contact";
}
function getInitials(name) {
	const parts = name.trim().split(/\s+/);
	return ((parts[0]?.[0] ?? "") + (parts.length > 1 ? parts[parts.length - 1]?.[0] ?? "" : "")).toUpperCase() || "?";
}
/** Lowercase relative label derived from `contact.updated_at`.
*  Returns null if the timestamp is missing or unparseable. Lowercase on
*  purpose so callers can compose phrases like "Last updated 3 days ago"
*  without an awkward "Last updated Today". */
function getRelativeUpdated(contact) {
	const updated = typeof contact.updated_at === "string" ? contact.updated_at : null;
	if (!updated) return null;
	const date = new Date(updated);
	if (Number.isNaN(date.getTime())) return null;
	const diffMs = Date.now() - date.getTime();
	const diffDays = Math.floor(diffMs / (1e3 * 60 * 60 * 24));
	if (diffDays <= 0) return "today";
	if (diffDays === 1) return "yesterday";
	if (diffDays < 7) return `${diffDays} days ago`;
	if (diffDays < 30) {
		const weeks = Math.floor(diffDays / 7);
		return weeks === 1 ? "1 week ago" : `${weeks} weeks ago`;
	}
	if (diffDays < 365) {
		const months = Math.floor(diffDays / 30);
		return months === 1 ? "1 month ago" : `${months} months ago`;
	}
	const years = Math.floor(diffDays / 365);
	return years === 1 ? "1 year ago" : `${years} years ago`;
}
//#endregion
//#region ../../contacts/ui/src/portal/components/contacts/rep-layout/ContactsSidebarRow.tsx
function ContactsSidebarRow({ contact, isSelected, onSelect }) {
	const name = getDisplayName(contact);
	const id = String(contact.id);
	const secondary = contact.email ?? contact.status?.trim() ?? null;
	return /* @__PURE__ */ jsxs("button", {
		type: "button",
		onClick: () => onSelect(id),
		"aria-current": isSelected ? "true" : void 0,
		className: cn("group flex w-full items-center gap-3.5 rounded-xl px-3 py-3 text-left transition-colors", isSelected ? "bg-muted" : "hover:bg-muted/60"),
		children: [
			/* @__PURE__ */ jsx("div", {
				className: cn("text-muted-foreground relative flex size-12 shrink-0 items-center justify-center overflow-hidden rounded-xl text-base font-semibold transition-colors", isSelected ? "bg-background" : "bg-muted"),
				children: contact.avatar_url ? /* @__PURE__ */ jsx("img", {
					alt: name,
					src: contact.avatar_url,
					className: "size-12 object-cover"
				}) : /* @__PURE__ */ jsx("span", {
					"aria-hidden": "true",
					children: getInitials(name)
				})
			}),
			/* @__PURE__ */ jsxs("div", {
				className: "min-w-0 flex-1",
				children: [/* @__PURE__ */ jsx("span", {
					className: "text-foreground block truncate text-sm font-semibold tracking-tight",
					children: name
				}), secondary && /* @__PURE__ */ jsx("span", {
					className: "text-muted-foreground mt-0.5 block truncate text-sm",
					children: secondary
				})]
			}),
			/* @__PURE__ */ jsx(ChevronRight, {
				className: cn("size-4 shrink-0 transition-all", isSelected ? "text-foreground" : "text-muted-foreground/60 opacity-0 group-hover:translate-x-0.5 group-hover:opacity-100"),
				"aria-hidden": "true"
			})
		]
	});
}
//#endregion
//#region ../../contacts/ui/src/portal/components/contacts/rep-layout/ContactsSidebar.tsx
const DEBOUNCE_MS = 200;
function useBuiltInFilters() {
	const { t } = useContactsTranslation();
	return useMemo(() => [
		{
			id: "all",
			label: t("filter_all"),
			value: { kind: "all" }
		},
		{
			id: "status:lead",
			label: t("filter_leads"),
			value: {
				kind: "status",
				status: "lead"
			}
		},
		{
			id: "status:customer",
			label: t("filter_customers"),
			value: {
				kind: "status",
				status: "customer"
			}
		}
	], [t]);
}
function filterId(value) {
	if (value.kind === "all") return "all";
	if (value.kind === "status") return `status:${value.status}`;
	return `group:${value.tag}`;
}
function ContactsSidebar({ selectedContactId, onSelect, onAdd }) {
	const { t } = useContactsTranslation();
	const builtInFilters = useBuiltInFilters();
	const [searchInput, setSearchInput] = useState("");
	const [debouncedSearch, setDebouncedSearch] = useState("");
	const [filter, setFilter] = useState({ kind: "all" });
	useEffect(() => {
		const handle = window.setTimeout(() => {
			setDebouncedSearch(searchInput.trim());
		}, DEBOUNCE_MS);
		return () => window.clearTimeout(handle);
	}, [searchInput]);
	const { data: groups = [] } = useGroups();
	const { data, isLoading, isFetchingNextPage, hasNextPage, fetchNextPage, isError } = useInfiniteContacts(useMemo(() => ({
		search_query: debouncedSearch || void 0,
		tags: filter.kind === "group" ? [filter.tag] : void 0,
		sort_by: "full_name",
		sort_direction: "asc",
		per_page: 50
	}), [debouncedSearch, filter]));
	const contacts = useMemo(() => data?.pages.flatMap((page) => page.contacts ?? []) ?? [], [data]);
	const visibleContacts = useMemo(() => {
		if (filter.kind === "status") return contacts.filter((c) => c.status === filter.status);
		return contacts;
	}, [contacts, filter]);
	const sentinelRef = useRef(null);
	const hasAutoSelectedRef = useRef(false);
	useEffect(() => {
		if (hasAutoSelectedRef.current) return;
		if (selectedContactId) {
			hasAutoSelectedRef.current = true;
			return;
		}
		if (isLoading || visibleContacts.length === 0) return;
		if (!(typeof window === "undefined" || window.matchMedia("(min-width: 768px)").matches)) {
			hasAutoSelectedRef.current = true;
			return;
		}
		const first = visibleContacts[0];
		if (first) {
			hasAutoSelectedRef.current = true;
			onSelect(String(first.id));
		}
	}, [
		selectedContactId,
		isLoading,
		visibleContacts,
		onSelect
	]);
	useEffect(() => {
		const sentinel = sentinelRef.current;
		if (!sentinel || !hasNextPage) return;
		const observer = new IntersectionObserver((entries) => {
			if (entries[0]?.isIntersecting && !isFetchingNextPage) fetchNextPage();
		});
		observer.observe(sentinel);
		return () => observer.disconnect();
	}, [
		hasNextPage,
		isFetchingNextPage,
		fetchNextPage
	]);
	const activeFilterId = filterId(filter);
	return /* @__PURE__ */ jsxs(Fragment$1, { children: [
		/* @__PURE__ */ jsx("div", {
			className: "border-border/50 border-b px-6 py-3",
			children: /* @__PURE__ */ jsxs("div", {
				className: "flex items-center gap-3",
				children: [/* @__PURE__ */ jsxs("div", {
					className: "bg-muted focus-within:ring-foreground/20 flex min-w-0 flex-1 items-center gap-2 rounded-lg px-3 py-1.5 transition focus-within:ring-2",
					children: [/* @__PURE__ */ jsx(Search, {
						className: "text-muted-foreground size-3.5 shrink-0",
						"aria-hidden": "true"
					}), /* @__PURE__ */ jsx(Input, {
						value: searchInput,
						onChange: (e) => setSearchInput(e.target.value),
						placeholder: t("search_placeholder"),
						type: "search",
						className: "placeholder:text-muted-foreground/80 h-auto flex-1 border-0 bg-transparent p-0 text-xs font-medium shadow-none focus-visible:ring-0",
						"aria-label": t("search_placeholder")
					})]
				}), /* @__PURE__ */ jsxs("button", {
					type: "button",
					onClick: onAdd,
					className: "bg-primary text-primary-foreground hover:bg-primary/90 inline-flex shrink-0 items-center gap-1.5 rounded-lg px-3 py-1.5 text-xs font-semibold transition-colors",
					children: [/* @__PURE__ */ jsx(Plus, {
						className: "size-3.5",
						"aria-hidden": "true"
					}), t("add")]
				})]
			})
		}),
		/* @__PURE__ */ jsx(FilterPills, {
			activeId: activeFilterId,
			builtInFilters,
			groups: groups.map((g) => g.name),
			onChange: setFilter
		}),
		/* @__PURE__ */ jsx("div", {
			className: "flex-1 overflow-y-auto px-3 pb-8",
			children: isError ? /* @__PURE__ */ jsx("div", {
				className: "text-muted-foreground px-4 py-8 text-center text-sm",
				children: t("error_loading_list")
			}) : isLoading ? /* @__PURE__ */ jsx(SidebarSkeleton, {}) : visibleContacts.length === 0 ? /* @__PURE__ */ jsxs("div", {
				className: "space-y-2",
				children: [hasNextPage || isFetchingNextPage ? /* @__PURE__ */ jsx("div", {
					className: "text-muted-foreground px-4 py-8 text-center text-sm",
					children: t("searching")
				}) : /* @__PURE__ */ jsx("div", {
					className: "text-muted-foreground px-4 py-8 text-center text-sm",
					children: debouncedSearch ? t("no_contacts_search", { term: debouncedSearch }) : filter.kind === "all" ? t("no_contacts_yet") : t("no_contacts_filter")
				}), hasNextPage && /* @__PURE__ */ jsx("div", {
					ref: sentinelRef,
					"aria-hidden": "true",
					className: "h-4"
				})]
			}) : /* @__PURE__ */ jsxs("div", {
				className: "space-y-1",
				children: [
					visibleContacts.map((contact) => /* @__PURE__ */ jsx(ContactsSidebarRow, {
						contact,
						isSelected: String(contact.id) === selectedContactId,
						onSelect
					}, contact.id)),
					/* @__PURE__ */ jsx("div", {
						ref: sentinelRef,
						"aria-hidden": "true",
						className: "h-4"
					}),
					isFetchingNextPage && /* @__PURE__ */ jsx("div", {
						className: "text-muted-foreground py-3 text-center text-xs",
						children: t("loading_more")
					})
				]
			})
		})
	] });
}
function FilterPills({ activeId, builtInFilters, groups, onChange }) {
	return /* @__PURE__ */ jsx("div", {
		className: "overflow-x-auto pt-4 pb-4 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden",
		children: /* @__PURE__ */ jsx("div", {
			className: "flex gap-1.5 px-6",
			children: useMemo(() => [...builtInFilters, ...groups.map((tag) => ({
				id: `group:${tag}`,
				label: tag,
				value: {
					kind: "group",
					tag
				}
			}))], [builtInFilters, groups]).map(({ id, label, value }) => {
				const isActive = id === activeId;
				return /* @__PURE__ */ jsx("button", {
					type: "button",
					onClick: () => onChange(value),
					"aria-pressed": isActive,
					className: cn("shrink-0 rounded-full px-4 py-1.5 text-sm font-semibold capitalize transition-colors", isActive ? "bg-primary text-primary-foreground" : "border-border/50 bg-muted text-foreground hover:bg-muted/70 border"),
					children: label
				}, id);
			})
		})
	});
}
function SidebarSkeleton() {
	return /* @__PURE__ */ jsx("div", {
		className: "space-y-1.5 px-1",
		children: [
			0,
			1,
			2,
			3,
			4
		].map((i) => /* @__PURE__ */ jsxs("div", {
			className: "flex items-center gap-3 rounded-xl p-3",
			"aria-hidden": "true",
			children: [/* @__PURE__ */ jsx("div", { className: "bg-muted size-12 shrink-0 animate-pulse rounded-xl" }), /* @__PURE__ */ jsxs("div", {
				className: "flex-1 space-y-2",
				children: [/* @__PURE__ */ jsx("div", { className: "bg-muted h-3.5 w-3/5 animate-pulse rounded" }), /* @__PURE__ */ jsx("div", { className: "bg-muted h-3 w-4/5 animate-pulse rounded" })]
			})]
		}, i))
	});
}
//#endregion
//#region ../../contacts/ui/src/shared/components/contacts/contactDetailsForm.tsx
const DEFAULT_COUNTRIES = [];
const statusOptions = [
	{
		name: "New",
		value: "new"
	},
	{
		name: "Active",
		value: "active"
	},
	{
		name: "Inactive",
		value: "inactive"
	},
	{
		name: "Cold",
		value: "cold"
	},
	{
		name: "Lead",
		value: "lead"
	},
	{
		name: "Customer",
		value: "customer"
	}
];
const ContactDetailsForm = ({ className, countries = DEFAULT_COUNTRIES, renderAvatarPicker }) => {
	const { control, watch, setValue } = useFormContext();
	const currentStatus = useWatch({
		control,
		name: "status"
	});
	const avatarUrl = watch("avatar_url") ?? null;
	const effectiveStatusOptions = useMemo(() => {
		if (currentStatus && typeof currentStatus === "string" && !statusOptions.some((o) => o.value === currentStatus)) return [{
			name: currentStatus.charAt(0).toUpperCase() + currentStatus.slice(1).replace(/_/g, " "),
			value: currentStatus
		}, ...statusOptions];
		return statusOptions;
	}, [currentStatus]);
	const initials = [watch("first_name")?.[0] ?? "", watch("last_name")?.[0] ?? ""].filter(Boolean).join("").toUpperCase() || "?";
	return /* @__PURE__ */ jsxs("div", {
		className: cn("space-y-6", className),
		children: [renderAvatarPicker && /* @__PURE__ */ jsxs("div", {
			className: "flex flex-col items-center gap-3",
			children: [/* @__PURE__ */ jsx("div", {
				className: "border-border bg-background relative size-20 shrink-0 overflow-hidden rounded-full border-2",
				children: avatarUrl ? /* @__PURE__ */ jsx("img", {
					src: avatarUrl,
					alt: "",
					className: "h-full w-full object-cover"
				}) : /* @__PURE__ */ jsx("div", {
					className: "text-muted-foreground flex h-full w-full items-center justify-center text-lg font-semibold",
					children: initials
				})
			}), renderAvatarPicker({
				value: avatarUrl,
				onChange: (url) => setValue("avatar_url", url ?? "", { shouldDirty: true })
			})]
		}), /* @__PURE__ */ jsxs("div", {
			className: "grid grid-cols-1 gap-6 lg:grid-cols-2",
			children: [
				/* @__PURE__ */ jsx(FormField, {
					control,
					name: "first_name",
					render: ({ field }) => /* @__PURE__ */ jsxs(FormItem, { children: [
						/* @__PURE__ */ jsx(FormLabel, {
							className: "font-inter text-foreground font-medium",
							children: "First Name"
						}),
						/* @__PURE__ */ jsx(FormControl, { children: /* @__PURE__ */ jsx(Input, {
							placeholder: "Enter first name",
							...field,
							value: field.value ?? "",
							className: "ring-input"
						}) }),
						/* @__PURE__ */ jsx(FormMessage, {})
					] })
				}),
				/* @__PURE__ */ jsx(FormField, {
					control,
					name: "last_name",
					render: ({ field }) => /* @__PURE__ */ jsxs(FormItem, { children: [
						/* @__PURE__ */ jsx(FormLabel, {
							className: "font-inter text-foreground font-medium",
							children: "Last Name"
						}),
						/* @__PURE__ */ jsx(FormControl, { children: /* @__PURE__ */ jsx(Input, {
							placeholder: "Enter last name",
							...field,
							value: field.value ?? "",
							className: "ring-input"
						}) }),
						/* @__PURE__ */ jsx(FormMessage, {})
					] })
				}),
				/* @__PURE__ */ jsx(FormField, {
					control,
					name: "email",
					render: ({ field }) => /* @__PURE__ */ jsxs(FormItem, { children: [
						/* @__PURE__ */ jsx(FormLabel, {
							className: "font-inter text-foreground font-medium",
							children: "Email"
						}),
						/* @__PURE__ */ jsx(FormControl, { children: /* @__PURE__ */ jsx(Input, {
							placeholder: "Enter email address",
							type: "email",
							...field,
							value: field.value ?? "",
							className: "ring-input"
						}) }),
						/* @__PURE__ */ jsx(FormMessage, {})
					] })
				}),
				/* @__PURE__ */ jsx(FormField, {
					control,
					name: "phone",
					render: ({ field }) => /* @__PURE__ */ jsxs(FormItem, { children: [
						/* @__PURE__ */ jsx(FormLabel, {
							className: "font-inter text-foreground font-medium",
							children: "Phone"
						}),
						/* @__PURE__ */ jsx(FormControl, { children: /* @__PURE__ */ jsx(Input, {
							placeholder: "Enter phone number",
							...field,
							value: field.value ?? "",
							className: "ring-input"
						}) }),
						/* @__PURE__ */ jsx(FormMessage, {})
					] })
				}),
				/* @__PURE__ */ jsx(FormField, {
					control,
					name: "status",
					render: ({ field }) => /* @__PURE__ */ jsxs(FormItem, { children: [
						/* @__PURE__ */ jsx(FormLabel, {
							className: "font-inter text-foreground font-medium",
							children: "Status"
						}),
						/* @__PURE__ */ jsxs(Select, {
							value: field.value ?? "",
							onValueChange: field.onChange,
							children: [/* @__PURE__ */ jsx(FormControl, { children: /* @__PURE__ */ jsx(SelectTrigger, {
								className: "w-full",
								children: /* @__PURE__ */ jsx(SelectValue, { placeholder: "Select status" })
							}) }), /* @__PURE__ */ jsx(SelectContent, {
								position: "popper",
								sideOffset: 4,
								children: effectiveStatusOptions.map((opt) => /* @__PURE__ */ jsx(SelectItem, {
									value: opt.value,
									children: opt.name
								}, opt.value))
							})]
						}),
						/* @__PURE__ */ jsx(FormMessage, {})
					] })
				}),
				/* @__PURE__ */ jsx(FormField, {
					control,
					name: "address",
					render: ({ field }) => /* @__PURE__ */ jsxs(FormItem, {
						className: "lg:col-span-2",
						children: [
							/* @__PURE__ */ jsx(FormLabel, {
								className: "font-inter text-foreground font-medium",
								children: "Full Address"
							}),
							/* @__PURE__ */ jsx(FormControl, { children: /* @__PURE__ */ jsx(Input, {
								placeholder: "Enter street address",
								...field,
								value: field.value ?? "",
								className: "ring-input"
							}) }),
							/* @__PURE__ */ jsx(FormMessage, {})
						]
					})
				}),
				/* @__PURE__ */ jsx(FormField, {
					control,
					name: "city",
					render: ({ field }) => /* @__PURE__ */ jsxs(FormItem, { children: [
						/* @__PURE__ */ jsx(FormLabel, {
							className: "font-inter text-foreground font-medium",
							children: "City"
						}),
						/* @__PURE__ */ jsx(FormControl, { children: /* @__PURE__ */ jsx(Input, {
							placeholder: "Enter city",
							...field,
							value: field.value ?? "",
							className: "ring-input"
						}) }),
						/* @__PURE__ */ jsx(FormMessage, {})
					] })
				}),
				/* @__PURE__ */ jsx(FormField, {
					control,
					name: "state",
					render: ({ field }) => /* @__PURE__ */ jsxs(FormItem, { children: [
						/* @__PURE__ */ jsx(FormLabel, {
							className: "font-inter text-foreground font-medium",
							children: "State/Province"
						}),
						/* @__PURE__ */ jsx(FormControl, { children: /* @__PURE__ */ jsx(Input, {
							placeholder: "Enter state or province",
							...field,
							value: field.value ?? "",
							className: "ring-input"
						}) }),
						/* @__PURE__ */ jsx(FormMessage, {})
					] })
				}),
				/* @__PURE__ */ jsx(FormField, {
					control,
					name: "postal_code",
					render: ({ field }) => /* @__PURE__ */ jsxs(FormItem, { children: [
						/* @__PURE__ */ jsx(FormLabel, {
							className: "font-inter text-foreground font-medium",
							children: "Postal Code"
						}),
						/* @__PURE__ */ jsx(FormControl, { children: /* @__PURE__ */ jsx(Input, {
							placeholder: "Enter postal code",
							...field,
							value: field.value ?? "",
							className: "ring-input"
						}) }),
						/* @__PURE__ */ jsx(FormMessage, {})
					] })
				}),
				/* @__PURE__ */ jsx(FormField, {
					control,
					name: "country_code",
					render: ({ field }) => /* @__PURE__ */ jsxs(FormItem, { children: [
						/* @__PURE__ */ jsx(FormLabel, {
							className: "font-inter text-foreground font-medium",
							children: "Country"
						}),
						/* @__PURE__ */ jsx(FormControl, { children: /* @__PURE__ */ jsx(Combobox, {
							options: countries.map((c) => ({
								label: c.name,
								value: c.value
							})),
							value: field.value ?? "",
							onValueChange: field.onChange,
							placeholder: "Select country"
						}) }),
						/* @__PURE__ */ jsx(FormMessage, {})
					] })
				})
			]
		})]
	});
};
//#endregion
//#region ../../contacts/ui/src/shared/hooks/useContactDetail.ts
function useContactDetail(contactId, queryKeyPrefix = "contacts") {
	const api = useContactsCrud();
	return useQuery({
		queryKey: CONTACTS_QUERY_KEYS.detail(queryKeyPrefix, contactId),
		queryFn: () => api.getContact(contactId),
		enabled: !!contactId
	});
}
//#endregion
//#region ../../contacts/ui/src/shared/hooks/useUpdateContactMutation.ts
function useUpdateContactMutation(contactId, queryKeyPrefix = "contacts", options) {
	const queryClient = useQueryClient();
	const api = useContactsCrud();
	return useMutation({
		mutationFn: ({ id, data }) => api.updateContact(id, data),
		onSuccess: () => {
			fluidToast({
				title: "Contact updated successfully",
				type: "success"
			});
			queryClient.invalidateQueries({ queryKey: CONTACTS_QUERY_KEYS.all(queryKeyPrefix) });
			options?.onSuccess?.();
		},
		onError: (error) => {
			fluidToast({
				title: "Failed to save contact",
				type: "error",
				description: parseApiErrors(error)
			});
			options?.onError?.(error);
		}
	});
}
//#endregion
//#region ../../contacts/ui/src/shared/hooks/useDeleteContactMutation.ts
function useDeleteContactMutation(queryKeyPrefix = "contacts", options) {
	const queryClient = useQueryClient();
	const api = useContactsCrud();
	return useMutation({
		mutationFn: (contactId) => api.deleteContact(contactId),
		onSuccess: () => {
			fluidToast({
				title: "Contact deleted successfully",
				type: "success"
			});
			queryClient.invalidateQueries({ queryKey: CONTACTS_QUERY_KEYS.all(queryKeyPrefix) });
			options?.onSuccess?.();
		},
		onError: (error) => {
			fluidToast({
				title: "Failed to delete contact",
				type: "error",
				description: parseApiErrors(error)
			});
			options?.onError?.(error);
		}
	});
}
//#endregion
//#region ../../contacts/ui/src/shared/schemas/contactFormSchema.ts
/**
* Form schema for creating a contact.
* Matches CompanyContactCreate / ContactCreate from the OpenAPI spec.
*
* @see CompanyContactCreate in company_contacts.d.ts
* @see ContactCreate in users_contacts.d.ts
*/
const createContactFormSchema = z.object({
	first_name: z.string().min(1, { message: "First name is required" }),
	last_name: z.string().min(1, { message: "Last name is required" }),
	status: z.string().nullable().optional(),
	email: z.string().email().or(z.literal("")).nullable().optional(),
	phone: z.string().nullable().optional(),
	address: z.string().nullable().optional(),
	city: z.string().nullable().optional(),
	state: z.string().nullable().optional(),
	postal_code: z.string().nullable().optional(),
	country_code: z.coerce.string().nullable().optional(),
	language_code: z.coerce.string().nullable().optional(),
	affiliate: z.record(z.string(), z.unknown()).nullable().optional(),
	metadata: z.record(z.string(), z.unknown()).optional()
});
/**
* Form schema for editing a contact.
* Same fields as create plus id. Uses .passthrough() so extra fields
* from the Contact read model (full_name, avatar_url, etc.) don't
* cause validation failures.
*
* @see CompanyContactUpdate in company_contacts.d.ts
*/
const editContactFormSchema = createContactFormSchema.passthrough();
//#endregion
//#region ../../contacts/ui/src/shared/hooks/useContactDetailPage.ts
const mutableKeys = Object.keys(createContactFormSchema.shape);
function useContactDetailPage(contactId, options) {
	const queryKeyPrefix = options?.queryKeyPrefix ?? "contacts";
	const { data, isLoading } = useContactDetail(contactId, queryKeyPrefix);
	const { data: countries } = useQuery({
		queryKey: ["countries"],
		queryFn: options?.getCountries ?? (() => Promise.resolve([])),
		enabled: !!options?.getCountries
	});
	const countryOptions = useMemo(() => [...countries?.map((c) => ({
		name: c.name,
		value: c.iso ?? c.id.toString()
	})) ?? []].sort((a, b) => a.name.localeCompare(b.name)), [countries]);
	const contact = data?.contact;
	const methods = useZodForm(editContactFormSchema, {
		values: useMemo(() => {
			if (!contact) return void 0;
			return {
				...contact,
				country_code: contact.country?.iso ?? contact.country_id?.toString() ?? null
			};
		}, [contact]),
		mode: "onBlur"
	});
	const updateMutation = useUpdateContactMutation(contactId, queryKeyPrefix, { onSuccess: () => {
		methods.reset(methods.getValues());
		options?.onSaveSuccess?.();
	} });
	const deleteMutation = useDeleteContactMutation(queryKeyPrefix, { onSuccess: () => {
		options?.onDeleteSuccess?.();
	} });
	const onSave = useCallback(() => {
		methods.handleSubmit((formData) => {
			const payload = {};
			for (const key of mutableKeys) if (key in formData) payload[key] = formData[key];
			updateMutation.mutate({
				id: contactId,
				data: payload
			});
		}, (errors) => {
			fluidToast({
				title: "Please fix the form errors before saving",
				description: Object.entries(errors).map(([field, err]) => {
					const msg = typeof err?.message === "string" ? err.message : "invalid";
					return `${field.replace(/_/g, " ")}: ${msg}`;
				}).join(", ") || void 0,
				type: "error"
			});
		})();
	}, [
		methods,
		updateMutation,
		contactId
	]);
	const onDelete = useCallback(() => {
		deleteMutation.mutate(contactId);
	}, [deleteMutation, contactId]);
	return {
		contact,
		isLoading,
		methods,
		countryOptions,
		isDirty: methods.formState.isDirty,
		isSubmitting: updateMutation.isPending,
		isDeleting: deleteMutation.isPending,
		onSave,
		onDelete
	};
}
//#endregion
//#region ../../contacts/ui/src/portal/hooks/contacts/use-contact-tasks.ts
function useContactTasks(contactId) {
	const api = useTasksApi();
	return useQuery({
		queryKey: contactsKeys.tasks(contactId),
		queryFn: () => api.listTasks(contactId),
		enabled: !!contactId,
		select: (data) => data.tasks
	});
}
//#endregion
//#region ../../contacts/ui/src/portal/hooks/notes/use-contact-notes.ts
function useContactNotes(contactId) {
	const api = useNotesApi();
	return useQuery({
		queryKey: contactsKeys.notes(contactId),
		queryFn: () => api.listNotes(contactId),
		enabled: !!contactId,
		select: (data) => data.notes
	});
}
//#endregion
//#region ../../contacts/ui/src/shared/components/contacts/statusBadge.tsx
const statusStyles = {
	new: "border-[var(--status-new-border)] bg-[var(--status-new)] text-[var(--status-new-foreground)]",
	active: "border-[var(--status-active-border)] bg-[var(--status-active)] text-[var(--status-active-foreground)]",
	inactive: "border-border bg-muted text-muted-foreground",
	lead: "border-[var(--status-lead-border)] bg-[var(--status-lead)] text-[var(--status-lead-foreground)]",
	customer: "border-[var(--status-customer-border)] bg-[var(--status-customer)] text-[var(--status-customer-foreground)]",
	success: "border-[var(--badge-success-border)] bg-[var(--badge-success)] text-[var(--badge-success-foreground)]",
	warning: "border-[var(--badge-warning-border)] bg-[var(--badge-warning)] text-[var(--badge-warning-foreground)]",
	danger: "border-[var(--badge-danger-border)] bg-[var(--badge-danger)] text-[var(--badge-danger-foreground)]",
	info: "border-[var(--badge-info-border)] bg-[var(--badge-info)] text-[var(--badge-info-foreground)]",
	neutral: "border-border bg-muted text-muted-foreground",
	notice: "border-[var(--badge-notice-border)] bg-[var(--badge-notice)] text-[var(--badge-notice-foreground)]",
	accent: "border-[var(--badge-accent-border)] bg-[var(--badge-accent)] text-[var(--badge-accent-foreground)]"
};
const defaultStyle = "border-border bg-muted text-muted-foreground";
function getStatusStyle(status) {
	return statusStyles[status] ?? defaultStyle;
}
function StatusBadge({ status, label, className }) {
	return /* @__PURE__ */ jsx("span", {
		className: cn("inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold capitalize", getStatusStyle(status), className),
		children: label ?? status
	});
}
//#endregion
//#region ../../contacts/ui/src/portal/components/contacts/rep-layout/ContactDetailHero.tsx
function ContactDetailHero({ contact, tasksCount, notesCount }) {
	const { t } = useContactsTranslation();
	const name = getDisplayName(contact);
	const status = contact.status?.trim();
	const lastUpdated = getRelativeUpdated(contact);
	return /* @__PURE__ */ jsxs("div", {
		className: "flex flex-col gap-6 md:flex-row md:items-center md:justify-between md:gap-8",
		children: [/* @__PURE__ */ jsxs("div", {
			className: "flex flex-col items-start gap-4 md:flex-row md:items-center md:gap-5",
			children: [/* @__PURE__ */ jsx("div", {
				className: "bg-muted relative flex size-20 shrink-0 items-center justify-center overflow-hidden rounded-2xl md:size-24",
				children: contact.avatar_url ? /* @__PURE__ */ jsx("img", {
					alt: name,
					src: contact.avatar_url,
					className: "size-full object-cover"
				}) : /* @__PURE__ */ jsx("span", {
					"aria-hidden": "true",
					className: "text-muted-foreground text-2xl font-bold tracking-tight md:text-3xl",
					children: getInitials(name)
				})
			}), /* @__PURE__ */ jsxs("div", {
				className: "min-w-0 flex-1",
				children: [/* @__PURE__ */ jsx("h2", {
					className: "text-foreground text-2xl leading-tight font-bold tracking-tight md:text-3xl",
					children: name
				}), /* @__PURE__ */ jsxs("div", {
					className: "mt-2.5 flex flex-wrap items-center gap-2",
					children: [
						status && /* @__PURE__ */ jsx(StatusBadge, { status }),
						status && lastUpdated && /* @__PURE__ */ jsx("span", {
							"aria-hidden": "true",
							className: "text-muted-foreground/40 text-sm",
							children: "·"
						}),
						lastUpdated && /* @__PURE__ */ jsx("span", {
							className: "text-muted-foreground text-sm",
							children: t("last_updated", { date: lastUpdated })
						})
					]
				})]
			})]
		}), /* @__PURE__ */ jsxs("div", {
			className: "flex shrink-0 items-center gap-6 md:gap-8",
			children: [
				/* @__PURE__ */ jsx(Stat, {
					label: t("tab_tasks"),
					value: tasksCount,
					icon: ListTodo
				}),
				/* @__PURE__ */ jsx("div", {
					className: "bg-border h-10 w-px",
					"aria-hidden": "true"
				}),
				/* @__PURE__ */ jsx(Stat, {
					label: t("tab_notes"),
					value: notesCount,
					icon: StickyNote
				})
			]
		})]
	});
}
function Stat({ label, value, icon: Icon }) {
	return /* @__PURE__ */ jsxs("div", {
		className: "flex flex-col items-start gap-1",
		children: [/* @__PURE__ */ jsxs("div", {
			className: "text-muted-foreground flex items-center gap-1.5",
			children: [/* @__PURE__ */ jsx(Icon, {
				className: "size-3.5",
				"aria-hidden": true
			}), /* @__PURE__ */ jsx("span", {
				className: "text-xs font-medium",
				children: label
			})]
		}), /* @__PURE__ */ jsx("span", {
			className: "text-foreground text-2xl font-bold tracking-tight tabular-nums",
			children: value
		})]
	});
}
//#endregion
//#region ../../contacts/ui/src/portal/components/contacts/rep-layout/ContactInfoRow.tsx
function buildAddressLine(contact) {
	const parts = [
		contact.address,
		contact.city,
		contact.state,
		contact.postal_code
	].filter((part) => Boolean(part?.trim()));
	if (parts.length === 0) return null;
	return parts.join(", ");
}
function ContactInfoRow({ contact, onEditEmpty }) {
	const { t } = useContactsTranslation();
	const address = buildAddressLine(contact);
	return /* @__PURE__ */ jsxs("div", {
		className: "border-border/50 divide-border/50 mt-6 divide-y overflow-hidden rounded-2xl border",
		children: [
			/* @__PURE__ */ jsx(InfoRow, {
				icon: Mail,
				label: t("label_email"),
				value: contact.email,
				href: contact.email ? `mailto:${contact.email}` : void 0,
				onEditEmpty
			}),
			/* @__PURE__ */ jsx(InfoRow, {
				icon: Phone,
				label: t("label_phone"),
				value: contact.phone,
				href: contact.phone ? `tel:${contact.phone}` : void 0,
				onEditEmpty
			}),
			/* @__PURE__ */ jsx(InfoRow, {
				icon: MapPin,
				label: t("label_address"),
				value: address,
				href: address ? `https://www.google.com/maps/search/?api=1&query=${encodeURIComponent(address)}` : void 0,
				external: true,
				onEditEmpty
			})
		]
	});
}
function InfoRow({ icon: Icon, label, value, href, external = false, onEditEmpty }) {
	const { t } = useContactsTranslation();
	const trimmed = value?.trim();
	const isEmpty = !trimmed;
	const [copied, setCopied] = useState(false);
	const handleCopy = () => {
		if (!trimmed) return;
		if (typeof navigator === "undefined" || !navigator.clipboard) return;
		navigator.clipboard.writeText(trimmed).then(() => {
			setCopied(true);
			window.setTimeout(() => setCopied(false), 1500);
		}).catch(() => {});
	};
	if (isEmpty) {
		const addText = t("add_field", { field: label });
		if (!onEditEmpty) return /* @__PURE__ */ jsxs("div", {
			className: "flex items-center gap-3 px-4 py-2.5 md:px-5",
			children: [
				/* @__PURE__ */ jsx("div", {
					className: "border-border/50 text-muted-foreground/50 flex size-9 shrink-0 items-center justify-center rounded-full border-2 border-dashed",
					children: /* @__PURE__ */ jsx(Icon, {
						className: "size-4",
						"aria-hidden": true
					})
				}),
				/* @__PURE__ */ jsxs("div", {
					className: "min-w-0 flex-1",
					children: [/* @__PURE__ */ jsx("div", {
						className: "text-muted-foreground text-xs font-medium",
						children: label
					}), /* @__PURE__ */ jsx("div", {
						className: "text-muted-foreground/70 truncate text-sm italic",
						children: addText
					})]
				}),
				/* @__PURE__ */ jsx(Plus, {
					className: "text-muted-foreground/40 size-4 shrink-0",
					"aria-hidden": true
				})
			]
		});
		return /* @__PURE__ */ jsxs("button", {
			type: "button",
			onClick: onEditEmpty,
			"aria-label": addText,
			className: "hover:bg-muted/60 group flex w-full items-center gap-3 px-4 py-2.5 text-left transition-colors md:px-5",
			children: [
				/* @__PURE__ */ jsx("div", {
					className: "border-border/50 text-muted-foreground/50 group-hover:border-foreground/30 group-hover:text-muted-foreground flex size-9 shrink-0 items-center justify-center rounded-full border-2 border-dashed transition-colors",
					children: /* @__PURE__ */ jsx(Icon, {
						className: "size-4",
						"aria-hidden": true
					})
				}),
				/* @__PURE__ */ jsxs("div", {
					className: "min-w-0 flex-1",
					children: [/* @__PURE__ */ jsx("div", {
						className: "text-muted-foreground text-xs font-medium",
						children: label
					}), /* @__PURE__ */ jsx("div", {
						className: "text-muted-foreground/70 group-hover:text-muted-foreground truncate text-sm italic transition-colors",
						children: addText
					})]
				}),
				/* @__PURE__ */ jsx(Plus, {
					className: "text-muted-foreground/40 group-hover:text-foreground size-4 shrink-0 transition-colors",
					"aria-hidden": true
				})
			]
		});
	}
	return /* @__PURE__ */ jsxs("div", {
		className: "hover:bg-muted/60 group flex items-center transition-colors",
		children: [/* @__PURE__ */ jsxs("a", {
			href,
			...external ? {
				target: "_blank",
				rel: "noopener noreferrer"
			} : {},
			className: "flex min-w-0 flex-1 items-center gap-3 px-4 py-2.5 md:px-5",
			children: [/* @__PURE__ */ jsx("div", {
				className: "bg-muted text-muted-foreground group-hover:bg-muted/70 group-hover:text-foreground flex size-9 shrink-0 items-center justify-center rounded-full transition-colors",
				children: /* @__PURE__ */ jsx(Icon, {
					className: "size-4",
					"aria-hidden": true
				})
			}), /* @__PURE__ */ jsxs("div", {
				className: "min-w-0 flex-1",
				children: [/* @__PURE__ */ jsx("div", {
					className: "text-muted-foreground text-xs font-medium",
					children: label
				}), /* @__PURE__ */ jsx("div", {
					className: "text-foreground truncate text-sm font-semibold",
					children: trimmed
				})]
			})]
		}), /* @__PURE__ */ jsx("button", {
			type: "button",
			onClick: handleCopy,
			"aria-label": copied ? t("copied_field", { field: label }) : t("copy_field", { field: label }),
			className: "text-muted-foreground hover:bg-muted hover:text-foreground mr-3 flex size-8 shrink-0 items-center justify-center rounded-md transition-colors",
			children: copied ? /* @__PURE__ */ jsx(Check, {
				className: "text-primary size-3.5",
				"aria-hidden": true
			}) : /* @__PURE__ */ jsx(Copy, {
				className: "size-3.5",
				"aria-hidden": true
			})
		})]
	});
}
//#endregion
//#region ../../contacts/ui/src/portal/hooks/contacts/use-toggle-task-completion.ts
function useToggleTaskCompletion(contactId) {
	const queryClient = useQueryClient();
	const api = useTasksApi();
	return useMutation({
		mutationFn: ({ taskId, isCompleted }) => api.updateTask(taskId, contactId, { completed_at: isCompleted ? null : (/* @__PURE__ */ new Date()).toISOString() }),
		onSuccess: () => {
			queryClient.invalidateQueries({ queryKey: contactsKeys.tasks(contactId) });
		},
		onError: (error) => {
			fluidToast({
				title: "Failed to update task",
				type: "error",
				description: parseApiErrors(error)
			});
		}
	});
}
//#endregion
//#region ../../contacts/ui/src/portal/hooks/contacts/use-delete-contact-task.ts
function useDeleteContactTask(contactId, options) {
	const queryClient = useQueryClient();
	const api = useTasksApi();
	return useMutation({
		mutationFn: (taskId) => api.deleteTask(taskId, contactId),
		onSuccess: () => {
			fluidToast({
				title: "Task deleted",
				type: "success"
			});
			queryClient.invalidateQueries({ queryKey: contactsKeys.tasks(contactId) });
			options?.onSuccess?.();
		},
		onError: (error) => {
			fluidToast({
				title: "Failed to delete task",
				type: "error",
				description: parseApiErrors(error)
			});
		}
	});
}
//#endregion
//#region ../../contacts/ui/src/portal/hooks/contacts/use-update-contact-task.ts
function useUpdateContactTask(contactId, options) {
	const queryClient = useQueryClient();
	const api = useTasksApi();
	return useMutation({
		mutationFn: ({ taskId, input }) => api.updateTask(taskId, contactId, input),
		onSuccess: () => {
			fluidToast({
				title: "Task updated",
				type: "success"
			});
			queryClient.invalidateQueries({ queryKey: contactsKeys.tasks(contactId) });
			options?.onSuccess?.();
		},
		onError: (error) => {
			fluidToast({
				title: "Failed to update task",
				type: "error",
				description: parseApiErrors(error)
			});
		}
	});
}
//#endregion
//#region ../../contacts/ui/src/portal/utils/format-date.ts
function formatDateForDisplay(dateStr) {
	return new Date(dateStr).toLocaleDateString("en-US", {
		month: "short",
		day: "numeric",
		year: "numeric"
	});
}
//#endregion
//#region ../../contacts/ui/src/portal/components/editor/note-task-editor.tsx
function extractTitleAndBody(editor) {
	if (!editor) return {
		title: "",
		body: ""
	};
	const doc = editor.state.doc;
	let title = "";
	const bodyParts = [];
	doc.forEach((node) => {
		if (node.type.name === "heading" && !title) title = node.textContent.trim();
		else {
			const text = node.textContent.trim();
			if (text) bodyParts.push(text);
		}
	});
	return {
		title,
		body: bodyParts.join("\n")
	};
}
function extractBodyOnly(editor) {
	if (!editor) return "";
	const parts = [];
	editor.state.doc.forEach((node) => {
		const text = node.textContent.trim();
		if (text) parts.push(text);
	});
	return parts.join("\n");
}
function NoteTaskEditor({ titlePlaceholder = "New Note", bodyPlaceholder = "Start writing...", onChange, className, initialTitle, initialBody, showDueDate = false, initialDueDate, showTitle = true, editorClassName }) {
	const [dueDate, setDueDate] = useState(initialDueDate);
	const dueDateRef = useRef(initialDueDate);
	const dateInputRef = useRef(null);
	useEffect(() => {
		dueDateRef.current = dueDate;
	}, [dueDate]);
	const initialContent = showTitle ? initialTitle || initialBody ? `<h1>${initialTitle ?? ""}</h1>${initialBody ?? ""}` : void 0 : initialBody || void 0;
	const editor = useEditor({
		extensions: [
			StarterKit.configure({
				heading: showTitle ? false : { levels: [] },
				bulletList: {
					keepMarks: true,
					keepAttributes: false
				},
				orderedList: {
					keepMarks: true,
					keepAttributes: false
				}
			}),
			...showTitle ? [Heading.configure({ levels: [1] })] : [],
			Placeholder.configure({ placeholder: ({ node }) => {
				if (node.type.name === "heading") return titlePlaceholder;
				return bodyPlaceholder;
			} }),
			TextAlign.configure({
				types: showTitle ? ["heading", "paragraph"] : ["paragraph"],
				alignments: [
					"left",
					"center",
					"right",
					"justify"
				]
			}),
			Underline
		],
		content: initialContent ?? (showTitle ? {
			type: "doc",
			content: [{
				type: "heading",
				attrs: { level: 1 }
			}]
		} : void 0),
		onUpdate: ({ editor }) => {
			if (showTitle) {
				const { title, body } = extractTitleAndBody(editor);
				onChange?.({
					title,
					body,
					dueDate: dueDateRef.current
				});
			} else {
				const body = extractBodyOnly(editor);
				onChange?.({
					title: "",
					body,
					dueDate: dueDateRef.current
				});
			}
		}
	});
	const fireOnChange = () => {
		if (!editor || !onChange) return;
		if (showTitle) {
			const { title, body } = extractTitleAndBody(editor);
			onChange({
				title,
				body,
				dueDate
			});
		} else onChange({
			title: "",
			body: extractBodyOnly(editor),
			dueDate
		});
	};
	useEffect(() => {
		fireOnChange();
	}, [editor]);
	useEffect(() => {
		fireOnChange();
	}, [dueDate]);
	const buttonBase = "flex h-7 w-7 items-center justify-center rounded text-xs transition-colors";
	const buttonActive = "bg-muted text-primary";
	const buttonInactive = "text-muted-foreground hover:bg-muted/50";
	const toolbarSeparator = /* @__PURE__ */ jsx("div", { className: "bg-border mx-1 h-5 w-px" });
	return /* @__PURE__ */ jsxs("div", {
		className: cn("border-border/50 flex flex-col overflow-hidden rounded-lg border", className),
		children: [
			/* @__PURE__ */ jsxs("div", {
				className: "border-border/50 bg-muted/50 flex items-center gap-0.5 border-b px-2 py-1.5",
				children: [
					/* @__PURE__ */ jsx("button", {
						type: "button",
						onClick: () => editor?.chain().focus().toggleBold().run(),
						disabled: !editor?.can().chain().focus().toggleBold().run(),
						className: cn(buttonBase, "font-bold", editor?.isActive("bold") ? buttonActive : buttonInactive),
						title: "Bold",
						children: "B"
					}),
					/* @__PURE__ */ jsx("button", {
						type: "button",
						onClick: () => editor?.chain().focus().toggleItalic().run(),
						disabled: !editor?.can().chain().focus().toggleItalic().run(),
						className: cn(buttonBase, "italic", editor?.isActive("italic") ? buttonActive : buttonInactive),
						title: "Italic",
						children: "I"
					}),
					/* @__PURE__ */ jsx("button", {
						type: "button",
						onClick: () => editor?.chain().focus().toggleUnderline().run(),
						disabled: !editor?.can().chain().focus().toggleUnderline().run(),
						className: cn(buttonBase, "underline", editor?.isActive("underline") ? buttonActive : buttonInactive),
						title: "Underline",
						children: "U"
					}),
					toolbarSeparator,
					/* @__PURE__ */ jsx("button", {
						type: "button",
						onClick: () => editor?.chain().focus().setTextAlign("left").run(),
						className: cn(buttonBase, editor?.isActive({ textAlign: "left" }) ? buttonActive : buttonInactive),
						title: "Align left",
						children: /* @__PURE__ */ jsx(AlignLeft, { className: "size-3.5" })
					}),
					/* @__PURE__ */ jsx("button", {
						type: "button",
						onClick: () => editor?.chain().focus().setTextAlign("center").run(),
						className: cn(buttonBase, editor?.isActive({ textAlign: "center" }) ? buttonActive : buttonInactive),
						title: "Align center",
						children: /* @__PURE__ */ jsx(AlignCenter, { className: "size-3.5" })
					}),
					/* @__PURE__ */ jsx("button", {
						type: "button",
						onClick: () => editor?.chain().focus().setTextAlign("right").run(),
						className: cn(buttonBase, editor?.isActive({ textAlign: "right" }) ? buttonActive : buttonInactive),
						title: "Align right",
						children: /* @__PURE__ */ jsx(AlignRight, { className: "size-3.5" })
					}),
					/* @__PURE__ */ jsx("button", {
						type: "button",
						onClick: () => editor?.chain().focus().setTextAlign("justify").run(),
						className: cn(buttonBase, editor?.isActive({ textAlign: "justify" }) ? buttonActive : buttonInactive),
						title: "Justify",
						children: /* @__PURE__ */ jsx(AlignJustify, { className: "size-3.5" })
					}),
					toolbarSeparator,
					/* @__PURE__ */ jsx("button", {
						type: "button",
						onClick: () => editor?.chain().focus().toggleBulletList().run(),
						className: cn(buttonBase, editor?.isActive("bulletList") ? buttonActive : buttonInactive),
						title: "Bullet list",
						children: /* @__PURE__ */ jsx(List, { className: "size-3.5" })
					}),
					/* @__PURE__ */ jsx("button", {
						type: "button",
						onClick: () => editor?.chain().focus().toggleOrderedList().run(),
						className: cn(buttonBase, editor?.isActive("orderedList") ? buttonActive : buttonInactive),
						title: "Ordered list",
						children: /* @__PURE__ */ jsx(ListOrdered, { className: "size-3.5" })
					}),
					showDueDate && /* @__PURE__ */ jsxs(Fragment$1, { children: [toolbarSeparator, dueDate ? /* @__PURE__ */ jsxs("div", {
						className: "bg-primary/10 flex items-center gap-1 rounded px-2 py-1",
						children: [
							/* @__PURE__ */ jsx(Calendar, { className: "text-primary size-3.5" }),
							/* @__PURE__ */ jsx("span", {
								className: "text-primary text-xs font-medium",
								children: formatDateForDisplay(dueDate)
							}),
							/* @__PURE__ */ jsx("button", {
								type: "button",
								onClick: () => setDueDate(void 0),
								className: "text-primary/60 hover:text-primary ml-1",
								title: "Remove due date",
								children: /* @__PURE__ */ jsx(X, { className: "size-3" })
							})
						]
					}) : /* @__PURE__ */ jsxs(Fragment$1, { children: [/* @__PURE__ */ jsxs("button", {
						type: "button",
						onClick: () => dateInputRef.current?.showPicker(),
						className: "text-muted-foreground hover:bg-muted hover:text-foreground flex h-7 cursor-pointer items-center gap-1 rounded px-2 text-xs font-medium transition-colors",
						children: [/* @__PURE__ */ jsx(Calendar, { className: "size-3.5" }), /* @__PURE__ */ jsx("span", { children: "Due date" })]
					}), /* @__PURE__ */ jsx("input", {
						ref: dateInputRef,
						type: "date",
						className: "invisible absolute size-0",
						onChange: (e) => {
							if (e.target.value) setDueDate((/* @__PURE__ */ new Date(e.target.value + "T00:00:00")).toISOString());
						}
					})] })] })
				]
			}),
			/* @__PURE__ */ jsx(EditorContent, {
				editor,
				className: editorClassName ?? "min-h-[60vh] flex-1 overflow-y-auto p-4"
			}),
			/* @__PURE__ */ jsx("style", { children: `
        .ProseMirror {
          outline: none;
        }

        .ProseMirror h1 {
          font-size: 1.5rem;
          font-weight: 600;
          line-height: 1.3;
          margin-bottom: 0.5rem;
        }

        .ProseMirror h1.is-empty::before,
        .ProseMirror p.is-empty::before {
          color: var(--color-muted-foreground);
          content: attr(data-placeholder);
          float: left;
          height: 0;
          pointer-events: none;
        }

        .ProseMirror ul {
          list-style-type: disc;
          padding-left: 1.5rem;
          margin: 0.5rem 0;
        }

        .ProseMirror ol {
          list-style-type: decimal;
          padding-left: 1.5rem;
          margin: 0.5rem 0;
        }

        .ProseMirror li {
          margin: 0.25rem 0;
          display: list-item;
        }

        .ProseMirror li > p {
          margin: 0;
        }
      ` })
		]
	});
}
//#endregion
//#region ../../contacts/ui/src/portal/components/editor/note-task-modal.tsx
function NoteTaskModal({ open, onOpenChange, mode, type, initialTitle = "", initialBody = "", initialDueDate, showDueDate = false, onSave, isPending = false, isCompleted, onToggleComplete, isTogglePending = false }) {
	const [title, setTitle] = useState(initialTitle);
	const [body, setBody] = useState(initialBody);
	const dateInputRef = useRef(null);
	const [dueDate, setDueDate] = useState(initialDueDate);
	const typeLabel = type === "note" ? "Note" : "Task";
	const sheetTitle = mode === "edit" ? `Edit ${typeLabel}` : `New ${typeLabel}`;
	const requiresBody = type === "note";
	const canSave = !!title.trim() && (!requiresBody || !!body.trim()) && !isPending;
	const handleSave = () => {
		if (!canSave) return;
		onSave({
			title: title.trim(),
			body,
			dueDate
		});
	};
	return /* @__PURE__ */ jsx(Sheet, {
		open,
		onOpenChange,
		children: /* @__PURE__ */ jsxs(SheetContent, {
			className: "flex w-full flex-col sm:max-w-lg",
			children: [
				/* @__PURE__ */ jsx(SheetHeader, { children: /* @__PURE__ */ jsx(SheetTitle, { children: sheetTitle }) }),
				/* @__PURE__ */ jsxs("div", {
					className: "flex min-h-0 flex-1 flex-col gap-3",
					children: [
						/* @__PURE__ */ jsx(Input, {
							placeholder: `${typeLabel} title`,
							value: title,
							onChange: (e) => setTitle(e.target.value),
							autoFocus: true
						}),
						/* @__PURE__ */ jsx(NoteTaskEditor, {
							showTitle: false,
							bodyPlaceholder: "Start writing...",
							initialBody,
							editorClassName: "min-h-[200px] flex-1 overflow-y-auto p-4",
							onChange: (content) => {
								setBody(content.body);
							}
						}),
						showDueDate && /* @__PURE__ */ jsx("div", {
							className: "flex items-center gap-2",
							children: dueDate ? /* @__PURE__ */ jsxs("div", {
								className: "bg-primary/10 inline-flex items-center gap-1.5 rounded-md px-2.5 py-1.5",
								children: [
									/* @__PURE__ */ jsx(Calendar, { className: "text-primary size-3.5" }),
									/* @__PURE__ */ jsxs("span", {
										className: "text-primary text-sm font-medium",
										children: ["Due ", formatDateForDisplay(dueDate)]
									}),
									/* @__PURE__ */ jsx("button", {
										type: "button",
										onClick: () => setDueDate(void 0),
										className: "text-primary/60 hover:text-primary ml-1",
										title: "Remove due date",
										children: /* @__PURE__ */ jsx(X, { className: "size-3" })
									})
								]
							}) : /* @__PURE__ */ jsxs("div", {
								className: "relative",
								children: [/* @__PURE__ */ jsxs("button", {
									type: "button",
									onClick: () => dateInputRef.current?.showPicker(),
									className: "text-muted-foreground hover:text-foreground hover:bg-muted inline-flex cursor-pointer items-center gap-1.5 rounded-md px-2.5 py-1.5 text-sm font-medium transition-colors",
									children: [/* @__PURE__ */ jsx(Calendar, { className: "size-3.5" }), /* @__PURE__ */ jsx("span", { children: "Add due date" })]
								}), /* @__PURE__ */ jsx("input", {
									ref: dateInputRef,
									type: "date",
									className: "invisible absolute size-0",
									onChange: (e) => {
										if (e.target.value) setDueDate((/* @__PURE__ */ new Date(e.target.value + "T00:00:00")).toISOString());
									}
								})]
							})
						})
					]
				}),
				/* @__PURE__ */ jsxs(SheetFooter, {
					className: "flex-row justify-end gap-2 border-t pt-4",
					children: [
						mode === "edit" && onToggleComplete && /* @__PURE__ */ jsx(Button, {
							variant: "outline",
							onClick: onToggleComplete,
							disabled: isTogglePending,
							className: "mr-auto",
							children: isCompleted ? "Mark Incomplete" : "Mark Complete"
						}),
						/* @__PURE__ */ jsx(Button, {
							variant: "outline",
							onClick: () => onOpenChange(false),
							children: "Cancel"
						}),
						/* @__PURE__ */ jsx(Button, {
							onClick: handleSave,
							disabled: !canSave,
							children: isPending ? "Saving..." : "Save"
						})
					]
				})
			]
		})
	});
}
//#endregion
//#region ../../contacts/ui/src/portal/components/tasks/task-list.tsx
function formatDueDate$1(dateStr) {
	return new Date(dateStr).toLocaleDateString("en-US", {
		month: "short",
		day: "numeric",
		year: "numeric"
	});
}
function formatRelativeTime(dateStr, t) {
	const date = new Date(dateStr);
	const diffMs = (/* @__PURE__ */ new Date()).getTime() - date.getTime();
	const diffDays = Math.floor(diffMs / (1e3 * 60 * 60 * 24));
	if (diffDays === 0) return date.toLocaleTimeString("en-US", {
		hour: "numeric",
		minute: "2-digit"
	});
	if (diffDays === 1) return t("task_yesterday");
	return diffDays === 1 ? t("task_days_ago_one") : t("task_days_ago_other", { count: diffDays });
}
function classifyDue(dueAt, isCompleted, t) {
	if (isCompleted) return {
		label: t("task_due", { date: formatDueDate$1(dueAt) }),
		tone: "done"
	};
	const due = startOfLocalDay(dueAt);
	const today = startOfLocalDay(/* @__PURE__ */ new Date());
	const tomorrow = new Date(today);
	tomorrow.setDate(today.getDate() + 1);
	const dueTime = due.getTime();
	if (dueTime < today.getTime()) return {
		label: t("task_overdue_due", { date: formatDueDate$1(dueAt) }),
		tone: "overdue"
	};
	if (dueTime === today.getTime()) return {
		label: t("quick_today"),
		tone: "today"
	};
	if (dueTime === tomorrow.getTime()) return {
		label: t("quick_tomorrow"),
		tone: "tomorrow"
	};
	return {
		label: formatDueDate$1(dueAt),
		tone: "future"
	};
}
const DUE_TONE_CLASS = {
	overdue: "bg-destructive/10 text-destructive",
	today: "bg-primary/10 text-primary",
	tomorrow: "bg-primary/10 text-primary",
	future: "bg-muted text-muted-foreground",
	done: "bg-muted text-muted-foreground"
};
function TaskCard({ task, toggleCompletion, onEdit, onDeleteClick }) {
	const { t } = useContactsTranslation();
	const isCompleted = !!task.completed_at;
	const { title, body: bodyText } = parseTaskBody(task.body ?? "");
	const timestamp = task.created_at ? formatRelativeTime(task.created_at, t) : "";
	const due = task.due_at ? classifyDue(task.due_at, isCompleted, t) : null;
	return /* @__PURE__ */ jsxs("div", {
		role: "button",
		tabIndex: 0,
		onClick: () => onEdit(task),
		onKeyDown: (e) => {
			if (e.key === "Enter" || e.key === " ") {
				e.preventDefault();
				onEdit(task);
			}
		},
		className: "group border-border/50 hover:border-foreground/20 hover:bg-muted/40 relative cursor-pointer rounded-xl border p-4 transition-all hover:shadow-sm",
		children: [/* @__PURE__ */ jsxs("div", {
			className: "flex items-start gap-3",
			children: [/* @__PURE__ */ jsx("button", {
				type: "button",
				onClick: (e) => {
					e.stopPropagation();
					toggleCompletion.mutate({
						taskId: task.id,
						isCompleted
					});
				},
				disabled: toggleCompletion.isPending,
				className: "mt-0.5 shrink-0 transition-transform hover:scale-110 disabled:cursor-not-allowed disabled:opacity-50",
				"aria-label": isCompleted ? t("mark_as_open") : t("mark_as_completed"),
				children: isCompleted ? /* @__PURE__ */ jsx(CircleCheck, {
					className: "text-primary size-5",
					"aria-hidden": "true"
				}) : /* @__PURE__ */ jsx("div", { className: "border-muted-foreground/40 group-hover:border-primary size-5 rounded-full border-2 transition-colors" })
			}), /* @__PURE__ */ jsxs("div", {
				className: "min-w-0 flex-1",
				children: [
					/* @__PURE__ */ jsx("h4", {
						className: cn("text-foreground line-clamp-2 text-sm leading-snug font-semibold", isCompleted && "text-muted-foreground line-through"),
						children: title
					}),
					bodyText && /* @__PURE__ */ jsx("p", {
						className: cn("text-muted-foreground mt-1 line-clamp-2 text-xs leading-relaxed", isCompleted && "line-through"),
						children: bodyText
					}),
					(due || timestamp) && /* @__PURE__ */ jsxs("div", {
						className: "mt-2.5 flex flex-wrap items-center gap-1.5",
						children: [due && /* @__PURE__ */ jsxs("span", {
							className: cn("inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-xs font-medium", DUE_TONE_CLASS[due.tone]),
							children: [/* @__PURE__ */ jsx(Calendar, {
								className: "size-3",
								"aria-hidden": "true"
							}), due.label]
						}), timestamp && /* @__PURE__ */ jsx("span", {
							className: "text-muted-foreground/60 text-xs",
							children: timestamp
						})]
					})
				]
			})]
		}), /* @__PURE__ */ jsx("div", {
			className: "absolute top-3 right-3 opacity-0 transition-opacity group-hover:opacity-100 focus-within:opacity-100",
			children: /* @__PURE__ */ jsxs(DropdownMenu, { children: [/* @__PURE__ */ jsx(DropdownMenuTrigger, {
				asChild: true,
				children: /* @__PURE__ */ jsx(Button, {
					variant: "ghost",
					size: "icon-xs",
					onClick: (e) => e.stopPropagation(),
					"aria-label": t("task_actions"),
					children: /* @__PURE__ */ jsx(EllipsisVertical, { className: "size-4" })
				})
			}), /* @__PURE__ */ jsx(DropdownMenuContent, {
				align: "end",
				children: /* @__PURE__ */ jsx(DropdownMenuItem, {
					className: "text-destructive",
					onClick: (e) => {
						e.stopPropagation();
						onDeleteClick(task);
					},
					children: t("delete")
				})
			})] })
		})]
	});
}
function TaskList({ tasks, isLoading, contactId }) {
	const { t } = useContactsTranslation();
	const [taskToDelete, setTaskToDelete] = useState(null);
	const [editingTask, setEditingTask] = useState(null);
	const toggleCompletion = useToggleTaskCompletion(contactId);
	const deleteTask = useDeleteContactTask(contactId, { onSuccess: () => setTaskToDelete(null) });
	const updateTask = useUpdateContactTask(contactId, { onSuccess: () => setEditingTask(null) });
	const handleSave = (data) => {
		if (!editingTask) return;
		const taskBody = data.body ? `${data.title}\n\n${data.body}` : data.title;
		updateTask.mutate({
			taskId: editingTask.id,
			input: {
				body: taskBody,
				due_at: data.dueDate ?? null
			}
		});
	};
	const editingParsed = editingTask ? parseTaskBody(editingTask.body ?? "") : null;
	const handleModalOpenChange = (open) => {
		if (!open) setEditingTask(null);
	};
	if (isLoading) return /* @__PURE__ */ jsx("div", {
		className: "flex flex-col gap-3",
		children: [
			1,
			2,
			3
		].map((i) => /* @__PURE__ */ jsx("div", { className: "border-border/50 bg-muted/50 h-32 animate-pulse rounded-xl border" }, i))
	});
	if (tasks.length === 0) return /* @__PURE__ */ jsx(Fragment$1, {});
	return /* @__PURE__ */ jsxs("div", {
		className: "space-y-4",
		children: [
			/* @__PURE__ */ jsx("div", {
				className: "flex flex-col gap-3",
				children: tasks.map((task) => /* @__PURE__ */ jsx(TaskCard, {
					task,
					toggleCompletion,
					onEdit: setEditingTask,
					onDeleteClick: setTaskToDelete
				}, task.id))
			}),
			/* @__PURE__ */ jsx(NoteTaskModal, {
				open: editingTask !== null,
				onOpenChange: handleModalOpenChange,
				mode: "edit",
				type: "task",
				initialTitle: editingParsed?.title ?? "",
				initialBody: editingParsed?.body ?? "",
				initialDueDate: editingTask?.due_at ?? void 0,
				showDueDate: true,
				onSave: handleSave,
				isPending: updateTask.isPending,
				isCompleted: editingTask ? !!editingTask.completed_at : void 0,
				onToggleComplete: editingTask ? () => toggleCompletion.mutate({
					taskId: editingTask.id,
					isCompleted: !!editingTask.completed_at
				}, { onSuccess: () => setEditingTask(null) }) : void 0,
				isTogglePending: toggleCompletion.isPending
			}, editingTask?.id ?? "edit"),
			/* @__PURE__ */ jsx(AlertDialog, {
				open: taskToDelete !== null,
				onOpenChange: (open) => {
					if (!open) setTaskToDelete(null);
				},
				children: /* @__PURE__ */ jsxs(AlertDialogContent, { children: [/* @__PURE__ */ jsxs(AlertDialogHeader, { children: [/* @__PURE__ */ jsx(AlertDialogTitle, { children: t("delete_task_title") }), /* @__PURE__ */ jsx(AlertDialogDescription, { children: t("delete_task_confirm") })] }), /* @__PURE__ */ jsxs(AlertDialogFooter, { children: [/* @__PURE__ */ jsx(AlertDialogCancel, { children: t("cancel") }), /* @__PURE__ */ jsx(AlertDialogAction, {
					variant: "destructive",
					onClick: () => {
						if (taskToDelete) deleteTask.mutate(taskToDelete.id);
					},
					children: t("delete")
				})] })] })
			})
		]
	});
}
//#endregion
//#region ../../contacts/ui/src/portal/components/tasks/inline-task-composer.tsx
function InlineTaskComposer({ contactId }) {
	const { t } = useContactsTranslation();
	const [isOpen, setIsOpen] = useState(false);
	if (!isOpen) return /* @__PURE__ */ jsxs("button", {
		type: "button",
		onClick: () => setIsOpen(true),
		className: "border-border/50 text-muted-foreground hover:border-foreground/30 hover:bg-muted/40 hover:text-foreground flex w-full items-center gap-3 rounded-xl border border-dashed px-5 py-4 text-sm font-medium transition-colors",
		children: [/* @__PURE__ */ jsx(Plus, {
			className: "size-4",
			"aria-hidden": "true"
		}), t("new_task")]
	});
	const close = () => setIsOpen(false);
	return /* @__PURE__ */ jsx(TaskComposerForm, {
		contactId,
		onClose: close,
		onDone: close
	});
}
//#endregion
//#region ../../contacts/ui/src/portal/hooks/notes/use-delete-contact-note.ts
function useDeleteContactNote(contactId, options) {
	const queryClient = useQueryClient();
	const api = useNotesApi();
	return useMutation({
		mutationFn: (noteId) => api.deleteNote(noteId, contactId),
		onSuccess: () => {
			fluidToast({
				title: "Note deleted",
				type: "success"
			});
			queryClient.invalidateQueries({ queryKey: contactsKeys.notes(contactId) });
			options?.onSuccess?.();
		},
		onError: (error) => {
			fluidToast({
				title: "Failed to delete note",
				type: "error",
				description: parseApiErrors(error)
			});
		}
	});
}
//#endregion
//#region ../../contacts/ui/src/portal/hooks/notes/use-update-contact-note.ts
function useUpdateContactNote(contactId, options) {
	const queryClient = useQueryClient();
	const api = useNotesApi();
	return useMutation({
		mutationFn: ({ noteId, input }) => api.updateNote(noteId, contactId, input),
		onSuccess: () => {
			fluidToast({
				title: "Note updated",
				type: "success"
			});
			queryClient.invalidateQueries({ queryKey: contactsKeys.notes(contactId) });
			options?.onSuccess?.();
		},
		onError: (error) => {
			fluidToast({
				title: "Failed to update note",
				type: "error",
				description: parseApiErrors(error)
			});
		}
	});
}
//#endregion
//#region ../../contacts/ui/src/portal/hooks/notes/use-create-contact-note.ts
function useCreateContactNote(contactId, options) {
	const queryClient = useQueryClient();
	const api = useNotesApi();
	return useMutation({
		mutationFn: (input) => api.createNote(contactId, input),
		onSuccess: () => {
			fluidToast({
				title: "Note created",
				type: "success"
			});
			queryClient.invalidateQueries({ queryKey: contactsKeys.notes(contactId) });
			options?.onSuccess?.();
		},
		onError: (error) => {
			fluidToast({
				title: "Failed to create note",
				type: "error",
				description: parseApiErrors(error)
			});
		}
	});
}
//#endregion
//#region ../../contacts/ui/src/portal/components/notes/inline-note-composer.tsx
function detectMacPlatform() {
	if (typeof navigator === "undefined") return false;
	const platform = navigator.userAgentData?.platform ?? navigator.userAgent ?? "";
	return /Mac|iPhone|iPad/i.test(platform);
}
function InlineNoteComposer({ contactId }) {
	const { t } = useContactsTranslation();
	const [body, setBody] = useState("");
	const [isFocused, setIsFocused] = useState(false);
	const [isMac, setIsMac] = useState(false);
	const textareaRef = useRef(null);
	useEffect(() => {
		setIsMac(detectMacPlatform());
	}, []);
	const createNote = useCreateContactNote(contactId, { onSuccess: () => {
		setBody("");
		textareaRef.current?.blur();
	} });
	const submit = () => {
		const trimmed = body.trim();
		if (!trimmed || createNote.isPending) return;
		const firstLine = trimmed.split("\n")[0]?.slice(0, 120) ?? "Note";
		createNote.mutate({
			title: firstLine,
			body: trimmed
		});
	};
	const canSubmit = body.trim().length > 0 && !createNote.isPending;
	return /* @__PURE__ */ jsxs("div", {
		className: cn("border-border/50 focus-within:border-foreground/30 rounded-2xl border p-4 transition-colors", isFocused && "border-foreground/30"),
		children: [/* @__PURE__ */ jsx("textarea", {
			ref: textareaRef,
			value: body,
			onChange: (e) => setBody(e.target.value),
			onFocus: () => setIsFocused(true),
			onBlur: () => setIsFocused(false),
			onKeyDown: (e) => {
				if ((e.metaKey || e.ctrlKey) && e.key === "Enter") {
					e.preventDefault();
					submit();
				}
			},
			placeholder: t("note_placeholder"),
			"aria-label": t("note_body_aria"),
			rows: 3,
			className: "placeholder:text-muted-foreground text-foreground min-h-[80px] w-full resize-none border-0 bg-transparent text-sm leading-relaxed outline-none"
		}), /* @__PURE__ */ jsxs("div", {
			className: "mt-3 flex items-center justify-between gap-3",
			children: [/* @__PURE__ */ jsx("span", {
				className: "text-muted-foreground text-xs",
				children: isMac ? t("tip_save_shortcut_mac") : t("tip_save_shortcut_other")
			}), /* @__PURE__ */ jsx("button", {
				type: "button",
				onClick: submit,
				disabled: !canSubmit,
				className: "bg-primary text-primary-foreground hover:bg-primary/90 disabled:bg-muted disabled:text-muted-foreground inline-flex shrink-0 items-center gap-1.5 rounded-full px-4 py-1.5 text-xs font-semibold transition-colors disabled:cursor-not-allowed",
				children: createNote.isPending ? t("adding") : t("add_note")
			})]
		})]
	});
}
//#endregion
//#region ../../contacts/ui/src/portal/components/notes/notes-list.tsx
function formatDueDate(dateStr) {
	return new Date(dateStr).toLocaleDateString("en-US", {
		month: "short",
		day: "numeric",
		year: "numeric"
	});
}
function formatRelativeNote(dateStr, t) {
	const date = new Date(dateStr);
	const diffMs = (/* @__PURE__ */ new Date()).getTime() - date.getTime();
	const diffDays = Math.floor(diffMs / (1e3 * 60 * 60 * 24));
	if (diffDays === 0) return date.toLocaleTimeString("en-US", {
		hour: "numeric",
		minute: "2-digit"
	});
	if (diffDays === 1) return t("task_yesterday");
	if (diffDays < 7) return t("task_days_ago_other", { count: diffDays });
	return formatDueDate(dateStr);
}
function NoteCard({ note, onEdit, onDelete }) {
	const { t } = useContactsTranslation();
	const assetCount = note.assets?.length ?? 0;
	const showTitle = !!note.title?.trim() && note.title.trim() !== note.body?.trim();
	const dueDateValue = note.due_at ?? note.due_date ?? null;
	const createdLabel = note.created_at ? formatRelativeNote(note.created_at, t) : null;
	return /* @__PURE__ */ jsxs("div", {
		role: "button",
		tabIndex: 0,
		onClick: () => onEdit(note),
		onKeyDown: (e) => {
			if (e.key === "Enter" || e.key === " ") {
				e.preventDefault();
				onEdit(note);
			}
		},
		className: "group border-border/50 hover:border-foreground/20 hover:bg-muted/40 relative cursor-pointer rounded-xl border p-4 transition-all hover:shadow-sm",
		children: [
			showTitle && /* @__PURE__ */ jsx("h4", {
				className: "text-foreground line-clamp-1 text-sm font-semibold",
				children: note.title
			}),
			/* @__PURE__ */ jsx("p", {
				className: cn("text-foreground line-clamp-4 text-sm leading-relaxed whitespace-pre-wrap", showTitle && "text-muted-foreground mt-1"),
				children: note.body
			}),
			(createdLabel || dueDateValue || assetCount > 0) && /* @__PURE__ */ jsxs("div", {
				className: "mt-2.5 flex flex-wrap items-center gap-3",
				children: [
					createdLabel && /* @__PURE__ */ jsx("span", {
						className: "text-muted-foreground/70 text-xs",
						children: createdLabel
					}),
					dueDateValue && /* @__PURE__ */ jsxs("span", {
						className: "bg-primary/10 text-primary inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-xs font-medium",
						children: [/* @__PURE__ */ jsx(Calendar, {
							className: "size-3",
							"aria-hidden": "true"
						}), t("task_due", { date: formatDueDate(dueDateValue) })]
					}),
					assetCount > 0 && /* @__PURE__ */ jsxs("span", {
						className: "text-muted-foreground inline-flex items-center gap-1 text-xs",
						children: [/* @__PURE__ */ jsx(Paperclip, {
							className: "size-3",
							"aria-hidden": "true"
						}), assetCount === 1 ? t("attachment_one") : t("attachment_other", { count: assetCount })]
					})
				]
			}),
			/* @__PURE__ */ jsx("div", {
				className: "absolute top-3 right-3 opacity-0 transition-opacity group-hover:opacity-100 focus-within:opacity-100",
				children: /* @__PURE__ */ jsxs(DropdownMenu, { children: [/* @__PURE__ */ jsx(DropdownMenuTrigger, {
					asChild: true,
					children: /* @__PURE__ */ jsx(Button, {
						variant: "ghost",
						size: "icon-xs",
						onClick: (e) => e.stopPropagation(),
						"aria-label": t("note_actions"),
						children: /* @__PURE__ */ jsx(EllipsisVertical, { className: "size-4" })
					})
				}), /* @__PURE__ */ jsx(DropdownMenuContent, {
					align: "end",
					children: /* @__PURE__ */ jsx(DropdownMenuItem, {
						className: "text-destructive",
						onClick: (e) => {
							e.stopPropagation();
							onDelete(note);
						},
						children: t("delete")
					})
				})] })
			})
		]
	});
}
function NotesList({ notes, isLoading, contactId }) {
	const { t } = useContactsTranslation();
	const [noteToDelete, setNoteToDelete] = useState(null);
	const [editingNote, setEditingNote] = useState(null);
	const deleteNote = useDeleteContactNote(contactId, { onSuccess: () => setNoteToDelete(null) });
	const updateNote = useUpdateContactNote(contactId, { onSuccess: () => setEditingNote(null) });
	const handleEditSave = (data) => {
		if (!editingNote) return;
		updateNote.mutate({
			noteId: editingNote.id,
			input: {
				title: data.title,
				body: data.body
			}
		});
	};
	return /* @__PURE__ */ jsxs("div", {
		className: "space-y-4",
		children: [
			/* @__PURE__ */ jsx(InlineNoteComposer, { contactId }),
			isLoading ? /* @__PURE__ */ jsx("div", {
				className: "flex flex-col gap-3",
				children: [
					1,
					2,
					3
				].map((i) => /* @__PURE__ */ jsx("div", { className: "border-border/50 bg-muted/50 h-20 animate-pulse rounded-xl border" }, i))
			}) : notes.length === 0 ? null : /* @__PURE__ */ jsx("div", {
				className: "flex flex-col gap-3",
				children: notes.map((note) => /* @__PURE__ */ jsx(NoteCard, {
					note,
					onEdit: setEditingNote,
					onDelete: setNoteToDelete
				}, note.id))
			}),
			/* @__PURE__ */ jsx(NoteTaskModal, {
				open: editingNote !== null,
				onOpenChange: (open) => {
					if (!open) setEditingNote(null);
				},
				mode: "edit",
				type: "note",
				initialTitle: editingNote?.title ?? "",
				initialBody: editingNote?.body ?? "",
				onSave: handleEditSave,
				isPending: updateNote.isPending
			}, editingNote?.id ?? "edit"),
			/* @__PURE__ */ jsx(AlertDialog, {
				open: !!noteToDelete,
				onOpenChange: (open) => {
					if (!open) setNoteToDelete(null);
				},
				children: /* @__PURE__ */ jsxs(AlertDialogContent, { children: [/* @__PURE__ */ jsxs(AlertDialogHeader, { children: [/* @__PURE__ */ jsx(AlertDialogTitle, { children: t("delete_note_title") }), /* @__PURE__ */ jsx(AlertDialogDescription, { children: t("delete_note_irreversible") })] }), /* @__PURE__ */ jsxs(AlertDialogFooter, { children: [/* @__PURE__ */ jsx(AlertDialogCancel, { children: t("cancel") }), /* @__PURE__ */ jsx(AlertDialogAction, {
					variant: "destructive",
					onClick: () => {
						if (noteToDelete) deleteNote.mutate(noteToDelete.id);
					},
					children: t("delete")
				})] })] })
			})
		]
	});
}
//#endregion
//#region ../../contacts/ui/src/portal/components/contacts/rep-layout/ContactDetailTabs.tsx
const VISIBLE_TABS = ["Tasks", "Notes"];
function ContactDetailTabs({ contactId, tasks, isLoadingTasks, notes, isLoadingNotes, activeTab, onTabChange }) {
	const { t } = useContactsTranslation();
	const tabLabels = {
		Tasks: t("tab_tasks"),
		Notes: t("tab_notes")
	};
	return /* @__PURE__ */ jsxs("div", {
		className: "mt-8",
		children: [/* @__PURE__ */ jsx("div", {
			className: "border-border/50 flex items-center gap-1 border-b",
			children: VISIBLE_TABS.map((tab) => {
				const count = tab === "Tasks" ? tasks.length : notes.length;
				const isActive = activeTab === tab;
				return /* @__PURE__ */ jsxs("button", {
					type: "button",
					onClick: () => onTabChange(tab),
					className: cn("relative flex items-center gap-1.5 px-3 py-2.5 text-sm font-semibold transition-colors", isActive ? "text-foreground" : "text-muted-foreground hover:text-foreground"),
					children: [
						tabLabels[tab],
						/* @__PURE__ */ jsx("span", {
							className: cn("rounded-full px-1.5 text-xs leading-5 font-bold", isActive ? "bg-primary text-primary-foreground" : "bg-muted text-muted-foreground"),
							children: count
						}),
						isActive && /* @__PURE__ */ jsx("span", {
							className: "bg-primary absolute inset-x-0 -bottom-px h-0.5",
							"aria-hidden": "true"
						})
					]
				}, tab);
			})
		}), /* @__PURE__ */ jsxs("div", {
			className: "pt-6",
			children: [activeTab === "Tasks" && /* @__PURE__ */ jsxs("div", {
				className: "space-y-4",
				children: [/* @__PURE__ */ jsx(InlineTaskComposer, { contactId }), /* @__PURE__ */ jsx(TaskList, {
					tasks,
					isLoading: isLoadingTasks,
					contactId,
					hideHeader: true
				})]
			}), activeTab === "Notes" && /* @__PURE__ */ jsx(NotesList, {
				notes,
				isLoading: isLoadingNotes,
				contactId
			})]
		})]
	});
}
//#endregion
//#region ../../contacts/ui/src/portal/components/contacts/rep-layout/ContactDetailPane.tsx
function ContactDetailPane({ contactId, queryKeyPrefix, getCountries, onBack }) {
	const { t } = useContactsTranslation();
	const { contact, isLoading, methods, countryOptions, isDirty, isSubmitting, isDeleting, onSave, onDelete } = useContactDetailPage(contactId, {
		queryKeyPrefix,
		getCountries,
		onDeleteSuccess: onBack,
		onSaveSuccess: () => setEditProfileOpen(false)
	});
	const { data: tasks = [], isLoading: isLoadingTasks } = useContactTasks(contactId);
	const { data: notes = [], isLoading: isLoadingNotes } = useContactNotes(contactId);
	const [confirmDelete, setConfirmDelete] = useState(false);
	const [activeTab, setActiveTab] = useState("Tasks");
	const [editProfileOpen, setEditProfileOpen] = useState(false);
	const handleConfirmDelete = useCallback(() => {
		setConfirmDelete(false);
		onDelete();
	}, [onDelete]);
	if (isLoading) return /* @__PURE__ */ jsx(ContactDetailSkeleton, { onBack });
	if (!contact) return /* @__PURE__ */ jsxs("div", {
		className: "flex h-full flex-1 flex-col",
		children: [/* @__PURE__ */ jsx(DetailTopBar, {
			onBack,
			phone: null,
			email: null,
			onDelete: null,
			onEditProfile: null
		}), /* @__PURE__ */ jsxs("div", {
			className: "mx-auto flex max-w-md flex-col items-center px-6 py-16 text-center",
			children: [/* @__PURE__ */ jsx("h2", {
				className: "text-foreground text-base font-semibold",
				children: t("error_loading")
			}), /* @__PURE__ */ jsx("p", {
				className: "text-muted-foreground mt-2 text-sm",
				children: t("error_loading_description")
			})]
		})]
	});
	const fullName = getDisplayName(contact);
	return /* @__PURE__ */ jsx(FormProvider, {
		...methods,
		children: /* @__PURE__ */ jsxs("div", {
			className: "flex h-full flex-1 flex-col",
			children: [
				/* @__PURE__ */ jsx(DetailTopBar, {
					onBack,
					phone: contact.phone ?? null,
					email: contact.email ?? null,
					onDelete: () => setConfirmDelete(true),
					onEditProfile: () => setEditProfileOpen(true)
				}),
				/* @__PURE__ */ jsx("div", {
					className: "flex-1 overflow-y-auto",
					children: /* @__PURE__ */ jsxs("div", {
						className: "mx-auto w-full max-w-[900px] px-6 pt-8 pb-16 md:px-8 md:pt-10",
						children: [
							/* @__PURE__ */ jsx(ContactDetailHero, {
								contact,
								tasksCount: tasks.length,
								notesCount: notes.length
							}),
							/* @__PURE__ */ jsx(ContactInfoRow, {
								contact,
								onEditEmpty: () => setEditProfileOpen(true)
							}),
							/* @__PURE__ */ jsx(ContactDetailTabs, {
								contactId,
								tasks,
								isLoadingTasks,
								notes,
								isLoadingNotes,
								activeTab,
								onTabChange: setActiveTab
							})
						]
					})
				}),
				/* @__PURE__ */ jsx(Dialog, {
					open: editProfileOpen,
					onOpenChange: (open) => {
						if (!open && isSubmitting) return;
						setEditProfileOpen(open);
					},
					children: /* @__PURE__ */ jsxs(DialogContent, {
						className: "max-h-[90vh] max-w-2xl overflow-y-auto",
						children: [
							/* @__PURE__ */ jsx(DialogHeader, { children: /* @__PURE__ */ jsx(DialogTitle, { children: t("edit_contact_name", { name: fullName }) }) }),
							/* @__PURE__ */ jsx(ContactDetailsForm, { countries: countryOptions }),
							/* @__PURE__ */ jsxs(DialogFooter, { children: [/* @__PURE__ */ jsx(Button, {
								type: "button",
								variant: "secondary",
								onClick: () => setEditProfileOpen(false),
								disabled: isSubmitting,
								children: t("cancel")
							}), /* @__PURE__ */ jsxs(Button, {
								type: "button",
								onClick: onSave,
								disabled: !isDirty || isSubmitting,
								"aria-busy": isSubmitting,
								children: [isSubmitting && /* @__PURE__ */ jsx(Spinner, { className: "size-4" }), isSubmitting ? t("saving") : t("save_changes")]
							})] })
						]
					})
				}),
				/* @__PURE__ */ jsx(AlertDialog, {
					open: confirmDelete,
					onOpenChange: setConfirmDelete,
					children: /* @__PURE__ */ jsxs(AlertDialogContent, { children: [/* @__PURE__ */ jsxs(AlertDialogHeader, { children: [/* @__PURE__ */ jsx(AlertDialogTitle, { children: t("delete_name", { name: fullName }) }), /* @__PURE__ */ jsx(AlertDialogDescription, { children: t("delete_confirm_permanent") })] }), /* @__PURE__ */ jsxs(AlertDialogFooter, { children: [/* @__PURE__ */ jsx(AlertDialogCancel, {
						disabled: isDeleting,
						children: t("cancel")
					}), /* @__PURE__ */ jsx(AlertDialogAction, {
						variant: "destructive",
						onClick: handleConfirmDelete,
						disabled: isDeleting,
						children: isDeleting ? t("deleting") : t("delete_contact")
					})] })] })
				})
			]
		})
	});
}
function DetailTopBar({ onBack, phone, email, onDelete, onEditProfile }) {
	const { t } = useContactsTranslation();
	return /* @__PURE__ */ jsxs("div", {
		className: "border-border/50 bg-background/90 sticky top-0 z-10 flex items-center justify-between border-b px-4 py-3 backdrop-blur md:px-8",
		children: [/* @__PURE__ */ jsxs("div", {
			className: "flex items-center gap-3",
			children: [/* @__PURE__ */ jsx("button", {
				type: "button",
				onClick: onBack,
				className: "text-muted-foreground hover:bg-muted hover:text-foreground flex size-8 items-center justify-center rounded-full transition-colors md:hidden",
				"aria-label": t("back_to_contacts"),
				children: /* @__PURE__ */ jsx(ChevronLeft, { className: "size-4" })
			}), /* @__PURE__ */ jsx("span", {
				className: "text-muted-foreground hidden text-xs font-semibold tracking-widest uppercase md:inline",
				children: t("contact_label")
			})]
		}), /* @__PURE__ */ jsxs("div", {
			className: "flex items-center gap-1",
			children: [
				onEditProfile && /* @__PURE__ */ jsx("button", {
					type: "button",
					onClick: onEditProfile,
					className: "text-muted-foreground hover:bg-muted hover:text-foreground flex size-8 items-center justify-center rounded-full transition-colors",
					"aria-label": t("edit_profile"),
					children: /* @__PURE__ */ jsx(Pencil, {
						className: "size-4",
						"aria-hidden": "true"
					})
				}),
				/* @__PURE__ */ jsx(ActionLink, {
					href: phone ? `tel:${phone}` : null,
					label: t("label_call"),
					icon: /* @__PURE__ */ jsx(Phone, {
						className: "size-4",
						"aria-hidden": "true"
					})
				}),
				/* @__PURE__ */ jsx(ActionLink, {
					href: email ? `mailto:${email}` : null,
					label: t("label_email"),
					icon: /* @__PURE__ */ jsx(Mail, {
						className: "size-4",
						"aria-hidden": "true"
					})
				}),
				onDelete && /* @__PURE__ */ jsxs(Fragment$1, { children: [/* @__PURE__ */ jsx("div", {
					className: "bg-border mx-1 h-5 w-px",
					"aria-hidden": "true"
				}), /* @__PURE__ */ jsxs(DropdownMenu, { children: [/* @__PURE__ */ jsx(DropdownMenuTrigger, {
					asChild: true,
					children: /* @__PURE__ */ jsx("button", {
						type: "button",
						className: "text-muted-foreground hover:bg-muted hover:text-foreground flex size-8 items-center justify-center rounded-full transition-colors",
						"aria-label": t("more_actions"),
						children: /* @__PURE__ */ jsx(MoreHorizontal, { className: "size-4" })
					})
				}), /* @__PURE__ */ jsx(DropdownMenuContent, {
					align: "end",
					children: /* @__PURE__ */ jsxs(DropdownMenuItem, {
						className: "text-destructive",
						onClick: onDelete,
						children: [/* @__PURE__ */ jsx(Trash2, {
							className: "size-4",
							"aria-hidden": "true"
						}), t("delete_contact")]
					})
				})] })] })
			]
		})]
	});
}
function ActionLink({ href, label, icon }) {
	const baseClass = "flex size-8 items-center justify-center rounded-full transition-colors";
	if (!href) return /* @__PURE__ */ jsx("span", {
		"aria-label": `${label} (unavailable)`,
		className: cn(baseClass, "text-muted-foreground/40 cursor-default"),
		children: icon
	});
	return /* @__PURE__ */ jsx("a", {
		href,
		"aria-label": label,
		className: cn(baseClass, "text-muted-foreground hover:bg-muted hover:text-foreground"),
		children: icon
	});
}
function ContactDetailSkeleton({ onBack }) {
	return /* @__PURE__ */ jsxs("div", {
		className: "flex h-full flex-1 flex-col",
		children: [/* @__PURE__ */ jsx(DetailTopBar, {
			onBack,
			phone: null,
			email: null,
			onDelete: null,
			onEditProfile: null
		}), /* @__PURE__ */ jsxs("div", {
			className: "mx-auto w-full max-w-[900px] flex-1 space-y-6 px-6 pt-8 pb-16 md:px-8 md:pt-10",
			children: [
				/* @__PURE__ */ jsxs("div", {
					className: "flex items-start gap-5",
					children: [/* @__PURE__ */ jsx("div", { className: "bg-muted size-20 animate-pulse rounded-xl" }), /* @__PURE__ */ jsxs("div", {
						className: "flex-1 space-y-3",
						children: [/* @__PURE__ */ jsx("div", { className: "bg-muted h-7 w-48 animate-pulse rounded" }), /* @__PURE__ */ jsx("div", { className: "bg-muted h-4 w-24 animate-pulse rounded" })]
					})]
				}),
				/* @__PURE__ */ jsx("div", { className: "bg-muted h-24 animate-pulse rounded-xl" }),
				/* @__PURE__ */ jsx("div", { className: "bg-muted h-64 animate-pulse rounded-xl" })
			]
		})]
	});
}
//#endregion
//#region ../../contacts/ui/src/portal/components/contacts/rep-layout/ContactsEmptyState.tsx
function ContactsEmptyState() {
	const { t } = useContactsTranslation();
	return /* @__PURE__ */ jsxs("div", {
		className: "hidden h-full flex-1 flex-col items-center justify-center px-8 text-center md:flex",
		children: [
			/* @__PURE__ */ jsx("div", {
				className: "bg-muted text-muted-foreground flex size-16 items-center justify-center rounded-xl",
				children: /* @__PURE__ */ jsx(Users, {
					className: "size-7",
					"aria-hidden": "true"
				})
			}),
			/* @__PURE__ */ jsx("h2", {
				className: "text-foreground mt-5 text-base font-semibold",
				children: t("empty_select_contact")
			}),
			/* @__PURE__ */ jsx("p", {
				className: "text-muted-foreground mt-1 max-w-xs text-sm",
				children: t("empty_select_description")
			})
		]
	});
}
//#endregion
//#region ../../contacts/ui/src/portal/components/contacts/rep-layout/RepContactsLayout.tsx
function RepContactsLayout({ selectedContactId, onSelect, onAdd, queryKeyPrefix, getCountries }) {
	return /* @__PURE__ */ jsxs("div", {
		className: "bg-background flex h-full overflow-hidden",
		children: [/* @__PURE__ */ jsx("aside", {
			className: cn("border-border/50 bg-background w-full shrink-0 overflow-hidden border-r md:flex md:w-[420px] md:flex-col", selectedContactId ? "hidden" : "flex flex-col"),
			children: /* @__PURE__ */ jsx(ContactsSidebar, {
				selectedContactId,
				onSelect,
				onAdd
			})
		}), /* @__PURE__ */ jsx("main", {
			className: cn("bg-background relative flex-1 md:flex md:flex-col", selectedContactId ? "flex flex-col" : "hidden md:flex"),
			children: selectedContactId ? /* @__PURE__ */ jsx(ContactDetailPane, {
				contactId: selectedContactId,
				queryKeyPrefix,
				getCountries,
				onBack: () => onSelect(null)
			}, selectedContactId) : /* @__PURE__ */ jsx(ContactsEmptyState, {})
		})]
	});
}
//#endregion
//#region ../../contacts/ui/src/shared/hooks/useCreateContactMutation.ts
function useCreateContactMutation(queryKeyPrefix = "contacts", options) {
	const queryClient = useQueryClient();
	const api = useContactsCrud();
	return useMutation({
		mutationFn: (data) => api.createContact(data),
		onSuccess: (data) => {
			fluidToast({
				title: "Contact created successfully",
				type: "success"
			});
			queryClient.invalidateQueries({ queryKey: CONTACTS_QUERY_KEYS.all(queryKeyPrefix) });
			options?.onSuccess?.(data);
		},
		onError: (error) => {
			if (options?.onError) options.onError(error);
			else fluidToast({
				title: "Failed to create contact",
				type: "error",
				description: parseApiErrors(error)
			});
		}
	});
}
//#endregion
//#region src/screens/ContactsScreen.tsx
var ContactsScreen_exports = /* @__PURE__ */ __exportAll({
	ContactsScreen: () => ContactsScreen,
	contactsScreenPropertySchema: () => contactsScreenPropertySchema
});
const QUERY_KEY_PREFIX = "sdk-contacts";
function ContactBrowseView({ selectedContactId, onSelect, onAdd }) {
	const countriesAdapter = useCountriesApi();
	return /* @__PURE__ */ jsx(RepContactsLayout, {
		selectedContactId,
		onSelect,
		onAdd,
		queryKeyPrefix: QUERY_KEY_PREFIX,
		getCountries: useCallback(async () => {
			return (await countriesAdapter.listCountries()).countries.map((c) => ({
				id: 0,
				name: c.name,
				iso: c.code
			}));
		}, [countriesAdapter])
	});
}
const CREATE_DEFAULT_VALUES = {
	first_name: "",
	last_name: "",
	email: "",
	phone: "",
	status: "new",
	address: "",
	city: "",
	state: "",
	postal_code: "",
	country_code: null,
	language_code: null,
	metadata: {},
	affiliate: {}
};
function ContactCreateView({ onNavigate, onCreateContact }) {
	const formRef = useRef(null);
	const countriesAdapter = useCountriesApi();
	const { data: countriesResponse } = useQuery({
		queryKey: storeKeys.countries(),
		queryFn: () => countriesAdapter.listCountries()
	});
	const countryOptions = useMemo(() => (countriesResponse?.countries ?? []).map((c) => ({
		name: c.name,
		value: c.code
	})).sort((a, b) => a.name.localeCompare(b.name)), [countriesResponse]);
	const methods = useZodForm(createContactFormSchema, { defaultValues: CREATE_DEFAULT_VALUES });
	const mutation = useCreateContactMutation(QUERY_KEY_PREFIX, { onSuccess: (data) => {
		onCreateContact?.();
		const newContactId = data?.contact?.id;
		if (newContactId) onNavigate({
			view: "browse",
			selectedContactId: String(newContactId)
		});
		else onNavigate({
			view: "browse",
			selectedContactId: null
		});
	} });
	const { mutate } = mutation;
	const onSubmit = useMemo(() => methods.handleSubmit((data) => {
		const { affiliate, ...contactFields } = data;
		const payload = {};
		for (const [key, value] of Object.entries(contactFields)) if (value !== "" && value !== null && value !== void 0) payload[key] = value;
		if (affiliate && Object.keys(affiliate).length > 0) payload.affiliate = affiliate;
		mutate(payload);
	}, () => {}), [methods, mutate]);
	return /* @__PURE__ */ jsx(ContactCreateScreen, {
		onNavigateToList: useCallback(() => {
			onNavigate({
				view: "browse",
				selectedContactId: null
			});
		}, [onNavigate]),
		onSubmit: () => formRef.current?.requestSubmit(),
		isPending: mutation.isPending,
		children: /* @__PURE__ */ jsx(FormProvider, {
			...methods,
			children: /* @__PURE__ */ jsx("div", {
				className: "mx-auto max-w-7xl space-y-12 md:px-10 md:py-8",
				children: /* @__PURE__ */ jsx("form", {
					ref: formRef,
					onSubmit,
					className: "mx-auto space-y-6 lg:max-w-2xl",
					children: /* @__PURE__ */ jsx(ContactDetailsForm, { countries: countryOptions })
				})
			})
		})
	});
}
function ContactsScreen({ onContactSelect, onCreateContact, background, textColor, accentColor, padding, borderRadius, defaultViewMode, ...divProps }) {
	const [nav, setNav] = useState({
		view: "browse",
		selectedContactId: null
	});
	const handleSelect = useCallback((id) => {
		setNav({
			view: "browse",
			selectedContactId: id
		});
		if (id) onContactSelect?.(id);
	}, [onContactSelect]);
	const handleAdd = useCallback(() => {
		setNav({ view: "new" });
	}, []);
	return /* @__PURE__ */ jsxs("div", {
		...divProps,
		className: `h-full ${divProps.className ?? ""}`,
		children: [nav.view === "browse" && /* @__PURE__ */ jsx(ContactBrowseView, {
			selectedContactId: nav.selectedContactId,
			onSelect: handleSelect,
			onAdd: handleAdd
		}), nav.view === "new" && /* @__PURE__ */ jsx(ContactCreateView, {
			onNavigate: setNav,
			onCreateContact
		})]
	});
}
const contactsScreenPropertySchema = {
	widgetType: "ContactsScreen",
	displayName: "Contacts Screen",
	tabsConfig: [{
		id: "styling",
		label: "Styling"
	}],
	fields: []
};
//#endregion
export { ContactsScreen_exports as n, contactsScreenPropertySchema as r, ContactsScreen as t };

//# sourceMappingURL=ContactsScreen-DJ8O35Pl.mjs.map