import { lt as __exportAll } from "./translation-adapter-B-Vhfzbz.mjs";
import { n as useDataSourceRegistryConfig } from "./registry-context-Rn7c5X_k.mjs";
import { r as useWidgetsApi, t as ErrorState } from "./error-state-CmesiiXJ.mjs";
import { i as getBorderColorField, l as getColorField, m as getPaddingField, n as borderWidthClasses, o as getBorderRadiusField, s as getBorderWidthField, t as borderColorClasses, u as getFontSizeField } from "./registries-BZVov8GL.mjs";
import { t as useWidgetPreviewContext } from "./preview-context-BeRbfntP.mjs";
import { useEffect, useMemo, useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { Fragment as Fragment$1, jsx, jsxs } from "react/jsx-runtime";
import { AudioWaveform, Bell, Calendar, CheckSquare, Eye, MessageCircle, Play, ShoppingCart, Star, Trophy, User, UserPlus } from "lucide-react";
//#region ../widgets/src/hooks/use-activities.preview.ts
const now = /* @__PURE__ */ new Date();
function minutesAgo(minutes) {
	return (/* @__PURE__ */ new Date(now.getTime() - minutes * 6e4)).toISOString();
}
const PREVIEW_DATA = [
	{
		id: 1,
		userName: "Sarah Johnson",
		avatarUrl: null,
		activityType: "Order Placed",
		targetName: "Wellness Starter Kit",
		timestamp: minutesAgo(12),
		slug: "order_placed"
	},
	{
		id: 2,
		userName: "Mike Chen",
		avatarUrl: null,
		activityType: "New Lead",
		targetName: "Signed up from Instagram link",
		timestamp: minutesAgo(45),
		slug: "new_lead"
	},
	{
		id: 3,
		userName: "Visitor from Austin, TX",
		avatarUrl: null,
		activityType: "Page Views",
		targetName: "Viewed product catalog (3 pages)",
		timestamp: minutesAgo(90),
		slug: "page_views"
	},
	{
		id: 4,
		userName: "Lisa Park",
		avatarUrl: null,
		activityType: "Video Complete",
		targetName: "Watched: Getting Started Guide",
		timestamp: minutesAgo(180),
		slug: "video_complete"
	}
];
//#endregion
//#region ../widgets/src/hooks/use-activities.ts
function useActivities() {
	const widgetsApi = useWidgetsApi();
	const { isPreview } = useWidgetPreviewContext();
	const { baseUrl } = useDataSourceRegistryConfig();
	return useQuery({
		queryKey: [
			"portal-widget-use",
			"activities",
			isPreview ? "preview" : baseUrl
		],
		queryFn: ({ signal }) => widgetsApi.fetchActivities(signal),
		enabled: !isPreview,
		...isPreview && { placeholderData: PREVIEW_DATA }
	});
}
//#endregion
//#region ../widgets/src/widgets/RecentActivityWidget.tsx
var RecentActivityWidget_exports = /* @__PURE__ */ __exportAll({
	RecentActivityWidget: () => RecentActivityWidget,
	recentActivityWidgetPropertySchema: () => recentActivityWidgetPropertySchema
});
const RELATIVE_TIME_REFRESH_MS = 6e4;
const DEFAULT_MAX_ITEMS_TO_SHOW = 6;
const MAX_ITEMS_TO_SHOW_LIMIT = 20;
const ACTIVITY_ICON_MAP = {
	order_placed: ShoppingCart,
	abandoned_cart: ShoppingCart,
	cart_items_added: ShoppingCart,
	new_cart_items_added: ShoppingCart,
	direct_message: MessageCircle,
	comment_reply: MessageCircle,
	message_received: MessageCircle,
	message_sent: MessageCircle,
	video: Play,
	video_complete: Play,
	video_contact: Play,
	video_complete_contact: Play,
	new_lead: UserPlus,
	page_views_contact: UserPlus,
	smart_link_clicked: UserPlus,
	page_views: Eye,
	upcoming_event: Calendar,
	review_left: Star,
	tasks: CheckSquare,
	announcements: Bell,
	fantasy_point: Trophy
};
const getActivityIcon = (slug) => ACTIVITY_ICON_MAP[slug] ?? User;
const formatAbsoluteTime = (timestamp) => new Date(timestamp).toLocaleTimeString("en-US", {
	hour: "numeric",
	minute: "2-digit",
	hour12: true
});
const formatRelativeTime = (timestamp, now) => {
	const then = new Date(timestamp).getTime();
	const diffSec = Math.max(0, Math.round((now - then) / 1e3));
	if (diffSec < 60) return "now";
	const diffMin = Math.floor(diffSec / 60);
	if (diffMin < 60) return `${diffMin}m`;
	const diffHr = Math.floor(diffMin / 60);
	if (diffHr < 24) return `${diffHr}h`;
	const diffDay = Math.floor(diffHr / 24);
	if (diffDay < 7) return `${diffDay}d`;
	return new Date(timestamp).toLocaleDateString("en-US", {
		month: "short",
		day: "numeric"
	});
};
const toLocalDateKey = (date) => {
	return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`;
};
const formatDateHeader = (timestamp, nowMs) => {
	const date = new Date(timestamp);
	if (!Number.isFinite(date.getTime())) return timestamp;
	const now = new Date(nowMs);
	const yesterday = new Date(now);
	yesterday.setDate(now.getDate() - 1);
	const todayKey = toLocalDateKey(now);
	const yesterdayKey = toLocalDateKey(yesterday);
	const dateKey = toLocalDateKey(date);
	if (dateKey === todayKey) return "Today";
	if (dateKey === yesterdayKey) return "Yesterday";
	return date.toLocaleDateString("en-US", {
		month: "long",
		day: "numeric"
	});
};
const getDateKey = (timestamp) => {
	const date = new Date(timestamp);
	if (!Number.isFinite(date.getTime())) return timestamp;
	return toLocalDateKey(date);
};
const getColorCssValue = (color) => color === "transparent" ? "transparent" : `var(--color-${color})`;
const normalizeMaxItemsToShow = (value) => {
	if (!Number.isFinite(value)) return DEFAULT_MAX_ITEMS_TO_SHOW;
	return Math.min(MAX_ITEMS_TO_SHOW_LIMIT, Math.max(1, Math.floor(value)));
};
const shouldRenderEyebrow = (showEyebrow, titleText) => showEyebrow && titleText.trim().toLowerCase() !== "recent activity";
const isUnknownUser = (name) => {
	if (!name) return true;
	const lower = name.trim().toLowerCase();
	if (!lower) return true;
	return lower === "unknown" || lower.includes("unknown visitor") || lower === "anonymous" || lower === "guest";
};
const getInitials = (name) => {
	if (!name) return "";
	return name.trim().split(/\s+/).slice(0, 2).map((p) => p[0]?.toUpperCase() ?? "").join("");
};
function Avatar({ activity, textColor, accentColor, surfaceColor, showTypeBadge }) {
	const TypeIcon = getActivityIcon(activity.slug);
	const unknown = isUnknownUser(activity.userName);
	const initials = unknown ? "" : getInitials(activity.userName);
	const [failedAvatarUrl, setFailedAvatarUrl] = useState(null);
	const avatarUrl = activity.avatarUrl;
	return /* @__PURE__ */ jsxs("div", {
		className: "relative shrink-0",
		children: [Boolean(avatarUrl) && failedAvatarUrl !== avatarUrl ? /* @__PURE__ */ jsx("img", {
			src: avatarUrl ?? void 0,
			alt: unknown ? "" : activity.userName,
			width: 36,
			height: 36,
			loading: "lazy",
			onError: () => setFailedAvatarUrl(avatarUrl),
			className: "size-9 rounded-full object-cover",
			style: { boxShadow: `inset 0 0 0 1px color-mix(in oklch, var(--color-${textColor}) 10%, transparent)` }
		}) : initials ? /* @__PURE__ */ jsx("div", {
			className: `flex size-9 items-center justify-center rounded-full text-[11px] font-bold tracking-[0.04em] text-${textColor}/80`,
			style: {
				background: `color-mix(in oklch, var(--color-${accentColor}) 12%, transparent)`,
				boxShadow: `inset 0 0 0 1px color-mix(in oklch, var(--color-${textColor}) 10%, transparent)`
			},
			"aria-label": activity.userName,
			children: initials
		}) : /* @__PURE__ */ jsx("div", {
			className: `flex size-9 items-center justify-center rounded-full`,
			style: {
				background: `color-mix(in oklch, var(--color-${textColor}) 5%, transparent)`,
				boxShadow: `inset 0 0 0 1px color-mix(in oklch, var(--color-${textColor}) 10%, transparent)`
			},
			"aria-label": "Unknown visitor",
			children: /* @__PURE__ */ jsx(User, { className: `size-3.5 text-${textColor}/55` })
		}), showTypeBadge && /* @__PURE__ */ jsx("span", {
			className: `bg-${accentColor} text-${accentColor}-foreground absolute -right-0.5 -bottom-0.5 flex size-4 items-center justify-center rounded-full`,
			style: { boxShadow: `0 0 0 2px ${getColorCssValue(surfaceColor)}` },
			"aria-hidden": "true",
			children: /* @__PURE__ */ jsx(TypeIcon, { style: {
				width: 8,
				height: 8
			} })
		})]
	});
}
function ActivityRow({ activity, accentColor, textColor, surfaceColor, showRelativeTime, nowMs }) {
	const timeText = showRelativeTime ? formatRelativeTime(activity.timestamp, nowMs) : formatAbsoluteTime(activity.timestamp);
	const absoluteTooltip = new Date(activity.timestamp).toLocaleString("en-US", {
		weekday: "short",
		month: "short",
		day: "numeric",
		hour: "numeric",
		minute: "2-digit"
	});
	return /* @__PURE__ */ jsxs("li", {
		role: "article",
		className: "relative flex items-start gap-3 rounded-md p-2",
		children: [/* @__PURE__ */ jsx(Avatar, {
			activity,
			textColor,
			accentColor,
			surfaceColor,
			showTypeBadge: true
		}), /* @__PURE__ */ jsxs("div", {
			className: "flex min-w-0 flex-1 flex-col",
			children: [/* @__PURE__ */ jsxs("div", {
				className: "flex items-baseline gap-2",
				children: [/* @__PURE__ */ jsx("p", {
					className: `min-w-0 flex-1 truncate text-[13px] leading-tight font-semibold text-${textColor}`,
					children: activity.activityType
				}), /* @__PURE__ */ jsx("span", {
					title: absoluteTooltip,
					className: `shrink-0 font-mono text-[10px] font-medium tabular-nums text-${textColor}/45`,
					children: timeText
				})]
			}), /* @__PURE__ */ jsxs("p", {
				className: `mt-0.5 truncate text-[12px] leading-snug text-${textColor}/65`,
				children: [/* @__PURE__ */ jsx("span", {
					className: `font-semibold text-${textColor}/85`,
					children: activity.userName
				}), activity.targetName && /* @__PURE__ */ jsxs(Fragment$1, { children: [/* @__PURE__ */ jsx("span", {
					className: `mx-1 text-${textColor}/35`,
					children: "·"
				}), /* @__PURE__ */ jsx("span", { children: activity.targetName })] })]
			})]
		})]
	});
}
function useRelativeTimeNow() {
	const [nowMs, setNowMs] = useState(() => Date.now());
	useEffect(() => {
		const timer = window.setInterval(() => {
			setNowMs(Date.now());
		}, RELATIVE_TIME_REFRESH_MS);
		return () => window.clearInterval(timer);
	}, []);
	return nowMs;
}
function RecentActivityWidget({ titleEnabled = true, titleText = "Activity", titleFontSize = "xl", titleColor = "foreground", background = {
	type: "solid",
	color: "background"
}, textColor = "foreground", accentColor = "primary", padding = 4, borderRadius = "md", borderWidth = "thin", borderColor = "muted", maxItemsToShow = 6, showTimeline = true, showRelativeTime = true, showCountChip = true, showEyebrow = true, className, ...props }) {
	const backgroundColor = background.color || "background";
	const backgroundImage = (background.resource?.image_url || background.resource?.imageUrl) && background.type === "image" ? `url(${background.resource.image_url || background.resource.imageUrl})` : "none";
	const { data: activities = [], isLoading, isError } = useActivities();
	const nowMs = useRelativeTimeNow();
	const maxVisibleItems = normalizeMaxItemsToShow(maxItemsToShow);
	const activitiesToShow = useMemo(() => {
		if (activities.length === 0) return [];
		const groups = /* @__PURE__ */ new Map();
		for (const activity of activities.slice(0, maxVisibleItems)) {
			const key = getDateKey(activity.timestamp);
			const existing = groups.get(key);
			if (existing) existing.push(activity);
			else groups.set(key, [activity]);
		}
		return Array.from(groups.entries()).map(([key, items]) => ({
			date: formatDateHeader(items[0]?.timestamp ?? key, nowMs),
			items
		}));
	}, [
		activities,
		maxVisibleItems,
		nowMs
	]);
	const totalCount = Math.min(activities.length, maxVisibleItems);
	return /* @__PURE__ */ jsx("div", {
		className: `@container overflow-hidden rounded-${borderRadius} bg-${backgroundColor} text-${textColor} ${borderWidthClasses[borderWidth]} ${borderWidth !== "none" ? borderColorClasses[borderColor] : ""} ${className ?? ""}`,
		style: {
			backgroundImage,
			boxShadow: `0 1px 2px color-mix(in oklch, var(--color-foreground) 4%, transparent), 0 14px 32px -20px color-mix(in oklch, var(--color-foreground) 14%, transparent)`
		},
		...props,
		children: /* @__PURE__ */ jsxs("div", {
			className: `p-${padding} flex flex-col`,
			children: [titleEnabled && titleText && /* @__PURE__ */ jsxs("div", {
				className: "mb-4 flex items-end justify-between gap-3",
				children: [/* @__PURE__ */ jsxs("div", {
					className: "flex min-w-0 flex-col",
					children: [shouldRenderEyebrow(showEyebrow, titleText) && /* @__PURE__ */ jsx("span", {
						className: `text-[10px] font-bold tracking-[0.2em] uppercase text-${textColor}/55`,
						children: "Recent"
					}), /* @__PURE__ */ jsx("h2", {
						className: `mt-0.5 text-${titleFontSize} leading-tight font-bold tracking-[-0.015em] text-${titleColor}`,
						children: titleText
					})]
				}), !isLoading && !isError && showCountChip && totalCount > 0 && /* @__PURE__ */ jsxs("span", {
					className: `inline-flex shrink-0 items-center gap-1.5 rounded-full bg-${accentColor}/10 px-2 py-1 text-[10px] font-bold tracking-[0.06em] text-${accentColor}`,
					children: [
						/* @__PURE__ */ jsx("span", {
							"aria-hidden": "true",
							className: `size-1.5 rounded-full bg-${accentColor}`
						}),
						totalCount,
						" ",
						totalCount === 1 ? "update" : "updates"
					]
				})]
			}), isLoading ? /* @__PURE__ */ jsx(ActivitySkeleton, {
				textColor,
				showTimeline,
				rowCount: maxVisibleItems
			}) : isError ? /* @__PURE__ */ jsx(ErrorState, {}) : activities.length === 0 ? /* @__PURE__ */ jsx(EmptyState, {
				textColor,
				accentColor
			}) : /* @__PURE__ */ jsx("div", {
				role: "feed",
				className: "flex flex-col gap-3",
				children: activitiesToShow.map((group, groupIdx) => /* @__PURE__ */ jsxs("section", {
					className: "flex flex-col gap-1",
					children: [/* @__PURE__ */ jsxs("header", {
						className: "flex items-center gap-2 px-2",
						children: [/* @__PURE__ */ jsx("span", {
							className: `text-[10px] font-bold tracking-[0.18em] uppercase text-${textColor}/55`,
							children: group.date
						}), /* @__PURE__ */ jsx("span", {
							"aria-hidden": "true",
							className: "h-px flex-1",
							style: { background: `color-mix(in oklch, var(--color-${textColor}) 8%, transparent)` }
						})]
					}), /* @__PURE__ */ jsxs("ul", {
						className: "relative flex flex-col",
						children: [showTimeline && group.items.length > 1 && /* @__PURE__ */ jsx("span", {
							"aria-hidden": "true",
							className: "pointer-events-none absolute top-[26px] bottom-[26px] left-[26px] w-px",
							style: { background: `color-mix(in oklch, var(--color-${textColor}) 10%, transparent)` }
						}), group.items.map((activity) => /* @__PURE__ */ jsx(ActivityRow, {
							activity,
							accentColor,
							textColor,
							surfaceColor: backgroundColor,
							showRelativeTime,
							nowMs
						}, activity.id))]
					})]
				}, `${group.date}-${groupIdx}`))
			})]
		})
	});
}
function EmptyState({ textColor, accentColor }) {
	return /* @__PURE__ */ jsxs("div", {
		className: "flex flex-col items-center justify-center gap-3 px-4 py-10",
		children: [/* @__PURE__ */ jsx("div", {
			className: "relative flex size-12 items-center justify-center rounded-full",
			style: {
				background: `color-mix(in oklch, var(--color-${accentColor}) 10%, transparent)`,
				boxShadow: `inset 0 0 0 1px color-mix(in oklch, var(--color-${textColor}) 8%, transparent)`
			},
			children: /* @__PURE__ */ jsx(AudioWaveform, { className: `size-5 text-${accentColor}/80` })
		}), /* @__PURE__ */ jsxs("div", {
			className: "flex flex-col items-center gap-1",
			children: [/* @__PURE__ */ jsx("p", {
				className: `text-[13px] font-semibold text-${textColor}/80`,
				children: "No activity yet"
			}), /* @__PURE__ */ jsx("p", {
				className: `max-w-[24ch] text-center text-[11px] leading-snug text-${textColor}/55`,
				children: "Orders, messages, views and leads will show up here as they happen."
			})]
		})]
	});
}
function ActivitySkeleton({ textColor, showTimeline, rowCount }) {
	return /* @__PURE__ */ jsxs("div", {
		className: "relative flex flex-col",
		"aria-busy": "true",
		children: [showTimeline && /* @__PURE__ */ jsx("span", {
			"aria-hidden": "true",
			className: "pointer-events-none absolute top-[26px] bottom-[26px] left-[26px] w-px",
			style: { background: `color-mix(in oklch, var(--color-${textColor}) 10%, transparent)` }
		}), Array.from({ length: rowCount }, (_, i) => i).map((i) => /* @__PURE__ */ jsxs("div", {
			className: "relative flex items-start gap-3 rounded-md p-2",
			children: [/* @__PURE__ */ jsx("div", { className: `size-9 shrink-0 animate-pulse rounded-full bg-${textColor}/10` }), /* @__PURE__ */ jsxs("div", {
				className: "flex min-w-0 flex-1 flex-col gap-1.5",
				children: [/* @__PURE__ */ jsx("div", { className: `h-2 w-2/3 animate-pulse rounded-full bg-${textColor}/10` }), /* @__PURE__ */ jsx("div", { className: `h-2 w-1/2 animate-pulse rounded-full bg-${textColor}/10` })]
			})]
		}, i))]
	});
}
const recentActivityWidgetPropertySchema = {
	widgetType: "RecentActivityWidget",
	displayName: "Recent Activity Widget",
	tabsConfig: [{
		id: "styling",
		label: "Styling"
	}],
	fields: [
		{
			key: "titleEnabled",
			label: "Widget Title",
			type: "boolean",
			description: "Display the title and eyebrow above the feed",
			defaultValue: true,
			tab: "styling",
			group: "Title"
		},
		{
			key: "titleText",
			label: "Title",
			type: "text",
			description: "Title text displayed above the activity feed",
			defaultValue: "Activity",
			tab: "styling",
			group: "Title",
			requiresKeyToBeTrue: "titleEnabled"
		},
		getFontSizeField({
			key: "titleFontSize",
			label: "Title Font Size",
			description: "Font size for the widget title",
			defaultValue: "xl",
			tab: "styling",
			group: "Title",
			requiresKeyToBeTrue: "titleEnabled"
		}),
		getColorField({
			key: "titleColor",
			label: "Title Color",
			description: "Color for the widget title",
			defaultValue: "foreground",
			tab: "styling",
			group: "Title",
			requiresKeyToBeTrue: "titleEnabled"
		}),
		{
			key: "showEyebrow",
			label: "Show 'RECENT' Eyebrow",
			type: "boolean",
			description: "Small uppercase label above the title",
			defaultValue: true,
			tab: "styling",
			group: "Title",
			requiresKeyToBeTrue: "titleEnabled"
		},
		{
			key: "showCountChip",
			label: "Show Updates Count Chip",
			type: "boolean",
			description: "Accent pill next to the title showing how many updates",
			defaultValue: true,
			tab: "styling",
			group: "Title",
			requiresKeyToBeTrue: "titleEnabled"
		},
		{
			key: "maxItemsToShow",
			label: "Max Items",
			type: "number",
			description: "Maximum number of activity items to display",
			defaultValue: DEFAULT_MAX_ITEMS_TO_SHOW,
			min: 1,
			max: MAX_ITEMS_TO_SHOW_LIMIT,
			step: 1,
			tab: "styling",
			group: "Feed"
		},
		{
			key: "showTimeline",
			label: "Timeline Spine",
			type: "boolean",
			description: "Draw a vertical line connecting activity avatars",
			defaultValue: true,
			tab: "styling",
			group: "Feed"
		},
		{
			key: "showRelativeTime",
			label: "Relative Timestamps",
			type: "boolean",
			description: "Show 'now / 2m / 1h / 3d' instead of absolute times",
			defaultValue: true,
			tab: "styling",
			group: "Feed"
		},
		{
			type: "background",
			key: "background",
			label: "Background",
			description: "Background for the widget container",
			defaultValue: "background",
			tab: "styling",
			group: "Design"
		},
		getColorField({
			key: "textColor",
			label: "Text Color",
			description: "Default text color for activity content",
			defaultValue: "foreground",
			tab: "styling",
			group: "Design"
		}),
		getColorField({
			key: "accentColor",
			label: "Accent Color",
			description: "Drives the count chip, type badge, initials avatar, and empty-state icon",
			defaultValue: "primary",
			tab: "styling",
			group: "Design"
		}),
		{
			key: "separator",
			type: "separator",
			label: "Separator",
			tab: "styling",
			group: "Design"
		},
		getPaddingField({
			key: "padding",
			label: "Padding",
			description: "Padding around the widget container",
			defaultValue: 4,
			tab: "styling",
			group: "Design"
		}),
		getBorderRadiusField({
			key: "borderRadius",
			label: "Border Radius",
			description: "Border radius for the widget container",
			defaultValue: "md",
			tab: "styling",
			group: "Design"
		}),
		getBorderWidthField({
			key: "borderWidth",
			label: "Border Width",
			description: "Border width for the widget container",
			defaultValue: "thin",
			tab: "styling",
			group: "Design"
		}),
		getBorderColorField({
			key: "borderColor",
			label: "Border Color",
			description: "Border color for the widget container",
			defaultValue: "muted",
			tab: "styling",
			group: "Design"
		})
	]
};
//#endregion
export { RecentActivityWidget_exports as n, recentActivityWidgetPropertySchema as r, RecentActivityWidget as t };

//# sourceMappingURL=RecentActivityWidget-W5VOvYig.mjs.map