import { n as useFluidContext } from "./FluidProvider-CqFxMwqz.mjs";
import { d as orders_list, f as orders_show } from "./portal_tenant-l4a-eX2B.mjs";
import { n as usePortalTenantClient } from "./PortalTenantClientProvider-BF-1Fy27.mjs";
import { i as createTranslationContext, n as createDomainTranslations, o as useActiveLocale, r as useDomainDict, t as createStaticDictAdapter } from "./static-dict-adapter-OprHuHgs.mjs";
import { Cn as cn, an as BreadcrumbLink, cn as BreadcrumbSeparator, f as fluidToast, h as Skeleton, in as BreadcrumbItem, k as Input, on as BreadcrumbList, rn as Breadcrumb, sn as BreadcrumbPage } from "./src-Dk1FJOX0.mjs";
import { n as ScreenHeaderBreadcrumbs } from "./ScreenHeaderContext-Dn12BZyj.mjs";
import { n as useAppNavigation } from "./AppNavigationContext-DNomMUij.mjs";
import { createContext, useContext, useEffect, useMemo, useState } from "react";
import { useInfiniteQuery, useQuery } from "@tanstack/react-query";
import { Fragment as Fragment$1, jsx, jsxs } from "react/jsx-runtime";
import { AlertCircle, ImageOff, Repeat, Search } from "lucide-react";
//#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 ../../orders/core/src/utils/build-static-map-url.ts
function buildStaticMapUrl(apiKey, address, options) {
	if (!address.address1 || !address.city || !address.state || !address.postal_code) return null;
	const formatted = `${address.address1}, ${address.city}, ${address.state} ${address.postal_code.slice(0, 5)}`;
	const encoded = encodeURIComponent(formatted);
	const width = options?.width ?? 600;
	const height = options?.height ?? 300;
	return `https://maps.googleapis.com/maps/api/staticmap?center=${encoded}&zoom=${options?.zoom ?? 15}&size=${width}x${height}&maptype=roadmap&markers=color:${encodeURIComponent(options?.markerColor ?? "red")}%7C${encoded}&key=${apiKey}`;
}
//#endregion
//#region src/adapters/orders-api-adapter.ts
/**
* Requires a BFF money field to be present. The BFF contract guarantees
* subtotal/discount/shipping/tax on every Order, so a missing value signals
* a broken contract. Mirrors the fail-loud pattern in subscriptions-api-adapter
* (see the `BFF returned a successful response but subscription data was
* missing` throw) and avoids silently rendering $0.00 in the UI, which a
* customer cannot distinguish from a legitimately free line.
*/
function requireMoneyField(value, field) {
	if (value == null) throw new Error(`BFF returned an order without required money field "${field}"`);
	return value;
}
function mapAddress(raw) {
	if (!raw) return null;
	return {
		id: raw.id ?? 0,
		name: raw.name ?? null,
		address1: raw.address1 ?? null,
		address2: raw.address2 ?? null,
		city: raw.city ?? null,
		state: raw.state ?? null,
		postal_code: raw.postal_code ?? null,
		country_code: raw.country_code ?? null
	};
}
function mapPaymentMethod(raw) {
	if (!raw) return null;
	return {
		id: raw.id ?? 0,
		source: raw.source ?? "",
		payment_type: raw.payment_type ?? "",
		card_type: raw.card_type ?? null,
		last4: raw.last4 ?? null
	};
}
function mapToPortalTenantOrder(raw) {
	const subtotal = requireMoneyField(raw.subtotal, "subtotal");
	const discount = requireMoneyField(raw.discount, "discount");
	const shipping = requireMoneyField(raw.shipping, "shipping");
	const tax = requireMoneyField(raw.tax, "tax");
	const total = requireMoneyField(raw.total, "total");
	return {
		id: raw.id ?? 0,
		token: raw.token ?? "",
		status: raw.status ?? "pending",
		subtotal,
		subtotal_in_currency: raw.subtotal_in_currency ?? subtotal,
		discount,
		discount_in_currency: raw.discount_in_currency ?? discount,
		shipping,
		shipping_in_currency: raw.shipping_in_currency ?? shipping,
		tax,
		tax_in_currency: raw.tax_in_currency ?? tax,
		total,
		total_in_currency: raw.total_in_currency ?? total,
		currency: raw.currency ?? "",
		line_items: (raw.line_items ?? []).map((li) => {
			const liPrice = li.price ?? "0";
			const liTotal = li.total ?? "0";
			return {
				id: li.id ?? 0,
				product_id: li.product_id ?? 0,
				product_name: li.product_name ?? "",
				variant_id: li.variant_id ?? null,
				variant_name: li.variant_name ?? null,
				sku: li.sku ?? null,
				image_url: li.image_url ?? null,
				quantity: li.quantity ?? 0,
				price: liPrice,
				price_in_currency: li.price_in_currency ?? liPrice,
				total: liTotal,
				total_in_currency: li.total_in_currency ?? liTotal,
				source_subscription: li.source_subscription?.subscription_token ? { subscription_token: li.source_subscription.subscription_token } : null
			};
		}),
		customer_name: raw.customer_name ?? null,
		customer_email: raw.customer_email ?? null,
		address: mapAddress(raw.address),
		payment_method: mapPaymentMethod(raw.payment_method),
		subscription_order: raw.subscription_order ?? false,
		subscription_token: raw.subscription_token ?? null,
		total_points_credited: typeof raw.total_points_credited === "number" ? raw.total_points_credited : void 0,
		customer_points_balance: typeof raw.customer_points_balance === "number" ? raw.customer_points_balance : void 0,
		created_at: raw.created_at ?? "",
		updated_at: raw.updated_at ?? ""
	};
}
function mapToListOrder(raw) {
	const firstLineItem = raw.line_items?.[0];
	return {
		id: raw.id ?? 0,
		external_id: null,
		order_number: "",
		email: raw.customer_email ?? null,
		first_name: raw.customer_name?.split(" ")[0] ?? null,
		last_name: raw.customer_name?.split(" ").slice(1).join(" ") || null,
		amount: raw.total ?? "0",
		status: raw.status ?? "pending",
		order_status: raw.status ?? "pending",
		fulfillment_status: "unfulfilled",
		financial_status: "pending",
		currency_code: raw.currency ?? "",
		note: null,
		token: raw.token ?? "",
		warehouse_id: null,
		source: "web",
		created_at: raw.created_at ?? "",
		updated_at: raw.updated_at ?? "",
		total_display_amount: raw.total_in_currency ?? raw.total ?? "0",
		total_cv: 0,
		total_qv: 0,
		currency_symbol: "",
		items_count: raw.line_items?.length ?? 0,
		quantity_count: raw.line_items?.reduce((sum, li) => sum + (li.quantity ?? 0), 0) ?? 0,
		order_on_behalf_of: false,
		sale_date: null,
		customer: null,
		first_item: firstLineItem ? {
			title: firstLineItem.product_name ?? "",
			image_url: firstLineItem.image_url ?? ""
		} : null,
		thumbnail_image_urls: raw.line_items?.map((li) => li.image_url).filter((u) => typeof u === "string" && u.length > 0).slice(0, 3) ?? [],
		subscription: raw.subscription_order && raw.subscription_token ? {
			subscription_token: raw.subscription_token,
			status: "active"
		} : raw.subscription_order ? {
			subscription_token: "",
			status: "active"
		} : null
	};
}
function createPortalOrdersAdapter(client) {
	return {
		fetchOrderById: async (id) => {
			const response = await orders_show(client, id);
			return {
				order: mapToPortalTenantOrder(response.order ?? {}),
				meta: {
					request_id: response.meta?.request_id ?? "",
					timestamp: response.meta?.timestamp ?? ""
				}
			};
		},
		fetchCustomerOrders: async (params) => {
			const response = await orders_list(client, {
				"page[cursor]": params.cursor,
				"page[limit]": params.limit,
				status: params.status,
				q: params.search
			});
			return {
				orders: (response.orders ?? []).map(mapToListOrder),
				meta: {
					request_id: response.meta?.request_id ?? "",
					timestamp: response.meta?.timestamp ?? "",
					pagination: {
						cursor: response.meta?.pagination?.cursor ?? null,
						limit: response.meta?.pagination?.limit ?? 25,
						next_cursor: response.meta?.pagination?.next_cursor ?? null,
						prev_cursor: response.meta?.pagination?.prev_cursor ?? null
					}
				}
			};
		}
	};
}
//#endregion
//#region src/orders/PortalOrdersApiProvider.tsx
function PortalOrdersApiProvider({ children }) {
	const client = usePortalTenantClient();
	return /* @__PURE__ */ jsx(OrdersCoreProvider, {
		api: useMemo(() => createPortalOrdersAdapter(client), [client]),
		children
	});
}
//#endregion
//#region ../../orders/core/src/translation-adapter.ts
const ordersDomain = createDomainTranslations({
	fallback: {
		breadcrumb: "Orders",
		breadcrumb_detail: "Order #{{id}}",
		search_orders: "Search orders...",
		order_number: "Order #",
		date: "Date",
		status: "Status",
		product: "Product",
		total: "Total",
		no_orders_found: "No orders found",
		no_matching_orders: "No matching orders",
		no_image_available: "No image available",
		no_image: "No image",
		this_product_no_longer_exists: "This product no longer exists",
		subscription: "Subscription",
		subscription_hash: "Subscription #{{token}}",
		view_subscription: "View Subscription",
		results: "results",
		previous: "Previous",
		next: "Next",
		pagination: "Pagination",
		showing: "Showing",
		to: "to",
		of: "of",
		order_not_found: "Order not found",
		error_generic: "An error occurred",
		error_loading_order: "Failed to load order: {{message}}",
		items_count: "Items ({{count}})",
		subtotal: "Subtotal",
		discount: "Discount",
		shipping: "Shipping",
		shipping_free: "Free",
		tax: "Tax",
		tax_included: "{{name}}, included",
		points_applied: "Points Applied",
		points_applied_singular: "pt",
		points_applied_plural: "pts",
		points_earned: "Points Earned on This Order!",
		points_total: "{{count}} points total",
		points: "points",
		status_label: "Status:",
		payment_label: "Payment:",
		fulfillment_label: "Fulfillment:",
		delivery_label: "Delivery:",
		order_info: "Order Info",
		order: "Order",
		order_number_label: "Order Number",
		email: "Email",
		customer: "Customer",
		payment_method: "Payment Method",
		no_payment_method: "No payment method",
		card_ending_in: "{{brand}} ending in {{last4}}",
		shipping_address: "Shipping Address",
		no_shipping_address: "No shipping address available",
		billing_address: "Billing Address",
		shipping_method: "Shipping Method",
		estimated_delivery: "Est. {{estimate}}",
		sku_label: "SKU: {{sku}}"
	},
	loaders: {
		de: () => import("./de-Cypc-Hxq.mjs").then((m) => m.default),
		el: () => import("./el-Bh8hJ3Sb.mjs").then((m) => m.default),
		es: () => import("./es-Cg8cMOtp.mjs").then((m) => m.default),
		fr: () => import("./fr-DgWrGvEV.mjs").then((m) => m.default),
		he: () => import("./he-BVY6B90O.mjs").then((m) => m.default),
		hu: () => import("./hu-LLo6jGPe.mjs").then((m) => m.default),
		id: () => import("./id-BX7tRIJi.mjs").then((m) => m.default),
		it: () => import("./it-v6VAzerN.mjs").then((m) => m.default),
		ja: () => import("./ja-DXou4ipe.mjs").then((m) => m.default),
		ko: () => import("./ko-Dz-Wgxg1.mjs").then((m) => m.default),
		nl: () => import("./nl-R5otfCco.mjs").then((m) => m.default),
		pl: () => import("./pl-XmX4DXLj.mjs").then((m) => m.default),
		pt: () => import("./pt-Dp-Xud8m.mjs").then((m) => m.default),
		ro: () => import("./ro-_VHATAwl.mjs").then((m) => m.default),
		ru: () => import("./ru-uYfqdjiU.mjs").then((m) => m.default),
		th: () => import("./th-DRXe_VBC.mjs").then((m) => m.default),
		tl: () => import("./tl-DhIAeJNn.mjs").then((m) => m.default),
		tr: () => import("./tr-D7wxmwZ0.mjs").then((m) => m.default),
		zh_CN: () => import("./zh_CN-DwjNaGj-.mjs").then((m) => m.default),
		zh_TW: () => import("./zh_TW-BxdfA8tp.mjs").then((m) => m.default)
	}
});
function createOrdersTranslationAdapter(locale, dict) {
	return createStaticDictAdapter(locale, dict);
}
//#endregion
//#region ../../orders/core/src/translation-api-context.ts
const { Provider, useTranslation } = createTranslationContext("Orders");
const OrdersTranslationProvider = Provider;
const useOrdersTranslation = useTranslation;
//#endregion
//#region src/providers/OrdersTranslationBridge.tsx
function OrdersTranslationBridge({ children }) {
	const { locale } = useActiveLocale();
	const dict = useDomainDict(ordersDomain, locale);
	return /* @__PURE__ */ jsx(OrdersTranslationProvider, {
		value: useMemo(() => createOrdersTranslationAdapter(locale, dict), [locale, dict]),
		children
	});
}
//#endregion
//#region src/screens/orders/portal-orders-list-helpers.ts
const replaceN = (s, n) => s.replace("{n}", String(n));
const STATUS_LOOKUP = {
	delivered: {
		kind: "delivered",
		labelKey: "orders_status_delivered"
	},
	completed: {
		kind: "delivered",
		labelKey: "orders_status_delivered"
	},
	fulfilled: {
		kind: "delivered",
		labelKey: "orders_status_delivered"
	},
	shipped: {
		kind: "shipped",
		labelKey: "orders_status_shipped"
	},
	cancelled: { kind: "cancelled" },
	returned: { kind: "cancelled" },
	refunded: { kind: "cancelled" },
	preparing: {
		kind: "preparing",
		labelKey: "orders_status_preparing"
	},
	pending: {
		kind: "pending",
		labelKey: "orders_status_processing"
	},
	unfulfilled: {
		kind: "pending",
		labelKey: "orders_status_processing"
	},
	processing: {
		kind: "pending",
		labelKey: "orders_status_processing"
	}
};
/**
* Map a raw `order_status` string from the BFF onto our internal status
* vocabulary (`StatusKind`). Aliases are folded together (`completed` →
* `delivered`, `unfulfilled` → `pending`, etc.). Unknown statuses pass
* through with `kind: "pending"` and the raw label capitalized — never
* synthesize a colored pill that pretends to be real status data.
*/
function mapStatus(orderStatus, t) {
	const entry = STATUS_LOOKUP[(orderStatus || "").toLowerCase()];
	const rawLabel = orderStatus ? orderStatus.charAt(0).toUpperCase() + orderStatus.slice(1) : "—";
	if (!entry) return {
		kind: "pending",
		label: rawLabel
	};
	return {
		kind: entry.kind,
		label: entry.labelKey ? t(entry.labelKey) : rawLabel
	};
}
const STATUS_STYLES = {
	delivered: {
		bg: "bg-emerald-50 dark:bg-emerald-950/40",
		text: "text-emerald-700 dark:text-emerald-400",
		dot: "bg-emerald-500"
	},
	shipped: {
		bg: "bg-sky-50 dark:bg-sky-950/40",
		text: "text-sky-700 dark:text-sky-400",
		dot: "bg-sky-500"
	},
	preparing: {
		bg: "bg-amber-50 dark:bg-amber-950/40",
		text: "text-amber-700 dark:text-amber-400",
		dot: "bg-amber-500"
	},
	pending: {
		bg: "bg-profile-icon-bg",
		text: "text-profile-text-muted",
		dot: "bg-profile-text-muted"
	},
	cancelled: {
		bg: "bg-profile-danger-bg",
		text: "text-profile-danger-icon",
		dot: "bg-profile-danger-icon"
	}
};
function filterPredicate(filter, order) {
	if (filter === "all") return true;
	if (filter === "subscription") return order.subscription != null;
	const status = mapStatus(order.order_status, identity).kind;
	if (filter === "delivered") return status === "delivered" || status === "shipped";
	if (filter === "preparing") return status === "preparing" || status === "pending";
	return true;
}
const identity = (k) => k;
function countByFilter(list) {
	return {
		all: list.length,
		delivered: list.filter((o) => filterPredicate("delivered", o)).length,
		preparing: list.filter((o) => filterPredicate("preparing", o)).length,
		subscription: list.filter((o) => filterPredicate("subscription", o)).length
	};
}
/**
* Group orders into date buckets ("This week", "This month", month name, or
* "{Month} {year}" for anything older than the current year). Insertion
* order is preserved within and between buckets so newest-first ordering
* from the BFF carries through.
*
* `t` resolves the structural bucket labels ("This week" / "This month").
* Older buckets use `toLocaleDateString` which is locale-aware on its own.
* `now` is injectable for tests; defaults to the current wall-clock time.
*/
function groupOrdersByDate(list, t, now = /* @__PURE__ */ new Date()) {
	if (list.length === 0) return [];
	const startOfToday = new Date(now.getFullYear(), now.getMonth(), now.getDate());
	const sevenDaysAgo = new Date(startOfToday);
	sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 7);
	const startOfMonth = new Date(now.getFullYear(), now.getMonth(), 1);
	const startOfYear = new Date(now.getFullYear(), 0, 1);
	const buckets = /* @__PURE__ */ new Map();
	const order = [];
	for (const o of list) {
		const created = new Date(o.created_at);
		let label;
		if (created >= sevenDaysAgo) label = t("orders_group_this_week");
		else if (created >= startOfMonth) label = t("orders_group_this_month");
		else if (created >= startOfYear) label = created.toLocaleDateString(void 0, { month: "long" });
		else label = created.toLocaleDateString(void 0, {
			month: "long",
			year: "numeric"
		});
		let bucket = buckets.get(label);
		if (!bucket) {
			bucket = [];
			buckets.set(label, bucket);
			order.push(label);
		}
		bucket.push(o);
	}
	return order.map((label) => ({
		label,
		orders: buckets.get(label) ?? []
	}));
}
/**
* Render a friendly relative-time label for an order's created_at.
* `t` resolves the relative-time templates; `{n}` placeholders are
* substituted with the day/week count. Absolute dates use
* `toLocaleDateString` which is locale-aware on its own.
* `now` is injectable for tests.
*/
function formatFriendlyDate(iso, t, now = /* @__PURE__ */ new Date()) {
	try {
		const d = new Date(iso);
		const startOfToday = new Date(now.getFullYear(), now.getMonth(), now.getDate());
		const startOfDate = new Date(d.getFullYear(), d.getMonth(), d.getDate());
		const diffDays = Math.round((startOfToday.getTime() - startOfDate.getTime()) / (1e3 * 60 * 60 * 24));
		if (diffDays === 0) return t("orders_today");
		if (diffDays === 1) return t("orders_yesterday");
		if (diffDays < 7) return replaceN(t("orders_n_days_ago"), diffDays);
		if (diffDays < 14) return t("orders_last_week");
		if (diffDays < 30) return replaceN(t("orders_n_weeks_ago"), Math.round(diffDays / 7));
		if (d.getFullYear() === now.getFullYear()) return d.toLocaleDateString(void 0, {
			month: "short",
			day: "numeric"
		});
		return d.toLocaleDateString(void 0, {
			month: "short",
			day: "numeric",
			year: "numeric"
		});
	} catch {
		return "";
	}
}
/**
* Compute the per-image transform for the photo-stack fan in `OrderRow`.
* Index 0 is the front (centered, no rotation); index 1 peeks right;
* index 2 peeks left.
*/
function fanStyle(i, count) {
	if (i === 0) return {
		left: "50%",
		transform: "translateX(-50%)",
		zIndex: 30
	};
	if (i === 1) return {
		left: "50%",
		transform: count === 2 ? "translateX(-25%) rotate(7deg)" : "translateX(-20%) rotate(7deg)",
		zIndex: 20
	};
	return {
		left: "50%",
		transform: "translateX(-80%) rotate(-7deg)",
		zIndex: 10
	};
}
//#endregion
//#region src/screens/orders/PortalOrdersList.tsx
const identityT = (key) => key;
function PortalOrdersList({ customerId, onOrderClick, t = identityT }) {
	const [searchTerm, setSearchTerm] = useState("");
	const [filter, setFilter] = useState("all");
	const { data, isLoading, isError, refetch, fetchNextPage, hasNextPage, isFetchingNextPage } = useInfiniteCustomerOrders({
		customerId,
		limit: 10,
		search: searchTerm || void 0,
		sort: "-created_at"
	}, { enabled: !!customerId });
	const list = useMemo(() => data?.pages.flatMap((p) => p.orders) ?? [], [data]);
	const counts = useMemo(() => countByFilter(list), [list]);
	const filteredList = useMemo(() => list.filter((o) => filterPredicate(filter, o)), [list, filter]);
	const groups = useMemo(() => groupOrdersByDate(filteredList, t), [filteredList, t]);
	return /* @__PURE__ */ jsxs(Fragment$1, { children: [/* @__PURE__ */ jsx(ScreenHeaderBreadcrumbs, { children: /* @__PURE__ */ jsx(Breadcrumb, { children: /* @__PURE__ */ jsx(BreadcrumbList, {
		className: "text-lg",
		children: /* @__PURE__ */ jsx(BreadcrumbItem, { children: /* @__PURE__ */ jsx(BreadcrumbPage, {
			className: "font-semibold",
			children: t("orders_title")
		}) })
	}) }) }), /* @__PURE__ */ jsx("div", {
		className: "relative",
		children: /* @__PURE__ */ jsxs("div", {
			className: "max-w-profile-container relative mx-auto px-5 pt-8 pb-20 md:px-8",
			children: [
				/* @__PURE__ */ jsxs("div", {
					className: "flex items-center gap-3",
					children: [/* @__PURE__ */ jsx("h1", {
						className: "text-profile-hero tracking-profile-hero text-profile-text md:text-profile-hero-lg flex-1 truncate font-bold",
						children: t("orders_title")
					}), /* @__PURE__ */ jsxs("div", {
						className: "relative hidden sm:block",
						children: [/* @__PURE__ */ jsx(Search, {
							className: "text-profile-text-muted pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2",
							strokeWidth: 2
						}), /* @__PURE__ */ jsx(Input, {
							value: searchTerm,
							onChange: (e) => setSearchTerm(e.target.value),
							placeholder: t("orders_search_placeholder"),
							className: "ring-profile-border bg-profile-card text-profile-sm h-9 w-64 rounded-md pl-9"
						})]
					})]
				}),
				list.length > 0 && /* @__PURE__ */ jsx(FilterPills, {
					active: filter,
					counts,
					onChange: setFilter,
					t
				}),
				isLoading ? /* @__PURE__ */ jsx("div", {
					className: "ring-profile-border bg-profile-card mt-4 overflow-hidden rounded-2xl ring-1",
					children: /* @__PURE__ */ jsx(OrdersListSkeleton, {})
				}) : isError ? /* @__PURE__ */ jsx("div", {
					className: "ring-profile-border bg-profile-card mt-4 overflow-hidden rounded-2xl ring-1",
					children: /* @__PURE__ */ jsx(ErrorState, {
						onRetry: () => refetch(),
						t
					})
				}) : filteredList.length === 0 ? /* @__PURE__ */ jsx("div", {
					className: "ring-profile-border bg-profile-card mt-4 overflow-hidden rounded-2xl ring-1",
					children: /* @__PURE__ */ jsx(EmptyState, {
						searching: !!searchTerm || filter !== "all",
						t
					})
				}) : /* @__PURE__ */ jsx("div", {
					className: "mt-4 space-y-6",
					children: groups.map((group) => /* @__PURE__ */ jsxs("div", { children: [/* @__PURE__ */ jsx("div", {
						className: "text-profile-xs text-profile-text-muted mb-2 px-1 font-semibold",
						children: group.label
					}), /* @__PURE__ */ jsx("div", {
						className: "space-y-3",
						children: group.orders.map((order) => /* @__PURE__ */ jsx(OrderRow, {
							order,
							onClick: () => onOrderClick(order),
							t
						}, order.id))
					})] }, group.label))
				}),
				hasNextPage && /* @__PURE__ */ jsx("div", {
					className: "mt-3 flex justify-center",
					children: /* @__PURE__ */ jsx("button", {
						type: "button",
						onClick: () => fetchNextPage(),
						disabled: isFetchingNextPage,
						className: "ring-profile-border bg-profile-card text-profile-text hover:bg-profile-pill-hover text-profile-xs inline-flex items-center gap-1 rounded-md px-3 py-1.5 font-bold ring-1 transition-all disabled:cursor-not-allowed disabled:opacity-40",
						children: isFetchingNextPage ? t("orders_loading") : t("orders_load_more")
					})
				})
			]
		})
	})] });
}
const FILTER_KEYS = [
	{
		key: "all",
		labelKey: "orders_filter_all"
	},
	{
		key: "delivered",
		labelKey: "orders_filter_delivered"
	},
	{
		key: "preparing",
		labelKey: "orders_filter_preparing"
	},
	{
		key: "subscription",
		labelKey: "orders_filter_subscription"
	}
];
function FilterPills({ active, counts, onChange, t }) {
	return /* @__PURE__ */ jsx("div", {
		className: "-mx-1 mt-5 flex flex-wrap gap-1.5 px-1",
		children: FILTER_KEYS.map((f) => {
			const isActive = f.key === active;
			const count = counts[f.key];
			return /* @__PURE__ */ jsxs("button", {
				type: "button",
				onClick: () => onChange(f.key),
				className: `text-profile-xs inline-flex items-center gap-1.5 rounded-md px-3 py-1.5 font-bold transition-all ${isActive ? "bg-profile-dark text-profile-dark-foreground" : "ring-profile-border bg-profile-card text-profile-text hover:bg-profile-pill-hover ring-1"}`,
				children: [t(f.labelKey), /* @__PURE__ */ jsx("span", {
					className: `text-profile-micro tabular-nums ${isActive ? "text-profile-dark-foreground/70" : "text-profile-text-muted"}`,
					children: count
				})]
			}, f.key);
		})
	});
}
function OrderRow({ order, onClick, t }) {
	const status = mapStatus(order.order_status, t);
	const dateLabel = formatFriendlyDate(order.created_at, t);
	const total = formatOrderTotal(order);
	const titleText = order.first_item?.title || `${t("orders_order_number_prefix")}${order.order_number}`;
	const titleSuffix = order.items_count > 1 ? t("orders_more_items").replace("{n}", String(order.items_count - 1)) : "";
	return /* @__PURE__ */ jsxs("button", {
		type: "button",
		onClick,
		className: "group bg-profile-card ring-profile-card-edge shadow-profile-card hover:ring-profile-text/10 hover:shadow-profile-card-hover focus-visible:ring-profile-text/30 relative flex w-full cursor-pointer items-center gap-4 rounded-2xl px-4 py-4 text-left ring-1 transition-all duration-300 hover:-translate-y-0.5 focus-visible:ring-2 focus-visible:outline-none",
		children: [/* @__PURE__ */ jsxs("div", {
			className: "min-w-0 flex-1",
			children: [/* @__PURE__ */ jsxs("div", {
				className: "flex items-center gap-2",
				children: [/* @__PURE__ */ jsxs("div", {
					className: "text-profile-md text-profile-text truncate font-bold",
					children: [titleText, titleSuffix && /* @__PURE__ */ jsx("span", {
						className: "text-profile-text-muted font-medium",
						children: titleSuffix
					})]
				}), /* @__PURE__ */ jsx(StatusPill, { status })]
			}), /* @__PURE__ */ jsxs("div", {
				className: "text-profile-xs text-profile-text-muted mt-1 truncate",
				children: [
					dateLabel,
					" · ",
					total
				]
			})]
		}), /* @__PURE__ */ jsx(ThumbnailStack, {
			fallback: order.first_item,
			urls: order.thumbnail_image_urls,
			isSubscription: order.subscription != null,
			t
		})]
	});
}
function ThumbnailStack({ urls, fallback, isSubscription, t }) {
	const effective = (urls && urls.length > 0 ? urls : fallback?.image_url ? [fallback.image_url] : []).slice(0, 3);
	if (effective.length === 0) return /* @__PURE__ */ jsxs("div", {
		className: "ring-profile-border bg-profile-icon-bg text-profile-text-muted relative flex size-12 shrink-0 items-center justify-center rounded-xl ring-1",
		children: [/* @__PURE__ */ jsx(ImageOff, {
			className: "size-5",
			strokeWidth: 1.75
		}), isSubscription && /* @__PURE__ */ jsx(SubscriptionBadge, { t })]
	});
	if (effective.length === 1) return /* @__PURE__ */ jsxs("div", {
		className: "relative size-12 shrink-0",
		children: [/* @__PURE__ */ jsx("img", {
			src: effective[0],
			alt: "",
			className: "bg-profile-card ring-profile-canvas size-12 rounded-xl object-cover ring-[3px]"
		}), isSubscription && /* @__PURE__ */ jsx(SubscriptionBadge, { t })]
	});
	return /* @__PURE__ */ jsxs("div", {
		className: `relative h-12 ${effective.length === 3 ? "w-[80px]" : "w-[60px]"} shrink-0`,
		children: [effective.map((url, i) => /* @__PURE__ */ jsx("img", {
			src: url,
			alt: "",
			className: "bg-profile-card ring-profile-canvas absolute top-0 size-12 rounded-xl object-cover ring-[3px]",
			style: fanStyle(i, effective.length)
		}, `${url}-${i}`)), isSubscription && /* @__PURE__ */ jsx(SubscriptionBadge, { t })]
	});
}
function SubscriptionBadge({ t }) {
	return /* @__PURE__ */ jsx("div", {
		className: "bg-profile-dark text-profile-dark-foreground ring-profile-canvas absolute -top-1 -right-1 z-40 flex size-5 items-center justify-center rounded-full ring-2",
		title: t("orders_subscription_badge"),
		children: /* @__PURE__ */ jsx(Repeat, {
			className: "size-2.5",
			strokeWidth: 2.75
		})
	});
}
function StatusPill({ status }) {
	const styles = STATUS_STYLES[status.kind];
	return /* @__PURE__ */ jsxs("span", {
		className: `text-profile-2xs inline-flex shrink-0 items-center gap-1 rounded-md px-2 py-0.5 font-semibold ${styles.bg} ${styles.text}`,
		children: [/* @__PURE__ */ jsx("span", { className: `size-1.5 rounded-full ${styles.dot}` }), status.label]
	});
}
function OrdersListSkeleton() {
	return /* @__PURE__ */ jsx(Fragment$1, { children: Array(4).fill(0).map((_, i) => /* @__PURE__ */ jsxs("div", {
		className: `flex items-center gap-3 px-4 py-3.5 ${i < 3 ? "border-profile-divider border-b" : ""}`,
		children: [/* @__PURE__ */ jsx("div", { className: "bg-profile-icon-bg size-12 shrink-0 animate-pulse rounded-xl" }), /* @__PURE__ */ jsxs("div", {
			className: "flex-1 space-y-2",
			children: [/* @__PURE__ */ jsx("div", { className: "bg-profile-icon-bg h-4 w-1/3 animate-pulse rounded" }), /* @__PURE__ */ jsx("div", { className: "bg-profile-icon-bg h-3 w-1/2 animate-pulse rounded" })]
		})]
	}, i)) });
}
function EmptyState({ searching, t }) {
	return /* @__PURE__ */ jsxs("div", {
		className: "flex flex-col items-center gap-2 px-4 py-12 text-center",
		children: [
			/* @__PURE__ */ jsx("div", {
				className: "bg-profile-icon-bg flex size-12 items-center justify-center rounded-full",
				children: /* @__PURE__ */ jsx(Search, {
					className: "text-profile-text-muted size-5",
					strokeWidth: 2
				})
			}),
			/* @__PURE__ */ jsx("div", {
				className: "text-profile-base text-profile-text font-bold",
				children: searching ? t("orders_no_matching") : t("orders_none_yet")
			}),
			/* @__PURE__ */ jsx("div", {
				className: "text-profile-xs text-profile-text-muted max-w-sm",
				children: searching ? t("orders_searching_hint") : t("orders_empty_hint")
			})
		]
	});
}
function ErrorState({ onRetry, t }) {
	return /* @__PURE__ */ jsxs("div", {
		className: "flex flex-col items-center gap-2 px-4 py-12 text-center",
		children: [
			/* @__PURE__ */ jsx("div", {
				className: "bg-profile-icon-bg flex size-12 items-center justify-center rounded-full",
				children: /* @__PURE__ */ jsx(AlertCircle, {
					className: "text-profile-text-muted size-5",
					strokeWidth: 2
				})
			}),
			/* @__PURE__ */ jsx("div", {
				className: "text-profile-base text-profile-text font-bold",
				children: t("orders_load_failed_title")
			}),
			/* @__PURE__ */ jsx("div", {
				className: "text-profile-xs text-profile-text-muted max-w-sm",
				children: t("orders_load_failed_hint")
			}),
			/* @__PURE__ */ jsx("button", {
				type: "button",
				onClick: onRetry,
				className: "bg-profile-dark text-profile-dark-foreground hover:bg-profile-dark-hover text-profile-xs mt-2 inline-flex items-center gap-1 rounded-md px-3 py-1.5 font-bold transition-all",
				children: t("orders_try_again")
			})
		]
	});
}
//#endregion
//#region src/screens/OrdersListScreen.tsx
const BFF_SCOPED_CUSTOMER_ID = 1;
const translations = {
	orders_title: "Order history",
	orders_search_placeholder: "Search orders...",
	orders_loading: "Loading...",
	orders_load_more: "Load more",
	orders_filter_all: "All",
	orders_filter_delivered: "Delivered",
	orders_filter_preparing: "Preparing",
	orders_filter_subscription: "Subscription",
	orders_status_delivered: "Delivered",
	orders_status_shipped: "Shipped",
	orders_status_preparing: "Preparing",
	orders_status_processing: "Processing",
	orders_group_this_week: "This week",
	orders_group_this_month: "This month",
	orders_today: "Today",
	orders_yesterday: "Yesterday",
	orders_n_days_ago: "{n} days ago",
	orders_last_week: "Last week",
	orders_n_weeks_ago: "{n} weeks ago",
	orders_order_number_prefix: "Order #",
	orders_more_items: " + {n} more",
	orders_subscription_badge: "From subscription",
	orders_no_matching: "No matching orders",
	orders_none_yet: "No orders yet",
	orders_searching_hint: "Try a different search term.",
	orders_empty_hint: "Your orders will show up here after you place one.",
	orders_load_failed_title: "Couldn't load your orders",
	orders_load_failed_hint: "Something went wrong on our end. Please try again.",
	orders_try_again: "Try again"
};
const t = (key) => translations[key] ?? key;
function OrdersListScreen() {
	const { navigate } = useAppNavigation();
	const handleOrderClick = (order) => {
		navigate(`orders/${order.token}`);
	};
	return /* @__PURE__ */ jsx(PortalOrdersList, {
		customerId: BFF_SCOPED_CUSTOMER_ID,
		onOrderClick: handleOrderClick,
		t
	});
}
//#endregion
//#region ../../orders/ui/src/components/status-badge.tsx
const colorStyles = {
	green: "bg-green-500/15 text-foreground",
	yellow: "bg-yellow-500/15 text-foreground",
	red: "bg-red-500/15 text-foreground",
	blue: "bg-blue-500/15 text-foreground",
	gray: "bg-foreground/10 text-foreground"
};
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/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
//#region ../../orders/ui/src/components/static-map.tsx
function StaticMap({ apiKey, address, options, alt = "Shipping address map", className }) {
	const [errored, setErrored] = useState(false);
	const url = buildStaticMapUrl(apiKey, address, options);
	if (!url || errored) return null;
	return /* @__PURE__ */ jsx("img", {
		src: url,
		alt,
		width: options?.width ?? 600,
		height: options?.height ?? 300,
		className: className ?? "border-border w-full rounded border object-cover shadow-xs",
		onError: () => setErrored(true)
	});
}
//#endregion
//#region ../../orders/ui/src/components/portal-order-detail.tsx
const PAYMENT_TYPE_LABELS = {
	apple_pay: "Apple Pay",
	google_pay: "Google Pay",
	paypal: "PayPal",
	braintree_paypal: "PayPal",
	affirm: "Affirm",
	klarna: "Klarna",
	bread: "Bread",
	iap: "In-App Purchase",
	citcon: "Citcon",
	ppro: "PPRO",
	dlocal: "dLocal",
	droplet: "Droplet"
};
function DetailSkeleton() {
	return /* @__PURE__ */ jsxs("div", {
		className: "flex flex-col lg:grid lg:grid-cols-8",
		children: [/* @__PURE__ */ jsx("div", {
			className: "bg-muted flex flex-col items-center px-8 lg:col-span-4",
			children: /* @__PURE__ */ jsxs("div", {
				className: "w-full max-w-lg py-6",
				children: [
					/* @__PURE__ */ jsx(Skeleton, { className: "mb-4 h-6 w-48" }),
					/* @__PURE__ */ jsx("div", {
						className: "space-y-4",
						children: /* @__PURE__ */ jsxs("div", {
							className: "flex items-center space-x-4",
							children: [/* @__PURE__ */ jsx(Skeleton, { className: "h-24 w-24 rounded" }), /* @__PURE__ */ jsxs("div", {
								className: "flex-1 space-y-2",
								children: [/* @__PURE__ */ jsx(Skeleton, { className: "h-4 w-3/4" }), /* @__PURE__ */ jsx(Skeleton, { className: "h-4 w-1/2" })]
							})]
						})
					}),
					/* @__PURE__ */ jsxs("div", {
						className: "mt-6 space-y-2",
						children: [/* @__PURE__ */ jsx(Skeleton, { className: "h-4 w-full" }), /* @__PURE__ */ jsx(Skeleton, { className: "h-5 w-full" })]
					})
				]
			})
		}), /* @__PURE__ */ jsx("div", {
			className: "bg-background px-8 pt-4 lg:col-span-4",
			children: /* @__PURE__ */ jsxs("div", {
				className: "mx-auto max-w-lg lg:mx-0 lg:mr-auto",
				children: [/* @__PURE__ */ jsx(Skeleton, { className: "mb-4 h-10 w-full rounded" }), /* @__PURE__ */ jsxs("div", {
					className: "mt-6 space-y-4",
					children: [/* @__PURE__ */ jsx(Skeleton, { className: "h-5 w-40" }), /* @__PURE__ */ jsx(Skeleton, { className: "h-16 w-full rounded" })]
				})]
			})
		})]
	});
}
function SummaryRow({ label, value }) {
	return /* @__PURE__ */ jsxs("div", {
		className: "flex items-center justify-between text-sm",
		children: [/* @__PURE__ */ jsx("p", {
			className: "text-muted-foreground",
			children: label
		}), /* @__PURE__ */ jsx("p", {
			className: "text-foreground",
			children: value
		})]
	});
}
/**
* Display a positive money string as a deduction (prefixed with "-").
* Idempotent: if the value already starts with "-" we leave it alone, so
* a future BFF that returns signed discounts can't produce "--$10.00".
*/
function asNegative(value) {
	return value.startsWith("-") ? value : `-${value}`;
}
/**
* Pick the formatted currency string when present, falling back to the raw
* decimal so the row still renders something for orders where the BFF left
* the field nil (e.g. a checkout where shipping was never set).
*/
function moneyDisplay(formatted, fallback) {
	return formatted ?? fallback;
}
function formatAddressLines(address) {
	const lines = [];
	if (address.name) lines.push(address.name);
	if (address.address1) lines.push(address.address1);
	if (address.address2) lines.push(address.address2);
	const cityLine = [
		address.city,
		address.state,
		address.postal_code
	].filter(Boolean).join(", ");
	if (cityLine) lines.push(cityLine);
	if (address.country_code) lines.push(address.country_code);
	return lines;
}
function AddressSection({ address }) {
	const { t } = useOrdersTranslation();
	const lines = formatAddressLines(address);
	if (lines.length === 0) return null;
	return /* @__PURE__ */ jsxs("div", {
		className: "border-border mb-6 border-b pb-6",
		children: [/* @__PURE__ */ jsx("h3", {
			className: "text-foreground mb-3 text-sm/6 font-semibold",
			children: t("shipping_address")
		}), /* @__PURE__ */ jsx("div", {
			className: "text-foreground space-y-0.5 text-sm",
			children: lines.map((line, index) => /* @__PURE__ */ jsx("p", { children: line }, index))
		})]
	});
}
function PaymentMethodSection({ paymentMethod }) {
	const { t } = useOrdersTranslation();
	const { card_type, last4 } = paymentMethod;
	const brand = card_type ? card_type.toUpperCase() : PAYMENT_TYPE_LABELS[paymentMethod.payment_type] ?? paymentMethod.payment_type;
	const label = last4 ? t("card_ending_in", {
		brand,
		last4
	}) : brand;
	if (!label) return null;
	return /* @__PURE__ */ jsxs("div", {
		className: "border-border mb-6 border-b pb-6",
		children: [/* @__PURE__ */ jsx("h3", {
			className: "text-foreground mb-3 text-sm/6 font-semibold",
			children: t("payment_method")
		}), /* @__PURE__ */ jsx("p", {
			className: "text-foreground text-sm",
			children: label
		})]
	});
}
function LineItemImage({ src, alt }) {
	const { t } = useOrdersTranslation();
	const [errored, setErrored] = useState(false);
	if (errored) return /* @__PURE__ */ jsx("span", {
		className: "text-xs",
		children: t("no_image")
	});
	return /* @__PURE__ */ jsx("img", {
		src,
		alt,
		className: "h-full w-full object-cover",
		onError: () => setErrored(true)
	});
}
function ItemRow({ item, onSubscriptionClick }) {
	const { t } = useOrdersTranslation();
	const subscriptionToken = item.source_subscription?.subscription_token;
	return /* @__PURE__ */ jsxs("div", {
		className: "flex items-center space-x-4 py-4",
		children: [/* @__PURE__ */ jsxs("div", {
			className: "relative shrink-0",
			children: [/* @__PURE__ */ jsx("div", {
				className: "bg-muted text-muted-foreground flex h-24 w-24 items-center justify-center overflow-hidden rounded",
				children: item.image_url ? /* @__PURE__ */ jsx(LineItemImage, {
					src: item.image_url,
					alt: item.product_name
				}) : /* @__PURE__ */ jsx("span", {
					className: "text-xs",
					children: t("no_image")
				})
			}), item.quantity > 1 && /* @__PURE__ */ jsx("span", {
				className: "bg-foreground text-background absolute -top-2 -right-2 z-10 flex h-6 w-6 items-center justify-center rounded-full text-xs font-medium",
				children: item.quantity
			})]
		}), /* @__PURE__ */ jsxs("div", {
			className: "flex min-w-0 flex-1 flex-col space-y-0.5",
			children: [
				/* @__PURE__ */ jsx("p", {
					className: "text-foreground truncate text-sm font-medium",
					title: item.product_name,
					children: item.product_name
				}),
				item.variant_name && /* @__PURE__ */ jsx("p", {
					className: "text-muted-foreground truncate text-xs",
					title: item.variant_name,
					children: item.variant_name
				}),
				/* @__PURE__ */ jsx("p", {
					className: "text-foreground text-sm font-medium",
					children: moneyDisplay(item.total_in_currency, item.total)
				}),
				item.quantity > 1 && /* @__PURE__ */ jsxs("p", {
					className: "text-muted-foreground text-xs",
					children: [
						moneyDisplay(item.price_in_currency, item.price),
						" x ",
						item.quantity
					]
				}),
				subscriptionToken && onSubscriptionClick && /* @__PURE__ */ jsx("button", {
					type: "button",
					title: subscriptionToken,
					className: "mt-1 max-w-full cursor-pointer truncate text-left text-xs text-blue-600 transition-colors duration-200 hover:text-blue-700 hover:underline",
					onClick: () => onSubscriptionClick(subscriptionToken),
					children: t("subscription_hash", { token: subscriptionToken })
				})
			]
		})]
	});
}
function ItemsSection({ order, onSubscriptionClick }) {
	const { t } = useOrdersTranslation();
	return /* @__PURE__ */ jsx("section", {
		className: "bg-muted flex w-full flex-col items-center px-8 lg:col-span-4",
		children: /* @__PURE__ */ jsxs("div", {
			className: "flex w-full max-w-lg flex-col",
			children: [
				/* @__PURE__ */ jsxs("div", {
					className: "mt-4",
					children: [/* @__PURE__ */ jsx("h2", {
						className: "text-foreground mb-2 text-lg font-medium",
						children: t("items_count", { count: String(order.line_items.length) })
					}), /* @__PURE__ */ jsx("hr", { className: "border-border" })]
				}),
				/* @__PURE__ */ jsx("div", {
					className: "divide-border divide-y",
					children: order.line_items.map((item) => /* @__PURE__ */ jsx(ItemRow, {
						item,
						onSubscriptionClick
					}, item.id))
				}),
				/* @__PURE__ */ jsxs("div", {
					className: "border-border mb-4 space-y-1 border-t pt-4",
					children: [
						/* @__PURE__ */ jsx(SummaryRow, {
							label: t("subtotal"),
							value: moneyDisplay(order.subtotal_in_currency, order.subtotal)
						}),
						parseFloat(order.discount) > 0 && /* @__PURE__ */ jsx(SummaryRow, {
							label: t("discount"),
							value: asNegative(moneyDisplay(order.discount_in_currency, order.discount))
						}),
						/* @__PURE__ */ jsx(SummaryRow, {
							label: t("shipping"),
							value: moneyDisplay(order.shipping_in_currency, order.shipping)
						}),
						/* @__PURE__ */ jsx(SummaryRow, {
							label: t("tax"),
							value: moneyDisplay(order.tax_in_currency, order.tax)
						}),
						/* @__PURE__ */ jsxs("div", {
							className: "mt-2 flex items-center justify-between text-base font-medium",
							children: [/* @__PURE__ */ jsx("p", {
								className: "text-muted-foreground text-sm font-medium",
								children: t("total")
							}), /* @__PURE__ */ jsx("p", {
								className: "text-foreground text-base font-bold",
								children: moneyDisplay(order.total_in_currency, order.total)
							})]
						})
					]
				}),
				order.total_points_credited != null && order.total_points_credited > 0 && /* @__PURE__ */ jsx("div", {
					className: "border-border mb-4 border-t pt-4",
					children: /* @__PURE__ */ jsxs("div", {
						className: "flex items-baseline justify-between",
						children: [/* @__PURE__ */ jsxs("div", { children: [/* @__PURE__ */ jsx("p", {
							className: "text-foreground text-sm font-semibold",
							children: t("points_earned")
						}), order.customer_points_balance != null && /* @__PURE__ */ jsx("p", {
							className: "text-muted-foreground text-xs",
							children: t("points_total", { count: order.customer_points_balance.toLocaleString() })
						})] }), /* @__PURE__ */ jsxs("div", {
							className: "text-right",
							children: [/* @__PURE__ */ jsxs("p", {
								className: "text-foreground text-sm font-semibold",
								children: ["+", order.total_points_credited.toLocaleString()]
							}), /* @__PURE__ */ jsx("p", {
								className: "text-muted-foreground text-xs",
								children: t("points")
							})]
						})]
					})
				})
			]
		})
	});
}
function DetailsSection({ order, googleMapsApiKey }) {
	const { t } = useOrdersTranslation();
	return /* @__PURE__ */ jsx("div", {
		className: "bg-background px-8 pt-4 lg:col-span-4",
		children: /* @__PURE__ */ jsxs("div", {
			className: "mx-auto max-w-lg lg:mx-0 lg:mr-auto",
			children: [
				/* @__PURE__ */ jsx("div", {
					className: "border-border mb-6 border-b pb-6",
					children: /* @__PURE__ */ jsx("div", {
						className: "flex flex-wrap items-center gap-3",
						children: /* @__PURE__ */ jsxs("div", {
							className: "flex items-center gap-2",
							children: [/* @__PURE__ */ jsx("span", {
								className: "text-muted-foreground text-sm",
								children: t("status_label")
							}), /* @__PURE__ */ jsx(OrderStatusBadge, { status: order.status })]
						})
					})
				}),
				googleMapsApiKey && order.address && /* @__PURE__ */ jsx("div", {
					className: "mb-6",
					children: /* @__PURE__ */ jsx(StaticMap, {
						apiKey: googleMapsApiKey,
						address: order.address
					})
				}),
				/* @__PURE__ */ jsxs("div", {
					className: "border-border mb-6 border-b pb-6",
					children: [
						/* @__PURE__ */ jsx("h3", {
							className: "text-foreground mb-3 text-sm/6 font-semibold",
							children: t("order_info")
						}),
						/* @__PURE__ */ jsxs("div", {
							className: "divide-border flex divide-x",
							children: [/* @__PURE__ */ jsxs("div", {
								className: "flex-1 pr-4",
								children: [/* @__PURE__ */ jsx("div", {
									className: "text-muted-foreground text-sm",
									children: t("order")
								}), /* @__PURE__ */ jsxs("div", {
									className: "text-foreground font-medium",
									children: ["#", order.id]
								})]
							}), /* @__PURE__ */ jsxs("div", {
								className: "flex-1 pl-4 text-right",
								children: [/* @__PURE__ */ jsx("div", {
									className: "text-muted-foreground text-sm",
									children: t("date")
								}), /* @__PURE__ */ jsx("div", {
									className: "text-foreground font-medium",
									children: new Date(order.created_at).toLocaleDateString("en-US", {
										year: "numeric",
										month: "short",
										day: "numeric"
									})
								})]
							})]
						}),
						order.customer_email && /* @__PURE__ */ jsxs("div", {
							className: "mt-3",
							children: [/* @__PURE__ */ jsx("div", {
								className: "text-muted-foreground text-sm",
								children: t("email")
							}), /* @__PURE__ */ jsx("div", {
								className: "text-foreground text-sm font-medium",
								children: order.customer_email
							})]
						}),
						order.customer_name && /* @__PURE__ */ jsxs("div", {
							className: "mt-3",
							children: [/* @__PURE__ */ jsx("div", {
								className: "text-muted-foreground text-sm",
								children: t("customer")
							}), /* @__PURE__ */ jsx("div", {
								className: "text-foreground text-sm font-medium",
								children: order.customer_name
							})]
						})
					]
				}),
				order.address && /* @__PURE__ */ jsx(AddressSection, { address: order.address }),
				order.payment_method && /* @__PURE__ */ jsx(PaymentMethodSection, { paymentMethod: order.payment_method })
			]
		})
	});
}
function PortalOrderDetail({ id, googleMapsApiKey, onNotFound, onError, onSubscriptionClick }) {
	const { data, isLoading, error } = usePortalTenantOrder(id);
	const order = data?.order;
	useEffect(() => {
		if (!isLoading && error) onError?.(error);
	}, [
		isLoading,
		error,
		onError
	]);
	useEffect(() => {
		if (!isLoading && !error && !order) onNotFound?.();
	}, [
		isLoading,
		error,
		order,
		onNotFound
	]);
	if (isLoading) return /* @__PURE__ */ jsx(DetailSkeleton, {});
	if (!order) return null;
	return /* @__PURE__ */ jsxs("div", {
		className: "flex flex-col lg:grid lg:grid-cols-8",
		children: [/* @__PURE__ */ jsx(ItemsSection, {
			order,
			onSubscriptionClick
		}), /* @__PURE__ */ jsx(DetailsSection, {
			order,
			googleMapsApiKey
		})]
	});
}
//#endregion
//#region ../../orders/ui/src/screens/PortalOrderDetailScreen.tsx
function PortalOrderDetailScreen({ id, googleMapsApiKey, onNavigateToList, onNotFound, onError, onSubscriptionClick }) {
	const { t } = useOrdersTranslation();
	return /* @__PURE__ */ jsxs(Fragment$1, { children: [/* @__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_detail", { id: String(id) })
			}) })
		]
	}) }) }), /* @__PURE__ */ jsx("div", {
		className: "mx-auto max-w-7xl px-4 py-4 sm:px-6 sm:py-6 lg:px-10 lg:py-8",
		children: /* @__PURE__ */ jsx(PortalOrderDetail, {
			id,
			googleMapsApiKey,
			onNotFound,
			onError,
			onSubscriptionClick
		})
	})] });
}
//#endregion
//#region src/screens/OrderDetailScreen.tsx
function OrderDetailScreen({ token, onToast }) {
	const { navigate } = useAppNavigation();
	const { config } = useFluidContext();
	const { t } = useOrdersTranslation();
	return /* @__PURE__ */ jsx(PortalOrderDetailScreen, {
		id: token,
		googleMapsApiKey: config.googleMapsApiKey,
		onNavigateToList: () => navigate("orders"),
		onNotFound: () => {
			onToast(t("order_not_found"), "warning");
			navigate("orders");
		},
		onError: (err) => {
			onToast(t("error_loading_order", { message: err instanceof Error ? err.message : t("error_generic") }), "error");
		},
		onSubscriptionClick: (subscriptionToken) => navigate(`subscriptions/${subscriptionToken}`)
	});
}
//#endregion
//#region src/screens/OrdersScreen.tsx
function defaultToast(message, type) {
	fluidToast({
		title: message,
		type
	});
}
function OrdersScreen({ onToast, background, textColor, accentColor, padding, borderRadius, ...divProps }) {
	const { currentSlug } = useAppNavigation();
	const effectiveToast = onToast ?? defaultToast;
	const detailToken = currentSlug.split("/")[1];
	if (detailToken !== void 0) return /* @__PURE__ */ jsx(OrdersTranslationBridge, { children: /* @__PURE__ */ jsx("div", {
		...divProps,
		children: /* @__PURE__ */ jsx(PortalOrdersApiProvider, { children: /* @__PURE__ */ jsx(OrderDetailScreen, {
			token: detailToken,
			onToast: effectiveToast
		}) })
	}) });
	return /* @__PURE__ */ jsx(OrdersTranslationBridge, { children: /* @__PURE__ */ jsx("div", {
		...divProps,
		children: /* @__PURE__ */ jsx(PortalOrdersApiProvider, { children: /* @__PURE__ */ jsx(OrdersListScreen, {}) })
	}) });
}
const ordersScreenPropertySchema = {
	widgetType: "OrdersScreen",
	displayName: "Orders Screen",
	tabsConfig: [{
		id: "styling",
		label: "Styling"
	}],
	fields: []
};
//#endregion
export { ordersScreenPropertySchema as n, OrdersScreen as t };

//# sourceMappingURL=OrdersScreen-D48ntVjo.mjs.map