import { An as cn, C as Skeleton, d as Table, f as TableBody, g as TableRow, h as TableHeader, m as TableHead, p as TableCell, y as Spinner } from "./src-B3W228vu.mjs";
import { t as SearchSort } from "./SearchSort-WObTUK9E.mjs";
import { createContext, useCallback, useContext, useEffect, useRef, useState } from "react";
import { useInfiniteQuery, useQuery } from "@tanstack/react-query";
import { jsx, jsxs } from "react/jsx-runtime";
//#region ../../orders/core/src/orders-api-context.ts
const OrdersApiContext = createContext(null);
const OrdersApiProvider = OrdersApiContext.Provider;
function useOrdersApi() {
	const api = useContext(OrdersApiContext);
	if (!api) throw new Error("useOrdersApi must be used within an OrdersCoreProvider");
	return api;
}
//#endregion
//#region ../../orders/core/src/provider.tsx
function OrdersCoreProvider({ api, children }) {
	return /* @__PURE__ */ jsx(OrdersApiProvider, {
		value: api,
		children
	});
}
//#endregion
//#region ../../orders/core/src/query-keys.ts
const ordersKeys = {
	all: ["orders"],
	list: (params) => [
		...ordersKeys.all,
		"list",
		params
	],
	detail: (orderToken) => [
		...ordersKeys.all,
		"detail",
		orderToken
	]
};
const portalTenantOrdersKeys = {
	all: ["portalTenantOrders"],
	list: (params) => [
		...portalTenantOrdersKeys.all,
		"list",
		params
	],
	detail: (id) => [
		...portalTenantOrdersKeys.all,
		"detail",
		id
	]
};
//#endregion
//#region ../../orders/core/src/hooks/use-infinite-customer-orders.ts
function useInfiniteCustomerOrders(params, options) {
	const api = useOrdersApi();
	return useInfiniteQuery({
		queryKey: [
			...ordersKeys.all,
			"infinite-list",
			params
		],
		queryFn: ({ pageParam }) => {
			if (!api.fetchCustomerOrders) throw new Error("fetchCustomerOrders not implemented on this OrdersApi");
			return api.fetchCustomerOrders({
				...params,
				cursor: pageParam
			});
		},
		getNextPageParam: (lastPage) => lastPage.meta?.pagination?.next_cursor ?? void 0,
		initialPageParam: void 0,
		enabled: options?.enabled ?? true
	});
}
//#endregion
//#region ../../orders/core/src/hooks/use-portal-tenant-order.ts
function usePortalTenantOrder(id, options) {
	const api = useOrdersApi();
	return useQuery({
		queryKey: portalTenantOrdersKeys.detail(id),
		queryFn: () => {
			if (!api.fetchOrderById) throw new Error("fetchOrderById not implemented on this OrdersApi");
			return api.fetchOrderById(id);
		},
		enabled: (options?.enabled ?? true) && !!id
	});
}
//#endregion
//#region ../../orders/core/src/utils/format-order-total.ts
function formatOrderTotal(order) {
	if (order.order_total_after_points_redemption != null) return `${order.currency_symbol || "$"}${Number(order.order_total_after_points_redemption).toFixed(2)}`;
	return order.total_display_amount || `${order.currency_symbol || "$"}${Number(order.amount).toFixed(2)}`;
}
//#endregion
//#region ../../platform/ui-components/src/components/InfiniteScrollSentinel.tsx
function InfiniteScrollSentinel({ onLoadMore, hasMore, isLoading, rootMargin = "200px" }) {
	const sentinelRef = useRef(null);
	useEffect(() => {
		const sentinel = sentinelRef.current;
		if (!sentinel || !hasMore || isLoading) return;
		const observer = new IntersectionObserver((entries) => {
			if (entries[0]?.isIntersecting) onLoadMore();
		}, { rootMargin });
		observer.observe(sentinel);
		return () => observer.disconnect();
	}, [
		onLoadMore,
		hasMore,
		isLoading,
		rootMargin
	]);
	if (!hasMore && !isLoading) return null;
	return /* @__PURE__ */ jsx("div", {
		className: "flex justify-center py-3",
		children: isLoading ? /* @__PURE__ */ jsx(Spinner, {}) : /* @__PURE__ */ jsx("div", { ref: sentinelRef })
	});
}
//#endregion
//#region ../../orders/ui/src/components/status-badge.tsx
const colorStyles = {
	green: "bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400",
	yellow: "bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-400",
	red: "bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-400",
	blue: "bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-400",
	gray: "bg-gray-100 text-gray-800 dark:bg-gray-800 dark:text-gray-300"
};
const dotColorStyles = {
	green: "bg-green-500",
	yellow: "bg-yellow-500",
	red: "bg-red-500",
	blue: "bg-blue-500",
	gray: "bg-gray-500"
};
const sizeStyles = {
	xs: "px-1.5 py-0.5 text-[10px]",
	sm: "px-2 py-0.5 text-xs",
	md: "px-2.5 py-1 text-sm"
};
function StatusBadge({ color, dot, size = "md", className, children }) {
	return /* @__PURE__ */ jsxs("span", {
		className: cn("inline-flex items-center gap-1 rounded-full font-medium whitespace-nowrap capitalize", colorStyles[color], sizeStyles[size], className),
		children: [dot && /* @__PURE__ */ jsx("span", { className: cn("h-1.5 w-1.5 rounded-full", dotColorStyles[color]) }), children]
	});
}
//#endregion
//#region ../../orders/ui/src/components/table-column.tsx
function TableColumn({ label, sortable = true, className, onSortClick, sortBy, sortData, chevronUpIcon, chevronDownIcon }) {
	const hideUpIcon = sortData?.column !== sortBy || sortData?.column === sortBy && sortData?.direction === "asc";
	const hideDownIcon = sortData?.column !== sortBy || sortData?.column === sortBy && sortData?.direction === "desc";
	return /* @__PURE__ */ jsx(TableHead, {
		className: cn("group text-muted-foreground cursor-pointer px-3 text-xs transition-colors duration-200", "hover:text-primary", className),
		onClick: () => sortable && onSortClick?.(sortBy ?? ""),
		children: /* @__PURE__ */ jsxs("div", {
			className: "relative flex items-center",
			children: [label, sortable && chevronUpIcon && chevronDownIcon && /* @__PURE__ */ jsx("button", {
				className: `ml-2 inline-flex flex-col items-center justify-center group-hover:opacity-100 ${sortData?.column === sortBy ? "opacity-100" : "opacity-0"} transition-opacity duration-200`,
				children: /* @__PURE__ */ jsxs("div", {
					className: "flex flex-col",
					children: [/* @__PURE__ */ jsx("img", {
						src: chevronUpIcon,
						alt: "",
						width: 12,
						height: 12,
						className: cn("text-muted-foreground group-hover:text-primary h-2.5 w-2.5 transition-colors duration-200", hideUpIcon && "opacity-0", sortData?.column !== sortBy && "group-hover:opacity-100")
					}), /* @__PURE__ */ jsx("img", {
						src: chevronDownIcon,
						alt: "",
						width: 12,
						height: 12,
						className: cn("text-muted-foreground group-hover:text-primary h-2.5 w-2.5 transition-colors duration-200", hideDownIcon && "opacity-0", sortData?.column !== sortBy && "group-hover:opacity-100")
					})]
				})
			})]
		})
	});
}
//#endregion
//#region ../../orders/ui/src/components/orders-list.tsx
function OrdersList({ customerId, onOrderClick, onSubscriptionClick, t, pageSize = 10 }) {
	const [searchTerm, setSearchTerm] = useState("");
	const { data, isLoading, fetchNextPage, hasNextPage, isFetchingNextPage } = useInfiniteCustomerOrders({
		customerId,
		limit: pageSize,
		search: searchTerm || void 0,
		sort: "-created_at"
	}, { enabled: !!customerId });
	const handleSearchChange = useCallback((term) => {
		setSearchTerm(term);
	}, []);
	const ordersList = data?.pages.flatMap((p) => p.orders) ?? [];
	return /* @__PURE__ */ jsxs("div", {
		className: "border-border overflow-hidden rounded-lg border shadow-sm",
		children: [
			/* @__PURE__ */ jsx("div", {
				className: "flex justify-end p-3",
				children: /* @__PURE__ */ jsx("div", {
					className: "w-full max-w-sm",
					children: /* @__PURE__ */ jsx(SearchSort, {
						searchValue: searchTerm,
						onSearchChange: handleSearchChange,
						placeholder: t("search_orders")
					})
				})
			}),
			/* @__PURE__ */ jsx("div", {
				className: "block md:hidden",
				children: isLoading ? Array(5).fill(0).map((_, index) => /* @__PURE__ */ jsx("div", {
					className: "border-border border-b p-4",
					children: /* @__PURE__ */ jsxs("div", {
						className: "flex space-x-3",
						children: [/* @__PURE__ */ jsx(Skeleton, { className: "h-12 w-12 rounded-md" }), /* @__PURE__ */ jsxs("div", {
							className: "flex-1 space-y-2",
							children: [/* @__PURE__ */ jsx(Skeleton, { className: "h-4 w-3/4" }), /* @__PURE__ */ jsx(Skeleton, { className: "h-3 w-1/2" })]
						})]
					})
				}, `skeleton-${index}`)) : ordersList.length === 0 ? /* @__PURE__ */ jsx("div", {
					className: "text-muted-foreground px-3 py-8 text-center text-sm",
					children: searchTerm ? t("no_matching_orders") : t("no_orders_found")
				}) : ordersList.map((order) => /* @__PURE__ */ jsx("div", {
					className: "border-border hover:bg-accent cursor-pointer border-b p-4 transition-colors duration-200 ease-in-out last:border-b-0",
					onClick: () => onOrderClick(order),
					children: /* @__PURE__ */ jsxs("div", {
						className: "flex items-start space-x-3",
						children: [order.first_item?.image_url ? /* @__PURE__ */ jsx("img", {
							src: order.first_item.image_url,
							alt: t("no_image_available"),
							width: 48,
							height: 48,
							className: "h-12 w-12 flex-shrink-0 rounded-md object-cover"
						}) : /* @__PURE__ */ jsx("div", { className: "bg-border h-12 w-12 flex-shrink-0 rounded-md" }), /* @__PURE__ */ jsxs("div", {
							className: "w-0 min-w-0 flex-1",
							children: [
								order.first_item?.title ? /* @__PURE__ */ jsx("p", {
									className: "text-foreground truncate text-sm font-medium",
									children: order.first_item.title
								}) : /* @__PURE__ */ jsx("div", {
									className: "bg-muted rounded-lg p-2",
									children: /* @__PURE__ */ jsx("div", {
										className: "text-muted-foreground text-xs",
										children: t("this_product_no_longer_exists")
									})
								}),
								order.subscription && /* @__PURE__ */ jsx(StatusBadge, {
									color: "blue",
									size: "xs",
									className: "mt-1",
									children: t("subscription")
								}),
								order.subscription?.subscription_token && onSubscriptionClick && /* @__PURE__ */ jsx("button", {
									type: "button",
									className: "text-foreground hover:text-foreground/80 mt-1 inline-block text-xs transition-colors duration-200 hover:underline",
									onClick: (e) => {
										e.stopPropagation();
										onSubscriptionClick(order.subscription.subscription_token);
									},
									children: t("view_subscription")
								}),
								/* @__PURE__ */ jsxs("div", {
									className: "mt-2 grid grid-cols-3 gap-x-4 gap-y-1 text-sm",
									children: [
										/* @__PURE__ */ jsxs("div", { children: [/* @__PURE__ */ jsx("span", {
											className: "text-muted-foreground block text-xs",
											children: t("date")
										}), /* @__PURE__ */ jsx("span", {
											className: "text-muted-foreground",
											children: new Date(order.created_at).toLocaleDateString()
										})] }),
										/* @__PURE__ */ jsxs("div", { children: [/* @__PURE__ */ jsx("span", {
											className: "text-muted-foreground block text-xs",
											children: t("status")
										}), /* @__PURE__ */ jsx(StatusBadge, {
											color: order.order_status === "completed" || order.order_status === "delivered" || order.order_status === "shipped" ? "green" : order.order_status === "cancelled" || order.order_status === "returned" ? "red" : "yellow",
											size: "xs",
											children: order.order_status
										})] }),
										/* @__PURE__ */ jsxs("div", { children: [/* @__PURE__ */ jsx("span", {
											className: "text-muted-foreground block text-xs",
											children: t("total")
										}), /* @__PURE__ */ jsx("span", {
											className: "text-foreground font-medium",
											children: formatOrderTotal(order)
										})] })
									]
								})
							]
						})]
					})
				}, order.id))
			}),
			/* @__PURE__ */ jsx("div", {
				className: "hidden md:block",
				children: /* @__PURE__ */ jsxs(Table, {
					className: "min-w-full table-fixed",
					children: [
						/* @__PURE__ */ jsxs("colgroup", { children: [
							/* @__PURE__ */ jsx("col", { className: "w-2/5 min-w-[240px]" }),
							/* @__PURE__ */ jsx("col", { className: "w-[20%] min-w-[100px]" }),
							/* @__PURE__ */ jsx("col", { className: "w-[20%] min-w-[100px]" }),
							/* @__PURE__ */ jsx("col", { className: "w-[20%] min-w-[100px]" })
						] }),
						/* @__PURE__ */ jsx(TableHeader, {
							className: "bg-muted",
							children: /* @__PURE__ */ jsxs(TableRow, {
								className: "hover:bg-muted h-10",
								children: [
									/* @__PURE__ */ jsx(TableColumn, {
										label: t("product"),
										sortable: false
									}),
									/* @__PURE__ */ jsx(TableColumn, {
										label: t("date"),
										sortable: false
									}),
									/* @__PURE__ */ jsx(TableColumn, {
										label: t("status"),
										sortable: false
									}),
									/* @__PURE__ */ jsx(TableColumn, {
										label: t("total"),
										sortable: false
									})
								]
							})
						}),
						/* @__PURE__ */ jsx(TableBody, {
							className: "bg-background",
							children: isLoading ? Array(5).fill(0).map((_, index) => /* @__PURE__ */ jsxs(TableRow, { children: [
								/* @__PURE__ */ jsx(TableCell, {
									className: "px-3 py-4",
									children: /* @__PURE__ */ jsxs("div", {
										className: "flex items-center space-x-2",
										children: [/* @__PURE__ */ jsx(Skeleton, { className: "h-9 w-9 rounded-md" }), /* @__PURE__ */ jsx(Skeleton, { className: "h-4 w-32" })]
									})
								}),
								/* @__PURE__ */ jsx(TableCell, {
									className: "px-3 py-4",
									children: /* @__PURE__ */ jsx(Skeleton, { className: "h-4 w-24" })
								}),
								/* @__PURE__ */ jsx(TableCell, {
									className: "px-3 py-4",
									children: /* @__PURE__ */ jsx(Skeleton, { className: "h-4 w-20" })
								}),
								/* @__PURE__ */ jsx(TableCell, {
									className: "px-3 py-4",
									children: /* @__PURE__ */ jsx(Skeleton, { className: "h-4 w-24" })
								})
							] }, `skeleton-${index}`)) : ordersList.length === 0 ? /* @__PURE__ */ jsx(TableRow, { children: /* @__PURE__ */ jsx(TableCell, {
								colSpan: 4,
								className: "text-muted-foreground px-3 py-8 text-center text-sm",
								children: searchTerm ? t("no_matching_orders") : t("no_orders_found")
							}) }) : ordersList.map((order) => /* @__PURE__ */ jsxs(TableRow, {
								className: "cursor-pointer",
								onClick: () => onOrderClick(order),
								children: [
									/* @__PURE__ */ jsx(TableCell, {
										className: "text-muted-foreground px-3 py-4 text-sm",
										children: /* @__PURE__ */ jsxs("div", {
											className: "flex max-w-[280px] flex-row items-center space-x-3",
											children: [order.first_item?.image_url ? /* @__PURE__ */ jsx("img", {
												src: order.first_item.image_url,
												alt: t("no_image_available"),
												width: 42,
												height: 42,
												className: "h-[42px] w-[42px] flex-shrink-0 rounded-md object-cover"
											}) : /* @__PURE__ */ jsx("div", { className: "bg-border ml-1 h-9 w-9 flex-shrink-0 rounded-md" }), /* @__PURE__ */ jsxs("div", {
												className: "flex min-w-0 flex-col space-y-1",
												children: [/* @__PURE__ */ jsxs("div", {
													className: "flex items-center space-x-2",
													children: [order.first_item?.title ? /* @__PURE__ */ jsx("span", {
														className: "text-foreground truncate text-sm font-medium",
														children: order.first_item.title
													}) : /* @__PURE__ */ jsx("div", {
														className: "bg-muted w-full rounded-lg p-2",
														children: /* @__PURE__ */ jsx("div", {
															className: "text-muted-foreground text-xs",
															children: t("this_product_no_longer_exists")
														})
													}), order.subscription && /* @__PURE__ */ jsx(StatusBadge, {
														color: "blue",
														size: "xs",
														className: "flex-shrink-0",
														children: t("subscription")
													})]
												}), order.subscription?.subscription_token && onSubscriptionClick && /* @__PURE__ */ jsx("button", {
													type: "button",
													className: "text-foreground hover:text-foreground/80 text-left text-xs transition-colors duration-200 hover:underline",
													onClick: (e) => {
														e.stopPropagation();
														onSubscriptionClick(order.subscription.subscription_token);
													},
													children: t("view_subscription")
												})]
											})]
										})
									}),
									/* @__PURE__ */ jsx(TableCell, {
										className: "text-muted-foreground px-3 py-4 text-sm whitespace-nowrap",
										children: new Date(order.created_at).toLocaleDateString()
									}),
									/* @__PURE__ */ jsx(TableCell, {
										className: "px-3 py-4 text-sm",
										children: /* @__PURE__ */ jsx(StatusBadge, {
											color: order.order_status === "completed" || order.order_status === "delivered" || order.order_status === "shipped" ? "green" : order.order_status === "cancelled" || order.order_status === "returned" ? "red" : "yellow",
											size: "xs",
											children: order.order_status
										})
									}),
									/* @__PURE__ */ jsx(TableCell, {
										className: "text-foreground px-3 py-4 text-sm whitespace-nowrap",
										children: formatOrderTotal(order)
									})
								]
							}, order.id))
						})
					]
				})
			}),
			/* @__PURE__ */ jsx(InfiniteScrollSentinel, {
				onLoadMore: fetchNextPage,
				hasMore: !!hasNextPage,
				isLoading: isFetchingNextPage
			})
		]
	});
}
//#endregion
//#region ../../orders/ui/src/lib/format.ts
function startCase(str) {
	if (!str) return "";
	return str.replace(/_/g, " ").replace(/\b\w/g, (char) => char.toUpperCase());
}
//#endregion
//#region ../../orders/ui/src/components/order-status-badge.tsx
const statusColorMap = {
	paid: "green",
	fulfilled: "green",
	delivered: "green",
	complete: "green",
	pending: "yellow",
	unfulfilled: "yellow",
	partially_fulfilled: "yellow",
	processing: "yellow",
	refunded: "red",
	cancelled: "red",
	failed: "red",
	voided: "red"
};
function OrderStatusBadge({ status, className }) {
	return /* @__PURE__ */ jsx(StatusBadge, {
		color: statusColorMap[status] ?? "gray",
		dot: true,
		size: "sm",
		className,
		children: startCase(status)
	});
}
//#endregion
export { usePortalTenantOrder as a, InfiniteScrollSentinel as i, OrdersList as n, OrdersCoreProvider as o, TableColumn as r, OrderStatusBadge as t };

//# sourceMappingURL=order-status-badge-CCd3NE1e.mjs.map