import { R as orders_list, z as orders_show } from "./translation-adapter-B-Vhfzbz.mjs";
import { d as ordersDomain, n as useFluidContext, u as createOrdersTranslationAdapter } from "./FluidProvider-w-PbxHiZ.mjs";
import { a as usePortalTenantClient } from "./query-keys-oPgLh6FY.mjs";
import { a as useActiveLocale, r as useDomainDict } from "./static-dict-adapter-CMDcV28R.mjs";
import { t as createTranslationContext } from "./translation-api-context-factory-dNziJNS1.mjs";
import { i as usePointsLabel } from "./PointsWidget-Bvnj_7Ck.mjs";
import { Gn as cn, M as Input, _n as BreadcrumbPage, g as Skeleton, gn as BreadcrumbList, hn as BreadcrumbLink, mn as BreadcrumbItem, p as fluidToast, pn as Breadcrumb, vn as BreadcrumbSeparator } from "./src-CAi8-qUm.mjs";
import { n as ScreenHeaderBreadcrumbs } from "./ScreenHeaderContext-BR9cGisQ.mjs";
import { n as useAppNavigation } from "./AppNavigationContext-DQcQSWd1.mjs";
import { a as paymentDescriptorLabel, i as normalizePaymentDescriptor, r as maskedCardLabelSegments, s as resolvePaymentMethodDisplay, t as isCardPaymentDescriptor, u as normalizeCardBrand } from "./display-naBonVqF.mjs";
import { createContext, use, 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 = use(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
	],
	stats: (params) => [
		...ordersKeys.all,
		"stats",
		params
	],
	detail: (orderToken) => [
		...ordersKeys.all,
		"detail",
		orderToken
	],
	adminDetail: (id) => ["order", id],
	changeLogs: (id, params) => params == null ? ["order_change_logs_paginated", id] : [
		"order_change_logs_paginated",
		id,
		params
	],
	changeLogsPage: (id, params) => [
		"order_change_logs",
		id,
		params
	],
	journey: (id) => ["orderJourneyV3", id],
	journeyEvents: (id) => ["order-journey-events", id],
	fraudCheckDetails: (id) => ["fraud-check-details", id]
};
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,
		phone: raw.phone ?? null
	};
}
function mapPaymentMethod(raw) {
	if (!raw) return null;
	return {
		id: raw.id ?? 0,
		source: raw.source ?? "",
		payment_type: raw.payment_type ?? "",
		card_network: raw.card_network ?? null,
		last4: raw.last4 ?? null,
		logo_url: raw.logo_url ?? null
	};
}
function mapShippingMethod(raw) {
	if (!raw) return null;
	return {
		id: raw.id ?? null,
		title: raw.title ?? ""
	};
}
/** Loose-read mapper for `tracking_informations`. Field is added to
*  the BFF by the paired Rails change but not yet in the generated
*  OpenAPI types — we read defensively so older deployments that
*  don't send the field render an empty array (block hides itself). */
function mapTrackingInformations(raw) {
	if (!Array.isArray(raw)) return [];
	return raw.flatMap((entry) => {
		if (typeof entry !== "object" || entry === null) return [];
		const e = entry;
		if (typeof e.tracking_number !== "string" || e.tracking_number.length === 0) return [];
		return [{
			id: typeof e.id === "number" ? e.id : 0,
			tracking_number: e.tracking_number,
			shipping_carrier: typeof e.shipping_carrier === "string" ? e.shipping_carrier : null,
			tracking_url: typeof e.tracking_url === "string" ? e.tracking_url : 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");
	const rawOrderNumber = raw.order_number;
	return {
		id: raw.id ?? 0,
		token: raw.token ?? "",
		order_number: typeof rawOrderNumber === "string" && rawOrderNumber.length > 0 ? rawOrderNumber : null,
		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,
		shipping_address: mapAddress(raw.shipping_address ?? null),
		billing_address: mapAddress(raw.billing_address ?? null),
		payment_method: mapPaymentMethod(raw.payment_method),
		shipping_method: mapShippingMethod(raw.shipping_method),
		subscription_order: raw.subscription_order ?? false,
		subscription_token: raw.subscription_token ?? null,
		tracking_informations: mapTrackingInformations(raw.tracking_informations),
		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,
		points_applied: typeof raw.points_applied === "number" ? raw.points_applied : void 0,
		points_applied_amount: typeof raw.points_applied_amount === "number" ? raw.points_applied_amount : void 0,
		points_applied_amount_in_currency: typeof raw.points_applied_amount_in_currency === "string" ? raw.points_applied_amount_in_currency : null,
		order_total_after_points_redemption: typeof raw.order_total_after_points_redemption === "number" ? raw.order_total_after_points_redemption : void 0,
		order_total_after_points_redemption_in_currency: typeof raw.order_total_after_points_redemption_in_currency === "string" ? raw.order_total_after_points_redemption_in_currency : null,
		created_at: raw.created_at ?? "",
		updated_at: raw.updated_at ?? ""
	};
}
function mapToListOrder(raw) {
	const firstLineItem = raw.line_items?.[0];
	const rawOrderNumber = raw.order_number;
	const orderNumber = typeof rawOrderNumber === "string" ? rawOrderNumber : "";
	return {
		id: raw.id ?? 0,
		external_id: null,
		order_number: orderNumber,
		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: (typeof raw.fulfillment_status === "string" ? raw.fulfillment_status : null) ?? "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: raw.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-api-context.ts
const { Provider: OrdersProvider, useTranslation } = createTranslationContext("Orders");
const OrdersTranslationProvider = OrdersProvider;
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 STATUS_LOOKUP = {
	fulfilled: {
		kind: "fulfilled",
		labelKey: "status_fulfilled"
	},
	completed: {
		kind: "fulfilled",
		labelKey: "status_fulfilled"
	},
	partially_fulfilled: {
		kind: "preparing",
		labelKey: "status_preparing"
	},
	in_progress: {
		kind: "preparing",
		labelKey: "status_preparing"
	},
	on_hold: {
		kind: "preparing",
		labelKey: "status_preparing"
	},
	scheduled: {
		kind: "preparing",
		labelKey: "status_preparing"
	},
	preparing: {
		kind: "preparing",
		labelKey: "status_preparing"
	},
	shipped: {
		kind: "shipped",
		labelKey: "status_shipped"
	},
	cancelled: { kind: "cancelled" },
	returned: { kind: "cancelled" },
	refunded: { kind: "cancelled" },
	pending: {
		kind: "pending",
		labelKey: "status_processing"
	},
	unfulfilled: {
		kind: "pending",
		labelKey: "status_processing"
	},
	processing: {
		kind: "pending",
		labelKey: "status_processing"
	}
};
/**
* Map a raw status string (typically `fulfillment_status`) from the BFF
* onto our internal status vocabulary (`StatusKind`). Aliases are folded
* together (`unfulfilled` → `pending`, `in_progress`/`scheduled` →
* `preparing`, 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 = {
	fulfilled: {
		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-muted",
		text: "text-muted-foreground",
		dot: "bg-muted-foreground"
	},
	cancelled: {
		bg: "bg-destructive/10",
		text: "text-destructive",
		dot: "bg-destructive"
	}
};
const CANCELLED_FAMILY = new Set([
	"cancelled",
	"returned",
	"refunded"
]);
/**
* Pick the right status string to drive the pill / filter for a list order.
* Cancelled-family lifecycle states come from `order_status`; everything
* else is read off `fulfillment_status` (the BFF source-of-truth per the
* `Commerce::Order#fulfillment_status` enum).
*/
function statusForOrder(order) {
	if (CANCELLED_FAMILY.has(order.order_status)) return order.order_status;
	return order.fulfillment_status ?? order.order_status;
}
function filterPredicate(filter, order) {
	if (filter === "all") return true;
	if (filter === "subscription") return order.subscription != null;
	const status = mapStatus(statusForOrder(order), identity).kind;
	if (filter === "fulfilled") return status === "fulfilled" || status === "shipped";
	if (filter === "preparing") return status === "preparing" || status === "pending";
	return true;
}
const identity = ((k) => k);
function countByFilter(list) {
	return {
		all: list.length,
		fulfilled: list.filter((o) => filterPredicate("fulfilled", o)).length,
		preparing: list.filter((o) => filterPredicate("preparing", o)).length,
		subscription: list.filter((o) => filterPredicate("subscription", o)).length
	};
}
/**
* The date to show reps in the order history list. Prefers `sale_date`
* (when the sale actually happened — meaningful for historical orders
* imported via sync, where `created_at` is just when the row landed in
* Fluid) and falls back to `created_at` for orders placed natively.
*/
function orderDisplayDate(order) {
	return order.sale_date ?? order.created_at;
}
/**
* 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.
*
* Buckets reps by `orderDisplayDate` — sale_date when set, created_at
* otherwise — so historical imported orders land in their real-life
* month instead of the day they were synced into Fluid.
*/
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 bucketDate = new Date(orderDisplayDate(o));
		let label;
		if (bucketDate >= sevenDaysAgo) label = t("group_this_week");
		else if (bucketDate >= startOfMonth) label = t("group_this_month");
		else if (bucketDate >= startOfYear) label = bucketDate.toLocaleDateString(void 0, { month: "long" });
		else label = bucketDate.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 by the i18n system. 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("today");
		if (diffDays === 1) return t("yesterday");
		if (diffDays < 7) return t("n_days_ago", { n: diffDays });
		if (diffDays < 14) return t("last_week");
		if (diffDays < 30) return t("n_weeks_ago", { n: 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
function PortalOrdersList({ customerId, onOrderClick, t: tProp }) {
	const { t: tContext } = useOrdersTranslation();
	const t = tProp ?? tContext;
	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("order_history")
		}) })
	}) }) }), /* @__PURE__ */ jsx("div", {
		className: "relative",
		children: /* @__PURE__ */ jsxs("div", {
			className: "relative mx-auto max-w-4xl 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-foreground flex-1 truncate text-xl font-bold tracking-tight md:text-2xl",
						children: t("order_history")
					}), /* @__PURE__ */ jsxs("div", {
						className: "relative hidden sm:block",
						children: [/* @__PURE__ */ jsx(Search, {
							className: "text-muted-foreground 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("search_orders"),
							className: "ring-border h-9 w-64 rounded-md bg-transparent pl-9 text-xs"
						})]
					})]
				}),
				list.length > 0 && /* @__PURE__ */ jsx(FilterPills, {
					active: filter,
					counts,
					onChange: setFilter,
					t
				}),
				isLoading ? /* @__PURE__ */ jsx("div", {
					className: "ring-border mt-4 overflow-hidden rounded-2xl bg-transparent ring-1",
					children: /* @__PURE__ */ jsx(OrdersListSkeleton, {})
				}) : isError ? /* @__PURE__ */ jsx("div", {
					className: "ring-border mt-4 overflow-hidden rounded-2xl bg-transparent ring-1",
					children: /* @__PURE__ */ jsx(ErrorState, {
						onRetry: () => refetch(),
						t
					})
				}) : filteredList.length === 0 ? /* @__PURE__ */ jsx("div", {
					className: "ring-border mt-4 overflow-hidden rounded-2xl bg-transparent 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-muted-foreground mb-2 px-1 text-xs 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-border text-foreground hover:bg-muted inline-flex items-center gap-1 rounded-md bg-transparent px-3 py-1.5 text-xs font-bold ring-1 transition-all disabled:cursor-not-allowed disabled:opacity-40",
						children: isFetchingNextPage ? t("loading") : t("load_more")
					})
				})
			]
		})
	})] });
}
const FILTER_KEYS = [
	{
		key: "all",
		labelKey: "filter_all"
	},
	{
		key: "fulfilled",
		labelKey: "filter_fulfilled"
	},
	{
		key: "preparing",
		labelKey: "filter_preparing"
	},
	{
		key: "subscription",
		labelKey: "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: `inline-flex items-center gap-1.5 rounded-md px-3 py-1.5 text-xs font-bold transition-all ${isActive ? "bg-primary text-primary-foreground" : "ring-border text-foreground hover:bg-muted bg-transparent ring-1"}`,
				children: [t(f.labelKey), /* @__PURE__ */ jsx("span", {
					className: `text-xs tabular-nums ${isActive ? "text-primary-foreground/70" : "text-muted-foreground"}`,
					children: count
				})]
			}, f.key);
		})
	});
}
function OrderRow({ order, onClick, t }) {
	const status = mapStatus(statusForOrder(order), t);
	const dateLabel = formatFriendlyDate(orderDisplayDate(order), t);
	const total = formatOrderTotal(order);
	const titleText = order.first_item?.title || `${t("order_number")}${order.order_number}`;
	const titleSuffix = order.items_count > 1 ? t("more_items", { n: order.items_count - 1 }) : "";
	return /* @__PURE__ */ jsxs("button", {
		type: "button",
		onClick,
		className: "group ring-foreground/5 hover:ring-foreground/10 focus-visible:ring-foreground/30 relative flex w-full cursor-pointer items-center gap-4 rounded-2xl bg-transparent p-4 text-left shadow-sm ring-1 transition-all duration-300 hover:-translate-y-0.5 hover:shadow-lg focus-visible:ring-2 focus-visible:outline-none",
		children: [/* @__PURE__ */ jsxs("div", {
			className: "min-w-0 flex-1",
			children: [
				order.order_number && order.first_item?.title && /* @__PURE__ */ jsxs("div", {
					className: "text-muted-foreground truncate text-xs",
					children: [t("order_number"), order.order_number]
				}),
				/* @__PURE__ */ jsxs("div", {
					className: "flex items-center gap-2",
					children: [/* @__PURE__ */ jsxs("div", {
						className: "text-foreground truncate text-sm font-bold",
						children: [titleText, titleSuffix && /* @__PURE__ */ jsx("span", {
							className: "text-muted-foreground font-medium",
							children: titleSuffix
						})]
					}), /* @__PURE__ */ jsx(StatusPill, { status })]
				}),
				/* @__PURE__ */ jsxs("div", {
					className: "text-muted-foreground mt-1 truncate text-xs",
					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-border bg-muted text-muted-foreground 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: "ring-background size-12 rounded-xl bg-transparent 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: "ring-background absolute top-0 size-12 rounded-xl bg-transparent 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-primary text-primary-foreground ring-background absolute -top-1 -right-1 z-40 flex size-5 items-center justify-center rounded-full ring-2",
		title: t("from_subscription"),
		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: `inline-flex shrink-0 items-center gap-1 rounded-md px-2 py-0.5 text-xs 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-border border-b" : ""}`,
		children: [/* @__PURE__ */ jsx("div", { className: "bg-muted size-12 shrink-0 animate-pulse rounded-xl" }), /* @__PURE__ */ jsxs("div", {
			className: "flex-1 space-y-2",
			children: [/* @__PURE__ */ jsx("div", { className: "bg-muted h-4 w-1/3 animate-pulse rounded" }), /* @__PURE__ */ jsx("div", { className: "bg-muted 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-muted flex size-12 items-center justify-center rounded-full",
				children: /* @__PURE__ */ jsx(Search, {
					className: "text-muted-foreground size-5",
					strokeWidth: 2
				})
			}),
			/* @__PURE__ */ jsx("div", {
				className: "text-foreground text-sm font-bold",
				children: searching ? t("no_matching_orders") : t("no_orders_yet")
			}),
			/* @__PURE__ */ jsx("div", {
				className: "text-muted-foreground max-w-sm text-xs",
				children: searching ? t("search_hint") : t("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-muted flex size-12 items-center justify-center rounded-full",
				children: /* @__PURE__ */ jsx(AlertCircle, {
					className: "text-muted-foreground size-5",
					strokeWidth: 2
				})
			}),
			/* @__PURE__ */ jsx("div", {
				className: "text-foreground text-sm font-bold",
				children: t("load_failed_title")
			}),
			/* @__PURE__ */ jsx("div", {
				className: "text-muted-foreground max-w-sm text-xs",
				children: t("load_failed_hint")
			}),
			/* @__PURE__ */ jsx("button", {
				type: "button",
				onClick: onRetry,
				className: "bg-primary text-primary-foreground hover:bg-primary/90 mt-2 inline-flex items-center gap-1 rounded-md px-3 py-1.5 text-xs font-bold transition-all",
				children: t("try_again")
			})
		]
	});
}
//#endregion
//#region src/screens/OrdersListScreen.tsx
const BFF_SCOPED_CUSTOMER_ID = 1;
function OrdersListScreen() {
	const { navigate } = useAppNavigation();
	const { t } = useOrdersTranslation();
	const handleOrderClick = (order) => {
		navigate(`orders/${order.token}`);
	};
	return /* @__PURE__ */ jsx(PortalOrdersList, {
		customerId: BFF_SCOPED_CUSTOMER_ID,
		onOrderClick: handleOrderClick,
		t
	});
}
//#endregion
//#region ../../payments/display/src/components/MaskedPaymentLabel.tsx
const labelStyle = {
	display: "inline-flex",
	minHeight: "1.5rem",
	alignItems: "center",
	fontSize: "0.875rem",
	lineHeight: 1,
	overflowWrap: "anywhere"
};
const segmentsStyle = {
	display: "inline-flex",
	alignItems: "center",
	flexWrap: "wrap",
	rowGap: "0.25rem"
};
const dotsStyle = {
	display: "inline-flex",
	alignItems: "center",
	gap: "0.375rem",
	flexWrap: "wrap"
};
const dotStyle = {
	display: "block",
	width: "0.375rem",
	height: "0.375rem",
	borderRadius: "9999px",
	backgroundColor: "currentColor"
};
const textAfterDotsStyle = { marginLeft: "0.125rem" };
const GROUP_GAP = "0.75rem";
function MaskedPaymentLabel({ label, className }) {
	const segments = maskedCardLabelSegments(label);
	if (!segments) return /* @__PURE__ */ jsx("p", {
		className,
		style: labelStyle,
		children: label
	});
	return /* @__PURE__ */ jsx("p", {
		className,
		style: labelStyle,
		"aria-label": label,
		children: /* @__PURE__ */ jsx("span", {
			"aria-hidden": "true",
			style: segmentsStyle,
			children: segments.map((segment, index) => {
				if (segment.kind === "gap") return null;
				const trailingGap = segments[index + 1]?.kind === "gap" ? { marginInlineEnd: GROUP_GAP } : null;
				if (segment.kind === "dots") return /* @__PURE__ */ jsx("span", {
					style: {
						...dotsStyle,
						...trailingGap
					},
					children: Array.from({ length: segment.count }, (_, dotIndex) => /* @__PURE__ */ jsx("span", { style: dotStyle }, dotIndex))
				}, `${segment.kind}-${index}`);
				const textStyle = {
					...segments[index - 1]?.kind === "dots" ? textAfterDotsStyle : null,
					...trailingGap
				};
				return /* @__PURE__ */ jsx("span", {
					style: Object.keys(textStyle).length > 0 ? textStyle : void 0,
					children: segment.value
				}, `${segment.kind}-${index}`);
			})
		})
	});
}
//#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/lib/translate-status.ts
/** Status values that have a `status_*` translation key in the orders dictionary. */
const translatableStatuses = new Set([
	"cancelled",
	"completed",
	"fulfilled",
	"pending",
	"preparing",
	"processing",
	"returned",
	"shipped"
]);
/**
* Translate an order status using the orders `t()` function.
* Falls back to `startCase` for statuses without a dedicated translation key.
*/
function translateStatus(t, status) {
	if (translatableStatuses.has(status)) return t(`status_${status}`);
	return startCase(status);
}
//#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 }) {
	const { t } = useOrdersTranslation();
	return /* @__PURE__ */ jsx(StatusBadge, {
		color: statusColorMap[status] ?? "gray",
		dot: true,
		size: "sm",
		className,
		children: translateStatus(t, status)
	});
}
//#endregion
//#region ../../orders/ui/src/components/static-map.tsx
function StaticMap({ apiKey, address, options, alt, className }) {
	const { t } = useOrdersTranslation();
	const [errored, setErrored] = useState(false);
	const url = buildStaticMapUrl(apiKey, address, options);
	if (!url || errored) return null;
	return /* @__PURE__ */ jsx("img", {
		src: url,
		alt: alt ?? t("shipping_address_map"),
		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/lib/effective-order-date.ts
function effectiveOrderDate(order) {
	return order.sale_date ?? order.created_at;
}
//#endregion
//#region ../../orders/ui/src/components/portal-order-detail.tsx
/** Capitalize the first letter for display in headings / sentence-leading copy. */
const capitalize = (value) => value.charAt(0).toUpperCase() + value.slice(1);
function isCardPaymentMethod(paymentMethod) {
	return paymentMethod.last4 != null || normalizePaymentDescriptor(paymentMethod.card_network) != null || normalizeCardBrand(paymentMethod.card_network) != null || isCardPaymentDescriptor(paymentMethod.source) || isCardPaymentDescriptor(paymentMethod.payment_type);
}
function fallbackPaymentLabel(paymentMethod) {
	return paymentDescriptorLabel(paymentMethod.payment_type, paymentMethod.source) ?? "Payment method";
}
function resolvePortalPaymentMethodDisplay(paymentMethod) {
	if (isCardPaymentMethod(paymentMethod)) return resolvePaymentMethodDisplay({
		kind: "card",
		brand: normalizeCardBrand(paymentMethod.card_network),
		last4: paymentMethod.last4,
		logoUrl: paymentMethod.logo_url
	});
	const fallbackLabel = fallbackPaymentLabel(paymentMethod);
	return resolvePaymentMethodDisplay({
		kind: "non_card",
		brand: fallbackLabel,
		fallbackLabel,
		logoUrl: paymentMethod.logo_url
	});
}
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 gap-x-4",
							children: [/* @__PURE__ */ jsx(Skeleton, { className: "size-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);
	if (address.phone) lines.push(address.phone);
	return lines;
}
function AddressBlock({ address, title }) {
	const lines = formatAddressLines(address);
	if (lines.length === 0) return null;
	return /* @__PURE__ */ jsxs("div", { children: [/* @__PURE__ */ jsx("h3", {
		className: "text-foreground mb-3 text-sm/6 font-semibold",
		children: title
	}), /* @__PURE__ */ jsx("div", {
		className: "text-foreground space-y-0.5 text-sm",
		children: lines.map((line, index) => /* @__PURE__ */ jsx("p", { children: line }, index))
	})] });
}
function ShippingMethodSection({ shippingMethod }) {
	const { t } = useOrdersTranslation();
	if (!shippingMethod.title) return null;
	return /* @__PURE__ */ jsxs("div", { children: [/* @__PURE__ */ jsx("h3", {
		className: "text-foreground mb-3 text-sm/6 font-semibold",
		children: t("shipping_method")
	}), /* @__PURE__ */ jsx("p", {
		className: "text-foreground text-sm",
		children: shippingMethod.title
	})] });
}
function TrackingShipmentsSection({ trackings }) {
	const { t } = useOrdersTranslation();
	if (trackings.length === 0) return null;
	return /* @__PURE__ */ jsxs("div", {
		className: "border-border bg-muted/40 mb-6 rounded-md border p-4",
		children: [/* @__PURE__ */ jsx("h3", {
			className: "text-foreground mb-3 text-sm/6 font-semibold",
			children: t("order_on_its_way")
		}), /* @__PURE__ */ jsx("ul", {
			className: "flex flex-col gap-3",
			children: trackings.map((tracking) => /* @__PURE__ */ jsxs("li", {
				className: "flex flex-row items-start justify-between gap-3",
				children: [/* @__PURE__ */ jsxs("div", {
					className: "flex flex-col",
					children: [/* @__PURE__ */ jsx("span", {
						className: "text-foreground text-sm",
						children: tracking.shipping_carrier ? `${tracking.shipping_carrier} · ${tracking.tracking_number}` : tracking.tracking_number
					}), !tracking.shipping_carrier && /* @__PURE__ */ jsx("span", {
						className: "text-muted-foreground text-xs",
						children: t("tracking_number")
					})]
				}), tracking.tracking_url && /* @__PURE__ */ jsx("a", {
					href: tracking.tracking_url,
					target: "_blank",
					rel: "noopener noreferrer",
					"aria-label": tracking.shipping_carrier ? t("track_package_aria_with_carrier", {
						carrier: tracking.shipping_carrier,
						number: tracking.tracking_number
					}) : t("track_package_aria", { number: tracking.tracking_number }),
					className: "text-primary shrink-0 text-sm font-medium hover:underline",
					children: t("track_package")
				})]
			}, `${tracking.id}-${tracking.tracking_number}`))
		})]
	});
}
function PaymentMethodSection({ paymentMethod }) {
	const { t } = useOrdersTranslation();
	const [logoErrored, setLogoErrored] = useState(false);
	const display = resolvePortalPaymentMethodDisplay(paymentMethod);
	const logoUrl = logoErrored ? display.logo.fallbackUrl : display.logo.primaryUrl;
	useEffect(() => {
		setLogoErrored(false);
	}, [
		paymentMethod.card_network,
		paymentMethod.last4,
		paymentMethod.logo_url,
		paymentMethod.payment_type,
		paymentMethod.source
	]);
	return /* @__PURE__ */ jsxs("div", { children: [/* @__PURE__ */ jsx("h3", {
		className: "text-foreground mb-3 text-sm/6 font-semibold",
		children: t("payment_method")
	}), /* @__PURE__ */ jsxs("div", {
		className: "flex min-h-6 items-center gap-2",
		children: [/* @__PURE__ */ jsx("span", {
			className: "inline-flex h-6 max-w-16 shrink-0 items-center justify-center",
			children: /* @__PURE__ */ jsx("img", {
				src: logoUrl,
				alt: display.accessibilityLabel,
				className: "block max-h-6 max-w-16 object-contain align-middle",
				onError: () => setLogoErrored(true)
			})
		}), /* @__PURE__ */ jsx(MaskedPaymentLabel, {
			label: display.label,
			className: "text-foreground"
		})]
	})] });
}
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 gap-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 gap-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();
	const { plural } = usePointsLabel();
	const totalValue = order.points_applied != null && order.points_applied > 0 ? moneyDisplay(order.order_total_after_points_redemption_in_currency ?? null, order.order_total_after_points_redemption != null ? String(order.order_total_after_points_redemption) : moneyDisplay(order.total_in_currency, order.total)) : moneyDisplay(order.total_in_currency, order.total);
	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)
						}),
						order.points_applied != null && order.points_applied > 0 && /* @__PURE__ */ jsxs("div", {
							className: "flex items-center justify-between text-sm",
							children: [/* @__PURE__ */ jsxs("p", {
								className: "text-muted-foreground",
								children: [t("points_applied"), /* @__PURE__ */ jsxs("span", {
									className: "ml-1 text-xs",
									children: [
										"(",
										order.points_applied.toLocaleString(),
										" ",
										order.points_applied === 1 ? t("points_applied_singular") : t("points_applied_plural"),
										")"
									]
								})]
							}), /* @__PURE__ */ jsx("p", {
								className: "text-foreground",
								children: asNegative(moneyDisplay(order.points_applied_amount_in_currency ?? null, String(order.points_applied_amount ?? 0)))
							})]
						}),
						/* @__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: totalValue
							})]
						})
					]
				}),
				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", { label: capitalize(plural) })
						}), order.customer_points_balance != null && /* @__PURE__ */ jsx("p", {
							className: "text-muted-foreground text-xs",
							children: t("points_total", {
								count: order.customer_points_balance.toLocaleString(),
								label: plural
							})
						})] }), /* @__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", { label: plural })
							})]
						})]
					})
				})
			]
		})
	});
}
function DetailsSection({ order, googleMapsApiKey }) {
	const { t, locale } = 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.shipping_address && /* @__PURE__ */ jsx("div", {
					className: "mb-6",
					children: /* @__PURE__ */ jsx(StaticMap, {
						apiKey: googleMapsApiKey,
						address: order.shipping_address
					})
				}),
				/* @__PURE__ */ jsx(TrackingShipmentsSection, { trackings: order.tracking_informations }),
				/* @__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.order_number ?? 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(effectiveOrderDate(order)).toLocaleDateString(locale, {
										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.shipping_address && order.billing_address ? /* @__PURE__ */ jsxs("div", {
					className: "border-border mb-6 grid grid-cols-2 gap-x-4 border-b pb-6",
					children: [/* @__PURE__ */ jsx(AddressBlock, {
						address: order.shipping_address,
						title: t("shipping_address")
					}), /* @__PURE__ */ jsx(AddressBlock, {
						address: order.billing_address,
						title: t("billing_address")
					})]
				}) : order.shipping_address && /* @__PURE__ */ jsx("div", {
					className: "border-border mb-6 border-b pb-6",
					children: /* @__PURE__ */ jsx(AddressBlock, {
						address: order.shipping_address,
						title: t("shipping_address")
					})
				}),
				(order.shipping_method || order.payment_method) && /* @__PURE__ */ jsxs("div", {
					className: "border-border mb-6 grid grid-cols-1 gap-x-4 gap-y-4 border-b pb-6 sm:grid-cols-2",
					children: [order.shipping_method && /* @__PURE__ */ jsx(ShippingMethodSection, { shippingMethod: order.shipping_method }), 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();
	const { data } = usePortalTenantOrder(id);
	const breadcrumbLabel = data?.order.order_number ?? data?.order.id.toString() ?? String(id);
	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: breadcrumbLabel })
			}) })
		]
	}) }) }), /* @__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-K8jpRA_z.mjs.map