require("./chunk-9hOWP6kD.cjs");
const require_portal_tenant = require("./portal_tenant-DG4gKXnu.cjs");
const require_PortalTenantClientProvider = require("./PortalTenantClientProvider-CVv-4rQ9.cjs");
const require_src = require("./src-B0ut9PTw.cjs");
let react = require("react");
let _tanstack_react_query = require("@tanstack/react-query");
let react_jsx_runtime = require("react/jsx-runtime");
let lucide_react = require("lucide-react");
let zustand = require("zustand");
let zustand_middleware = require("zustand/middleware");
//#region ../../platform/ui-components/src/components/SearchSort.tsx
function SearchSort({ searchValue, onSearchChange, placeholder = "Search...", sortOptions, sortValue, onSortChange }) {
	const activeSort = sortOptions?.find((o) => o.value === sortValue);
	return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
		className: "flex items-center gap-2",
		children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
			className: "relative min-w-0 flex-1",
			children: [
				/* @__PURE__ */ (0, react_jsx_runtime.jsx)(lucide_react.Search, { className: "text-muted-foreground pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2" }),
				/* @__PURE__ */ (0, react_jsx_runtime.jsx)(require_src.Input, {
					type: "search",
					value: searchValue,
					onChange: (e) => onSearchChange(e.target.value),
					placeholder,
					className: "pl-9 [&::-webkit-search-cancel-button]:hidden"
				}),
				searchValue.length > 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(require_src.Button, {
					variant: "ghost",
					size: "icon-xs",
					onClick: () => onSearchChange(""),
					"aria-label": "Clear search",
					className: "absolute top-1/2 right-2 -translate-y-1/2",
					children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(lucide_react.X, { className: "size-3" })
				})
			]
		}), sortOptions && sortOptions.length > 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(require_src.DropdownMenu, { children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(require_src.DropdownMenuTrigger, {
			asChild: true,
			children: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(require_src.Button, {
				variant: "outline",
				"aria-label": activeSort ? `Sort: ${activeSort.label}` : "Sort options",
				children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(lucide_react.ArrowUpDown, { className: "size-4" }), activeSort && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
					className: "hidden sm:inline",
					children: activeSort.label
				})]
			})
		}), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(require_src.DropdownMenuContent, {
			align: "end",
			children: sortOptions.map((option) => {
				const isActive = option.value === sortValue;
				return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(require_src.DropdownMenuItem, {
					onClick: () => onSortChange(option.value),
					children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
						className: "flex-1",
						children: option.label
					}), isActive && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(lucide_react.Check, { className: "text-muted-foreground size-4" })]
				}, option.value);
			})
		})] })]
	});
}
(0, react.createContext)(null);
//#endregion
//#region ../../products/core/src/portal-products-api-context.tsx
const PortalProductsCoreContext = (0, react.createContext)(null);
function PortalProductsCoreProvider({ api, children }) {
	return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(PortalProductsCoreContext.Provider, {
		value: { api },
		children
	});
}
function usePortalProductsApi() {
	const ctx = (0, react.useContext)(PortalProductsCoreContext);
	if (!ctx) throw new Error("usePortalProductsApi must be used within a <PortalProductsCoreProvider>");
	return ctx.api;
}
//#endregion
//#region ../../products/core/src/hooks/use-debounce.ts
function useDebounce(value, delay) {
	const [debouncedValue, setDebouncedValue] = (0, react.useState)(value);
	(0, react.useEffect)(() => {
		const timer = setTimeout(() => {
			setDebouncedValue(value);
		}, delay);
		return () => {
			clearTimeout(timer);
		};
	}, [value, delay]);
	return debouncedValue;
}
//#endregion
//#region ../../products/core/src/hooks/use-portal-products.ts
const portalProductKeys = {
	all: ["portal-products"],
	list: (params) => [
		...portalProductKeys.all,
		"list",
		params
	],
	detail: (id) => [
		...portalProductKeys.all,
		"detail",
		String(id)
	],
	search: (query, params) => [
		...portalProductKeys.all,
		"search",
		query,
		params
	],
	media: (productId) => [
		...portalProductKeys.all,
		"media",
		String(productId)
	]
};
function usePortalProduct(id, options) {
	const api = usePortalProductsApi();
	return (0, _tanstack_react_query.useQuery)({
		queryKey: portalProductKeys.detail(id),
		queryFn: () => api.getProduct(id),
		enabled: options?.enabled
	});
}
//#endregion
//#region ../../products/core/src/hooks/use-portal-product-catalog.ts
function usePortalProductCatalog({ perPage = 25 } = {}) {
	const api = usePortalProductsApi();
	const [searchTerm, setSearchTerm] = (0, react.useState)("");
	const debouncedSearchTerm = useDebounce(searchTerm, 300);
	const [currentSort, setCurrentSort] = (0, react.useState)("created_at_desc");
	return {
		searchTerm,
		setSearchTerm,
		debouncedSearchTerm,
		currentSort,
		setCurrentSort,
		fetchProducts: (0, react.useCallback)(async (pageParam) => {
			const cursor = pageParam;
			if (debouncedSearchTerm) return api.searchProducts(debouncedSearchTerm, {
				cursor,
				limit: perPage,
				sort: currentSort
			});
			return api.listProducts({
				cursor,
				limit: perPage,
				sort: currentSort
			});
		}, [
			api,
			debouncedSearchTerm,
			perPage,
			currentSort
		]),
		getNextPageParam: (0, react.useCallback)((lastPage, _allPages, lastPageParam) => {
			const nextCursor = lastPage.meta?.pagination?.next_cursor ?? void 0;
			if (nextCursor != null && nextCursor === lastPageParam) return;
			return nextCursor;
		}, []),
		queryKey: (0, react.useMemo)(() => [
			"portal-product-catalog",
			debouncedSearchTerm || "",
			perPage,
			currentSort
		], [
			debouncedSearchTerm,
			perPage,
			currentSort
		]),
		perPage
	};
}
//#endregion
//#region ../../products/core/src/hooks/use-portal-product-detail.ts
function usePortalProductDetail({ productId }) {
	const { data: productResponse, isLoading, error } = usePortalProduct(productId);
	const product = productResponse?.product;
	return {
		product,
		isLoading,
		error,
		images: (0, react.useMemo)(() => {
			if (!product?.images) return [];
			return product.images.map((img, idx) => ({
				id: idx,
				url: img.url ?? "",
				alt: img.alt ?? null
			}));
		}, [product?.images])
	};
}
//#endregion
//#region ../../products/core/src/utils/subscription-plans.ts
function ensureDefaultSubscriptionPlan(plans) {
	const activePlans = plans.filter((plan) => plan.active !== false);
	if (activePlans.length === 0) return plans.map((plan) => ({
		...plan,
		default: false
	}));
	if (!activePlans.some((plan) => plan.default === true)) {
		const planWithLowestId = activePlans.reduce((lowest, current) => {
			const lowestId = lowest.subscription_plan?.id || Infinity;
			return (current.subscription_plan?.id || Infinity) < lowestId ? current : lowest;
		});
		return plans.map((plan) => ({
			...plan,
			default: plan.subscription_plan?.id === planWithLowestId.subscription_plan?.id && plan.active !== false
		}));
	}
	return plans.map((plan) => ({
		...plan,
		default: plan.active !== false ? plan.default : false
	}));
}
function plansToAttributes(plans) {
	return plans.map((plan) => ({
		id: plan.id ?? void 0,
		subscription_plan_id: plan.subscription_plan.id,
		default: plan.default || false,
		active: plan.active !== false
	}));
}
//#endregion
//#region ../../products/core/src/stores/use-product-store.ts
const defaultState = {
	id: void 0,
	title: "",
	description: "",
	introduction: "",
	stripped: "",
	feature_text: "",
	sku: "",
	slug: "",
	canonical_url: null,
	image_url: "",
	image_path: void 0,
	status: "draft",
	publish_at: null,
	price: "0",
	commission: 0,
	public: true,
	no_index: false,
	show_reviews: true,
	publish_to_retail_store: true,
	publish_to_rep_store: true,
	publish_to_share_tab: true,
	collection_ids: [],
	tag_ids: [],
	images_attributes: [],
	product_subscription_plans_attributes: [],
	product_subscription_plans: [],
	variants_attributes: [],
	bundle: false,
	track_inventory_on_bundle_items: false,
	product_bundles_attributes: [],
	option_attrs: [],
	options: [],
	metafields_attributes: [],
	metadata: {},
	search_engine_optimizer_attributes: {
		title: "",
		description: "",
		image_url: "",
		image_path: "",
		block_crawler: false
	}
};
function syncSubscriptionPlans(plans) {
	const plansWithDefault = plans.filter((plan) => plan.active !== false).length > 0 ? ensureDefaultSubscriptionPlan(plans) : plans;
	return {
		product_subscription_plans: plansWithDefault,
		product_subscription_plans_attributes: plansToAttributes(plansWithDefault)
	};
}
const extractFilenameFromUrl = (imageUrl) => {
	try {
		return new URL(imageUrl).pathname.split("/").pop() || "";
	} catch {
		return imageUrl.split("/").pop()?.split("?")[0] || "";
	}
};
const createProductStore = (set, get) => ({
	...defaultState,
	track_inventory_on_bundle_items: false,
	translations: {},
	editedTranslations: {},
	translationErrors: {},
	translationLoading: {},
	translationsFetched: false,
	errors: {},
	isValid: false,
	isDirty: false,
	setProduct: (productData) => {
		set({
			id: productData.id || void 0,
			title: productData.title || "",
			description: productData.description || "",
			introduction: productData.introduction || "",
			stripped: productData.stripped || "",
			feature_text: productData.feature_text || "",
			sku: productData.sku || "",
			slug: productData.slug || "",
			canonical_url: productData.canonical_url || null,
			custom_slug: productData.custom_slug || false,
			image_url: productData.image_url || "",
			image_path: productData.image_path && !productData.image_path.includes("undefined") ? productData.image_path : productData.image_url ? extractFilenameFromUrl(productData.image_url) : void 0,
			status: productData.status || "draft",
			publish_at: productData.publish_at || null,
			commission: typeof productData.commission === "string" ? parseFloat(productData.commission) : productData.commission || 0,
			public: productData.public ?? true,
			no_index: productData.no_index ?? false,
			show_reviews: productData.show_reviews ?? true,
			publish_to_retail_store: productData.publish_to_retail_store,
			publish_to_rep_store: productData.publish_to_rep_store,
			publish_to_share_tab: productData.publish_to_share_tab,
			...productData.tax_category_id && { tax_category_id: productData.tax_category_id },
			international_tax_type: productData.international_tax_type || void 0,
			category_id: productData.category_id ? parseInt(productData.category_id) : productData.category?.id ? productData.category.id : void 0,
			application_theme_template_id: productData.application_theme_template_id || void 0,
			collection_ids: productData.collections?.map((collection) => collection.id),
			tag_ids: Array.isArray(productData.tags) ? productData.tags.map((tag) => typeof tag === "number" ? tag : tag?.id).filter(Boolean) : [],
			search_engine_optimizer_attributes: {
				id: productData.search_engine_optimizer?.id,
				title: productData.search_engine_optimizer?.title || productData.title || void 0,
				description: productData.search_engine_optimizer?.description || "",
				image_url: productData.search_engine_optimizer?.image_url || productData.image_url || "",
				image_path: productData.search_engine_optimizer?.image_path || productData.image_path || "",
				block_crawler: productData.search_engine_optimizer?.block_crawler ?? false
			},
			images_attributes: productData.images?.map((img) => ({
				id: img.id,
				position: img.position || 0,
				image_url: img.image_url,
				image_path: img.image_path && !img.image_path.includes("undefined") ? img.image_path : img.image_url ? extractFilenameFromUrl(img.image_url) : void 0,
				_destroy: false
			})) || [],
			...productData.images && productData.images.length > 0 && { image_path: (() => {
				if (productData.image_path && typeof productData.image_path === "string" && !productData.image_path.includes("undefined")) return productData.image_path;
				const firstImage = productData.images.find((img) => img.position === 0);
				if (firstImage?.image_path && typeof firstImage.image_path === "string" && !firstImage.image_path.includes("undefined")) return firstImage.image_path;
				return productData.image_url ? extractFilenameFromUrl(productData.image_url) : void 0;
			})() },
			product_subscription_plans: (() => {
				const plans = productData?.product_subscription_plans?.map((plan) => ({
					...plan,
					active: plan?.active
				})) || [];
				return plans.length > 0 ? ensureDefaultSubscriptionPlan(plans) : plans;
			})(),
			product_subscription_plans_attributes: (() => {
				const plans = productData?.product_subscription_plans?.map((plan) => ({
					...plan,
					active: plan?.active
				})) || [];
				return plansToAttributes(plans.length > 0 ? ensureDefaultSubscriptionPlan(plans) : plans);
			})(),
			variants_attributes: productData?.variants?.filter((variant) => variant.id !== null && variant.id !== void 0).map((variant) => ({
				id: variant.id,
				title: variant.title ?? productData?.title ?? "Untitled Variant",
				option_attrs: variant.option_attrs || [],
				sku: variant.sku || void 0,
				price: variant.price,
				track_quantity: variant.track_quantity ?? false,
				keep_selling: variant.keep_selling ?? false,
				bar_code: variant.bar_code ?? "",
				limit_subscription: variant.limit_subscription,
				subscription_max_qty: variant.subscription_max_qty ?? 0,
				customer_limit: variant.customer_limit ?? 0,
				is_master: variant.is_master,
				_destroy: false,
				images_attributes: variant?.images?.map((image) => ({
					id: image.id,
					position: image.position || 0,
					image_url: image.image_url,
					_destroy: false
				})),
				inventory_levels_attributes: variant?.inventory_levels?.filter((level) => (level.warehouse_id ?? level.warehouse?.id) != null).map((level) => ({
					id: level.id,
					available: level.available,
					committed: level.committed,
					on_hand: level.on_hand,
					unavailable: level.unavailable,
					warehouse_id: level.warehouse?.id || 0,
					_destroy: false
				})),
				variant_countries_attributes: variant?.variant_countries ? Object.entries(variant.variant_countries).map(([iso, country]) => ({
					id: country.id ?? 0,
					active: country.active ?? true,
					country_id: country.country_id,
					country_name: country.country_name ?? "",
					country_iso: iso,
					price: Number(country.price) || 0,
					subscription_price: Number(country.subscription_price) || 0,
					wholesale: Number(country.wholesale) || 0,
					wholesale_subscription_price: Number(country.wholesale_subscription_price) || 0,
					compare_price: Number(country.compare_price) || 0,
					cv: Number(country.cv) || 0,
					qv: Number(country.qv) || 0,
					pc_cv: Number(country.pc_cv) || 0,
					pc_qv: Number(country.pc_qv) || 0,
					cost_of_goods_sold: Number(country.cost_of_goods_sold) || 0,
					currency_code: country.currency_code || null,
					shipping: Number(country.shipping) || 0,
					points: country.points
				})) : []
			})),
			bundle: productData.product_bundles && productData.product_bundles.length > 0,
			track_inventory_on_bundle_items: productData.track_inventory_on_bundle_items ?? false,
			product_bundles_attributes: (productData.product_bundles || []).map((bundle) => ({
				id: bundle.id,
				bundled_variant_id: bundle.bundled_variant?.id || 0,
				bundled_variant: {
					title: bundle.bundled_variant?.title || "",
					sku: bundle.bundled_variant?.sku || null,
					price: String(bundle.bundled_variant?.price || "0"),
					price_in_currency: bundle.bundled_variant?.price_in_currency || "",
					currency_code: bundle.bundled_variant?.currency_code,
					product: {
						id: bundle.bundled_variant?.product.id || 0,
						title: bundle.bundled_variant?.product.title || "",
						image_url: bundle.bundled_variant?.product.image_url || "",
						price: bundle.bundled_variant?.product.price || "0",
						price_in_currency: bundle.bundled_variant?.product.price_in_currency || "",
						cv: bundle.bundled_variant?.product.cv || 0,
						qv: bundle.bundled_variant?.product.qv || 0
					}
				},
				cv: bundle.cv || 0,
				qv: bundle.qv || 0,
				quantity: bundle.quantity,
				display_externally: bundle.display_externally ?? true,
				_destroy: false
			})),
			option_attrs: productData.option_attrs || [],
			options: productData.options || [],
			metafields_attributes: (productData.metafields || []).map((metafield) => ({
				id: metafield.id,
				namespace: metafield.namespace,
				key: metafield.key,
				value: metafield.value,
				value_type: metafield.value_type,
				_destroy: false
			})),
			metadata: productData.metadata || {},
			errors: {},
			isValid: false,
			isDirty: false
		});
	},
	updateSlug: (slug, isManual = true) => {
		set((state) => ({
			slug,
			custom_slug: isManual,
			search_engine_optimizer_attributes: {
				...state.search_engine_optimizer_attributes,
				title: state.search_engine_optimizer_attributes?.title || "",
				description: state.search_engine_optimizer_attributes?.description || "",
				image_url: state.search_engine_optimizer_attributes?.image_url || "",
				image_path: state.search_engine_optimizer_attributes?.image_path || "",
				block_crawler: state.search_engine_optimizer_attributes?.block_crawler ?? false
			},
			isDirty: true
		}));
	},
	updateSEO: (seo) => {
		set((state) => ({
			search_engine_optimizer_attributes: {
				...state.search_engine_optimizer_attributes,
				title: seo.title !== void 0 ? seo.title : state.search_engine_optimizer_attributes?.title || "",
				description: seo.description !== void 0 ? seo.description : state.search_engine_optimizer_attributes?.description || "",
				image_url: seo.image_url !== void 0 ? seo.image_url : state.search_engine_optimizer_attributes?.image_url || "",
				image_path: seo.image_path !== void 0 ? seo.image_path : state.search_engine_optimizer_attributes?.image_path || "",
				block_crawler: seo.block_crawler !== void 0 ? seo.block_crawler : state.search_engine_optimizer_attributes?.block_crawler ?? false
			},
			isDirty: true
		}));
	},
	updateField: (key, value, options) => {
		const { shouldValidate = false, shouldClearError = true, markDirty = true } = options || {};
		set((state) => {
			if (key === "product_subscription_plans") return {
				...state,
				...syncSubscriptionPlans(value),
				errors: shouldClearError ? {
					...state.errors,
					[key]: void 0
				} : state.errors,
				isDirty: markDirty ? true : state.isDirty
			};
			return {
				...state,
				[key]: value,
				errors: shouldClearError ? {
					...state.errors,
					[key]: void 0
				} : state.errors,
				isDirty: markDirty ? true : state.isDirty
			};
		});
		if (shouldValidate) get().validateField(key);
	},
	updatePartial: (updates) => {
		set((state) => {
			if (updates.product_subscription_plans) return {
				...state,
				...updates,
				...syncSubscriptionPlans(updates.product_subscription_plans),
				errors: {
					...state.errors,
					...Object.keys(updates).reduce((acc, key) => {
						acc[key] = void 0;
						return acc;
					}, {})
				},
				isDirty: true
			};
			return {
				...state,
				...updates,
				errors: {
					...state.errors,
					...Object.keys(updates).reduce((acc, key) => {
						acc[key] = void 0;
						return acc;
					}, {})
				},
				isDirty: true
			};
		});
	},
	updateArrayItem: (arrayKey, itemId, updatedItem, idField = "id") => {
		set((state) => {
			const updatedArray = (Array.isArray(state[arrayKey]) ? state[arrayKey] : []).map((item) => {
				if (typeof item === "object" && item !== null && idField in item && item[idField] === itemId) return updatedItem;
				return item;
			});
			if (arrayKey === "product_subscription_plans") return {
				...state,
				...syncSubscriptionPlans(updatedArray),
				errors: {
					...state.errors,
					[arrayKey]: void 0
				},
				isDirty: true
			};
			return {
				...state,
				[arrayKey]: updatedArray,
				errors: {
					...state.errors,
					[arrayKey]: void 0
				},
				isDirty: true
			};
		});
	},
	reset: () => {
		set({
			...defaultState,
			track_inventory_on_bundle_items: false,
			custom_slug: false,
			errors: {},
			isValid: false,
			isDirty: false
		});
	},
	validateField: (field) => {
		const fieldValue = get()[field];
		const hasValue = fieldValue !== void 0 && fieldValue !== null && fieldValue !== "";
		set((state) => ({
			errors: {
				...state.errors,
				[field]: hasValue ? void 0 : `${field} is required`
			},
			isValid: hasValue && Object.keys(state.errors).every((key) => key === field || !state.errors[key])
		}));
	},
	validateRequired: () => {
		const state = get();
		const errors = {};
		if (!state.title) errors.title = "Title is required";
		if (Object.keys(errors).length > 0) {
			set({
				errors,
				isValid: false
			});
			return false;
		}
		set({
			errors: {},
			isValid: true
		});
		return true;
	},
	clearErrors: () => {
		set({
			errors: {},
			isValid: false
		});
	},
	clearFieldError: (field) => {
		set((state) => ({ errors: {
			...state.errors,
			[field]: void 0
		} }));
	},
	markClean: () => {
		set({ isDirty: false });
	},
	setTranslationLoading: (languageIso, loading) => {
		set((state) => ({ translationLoading: {
			...state.translationLoading,
			[languageIso]: loading
		} }));
	},
	setTranslationData: (languageIso, data) => {
		set((state) => ({
			translations: {
				...state.translations,
				[languageIso]: data
			},
			translationLoading: {
				...state.translationLoading,
				[languageIso]: false
			}
		}));
	},
	updateTranslationField: (languageIso, field, value) => {
		set((state) => {
			const originalValue = state.translations[languageIso]?.[field];
			let error;
			if (field === "title" && value === "" && originalValue && originalValue.trim() !== "") error = "Title is required";
			return {
				editedTranslations: {
					...state.editedTranslations,
					[languageIso]: {
						...state.editedTranslations[languageIso],
						[field]: value
					}
				},
				translationErrors: {
					...state.translationErrors,
					[languageIso]: {
						...state.translationErrors[languageIso],
						[field]: error
					}
				}
			};
		});
	},
	getTranslation: (languageIso, field) => {
		const state = get();
		return state.editedTranslations[languageIso]?.[field] ?? state.translations[languageIso]?.[field];
	},
	getOriginalTranslation: (languageIso, field) => {
		return get().translations[languageIso]?.[field];
	},
	getEditedTranslation: (languageIso, field) => {
		return get().editedTranslations[languageIso]?.[field];
	},
	setTranslationError: (languageIso, field, error) => {
		set((state) => ({ translationErrors: {
			...state.translationErrors,
			[languageIso]: {
				...state.translationErrors[languageIso],
				[field]: error
			}
		} }));
	},
	getTranslationError: (languageIso, field) => {
		return get().translationErrors[languageIso]?.[field];
	},
	isTranslationLoading: (languageIso) => {
		return get().translationLoading[languageIso] ?? false;
	},
	resetTranslations: () => {
		set({
			translations: {},
			editedTranslations: {},
			translationErrors: {},
			translationLoading: {},
			translationsFetched: false
		});
	},
	setTranslationsFetched: (fetched) => {
		set({ translationsFetched: fetched });
	}
});
process.env.NODE_ENV === "development" ? (0, zustand.create)()((0, zustand_middleware.devtools)(createProductStore, { name: "product-store" })) : (0, zustand.create)()(createProductStore);
(0, zustand.create)()((set, get) => ({
	draftData: null,
	isFromSettings: false,
	navigationTarget: null,
	saveDraft: (data) => {
		const formData = data;
		if (formData?.title || formData?.description || formData?.sku || formData?.product_subscription_plans && formData.product_subscription_plans.length > 0) set({ draftData: data });
	},
	getDraft: () => {
		const { draftData, isFromSettings, navigationTarget } = get();
		if (!draftData) return null;
		if (isFromSettings && navigationTarget) return draftData;
		set({ draftData: null });
		return null;
	},
	clearDraft: () => {
		const { draftData } = get();
		if (draftData) set({ draftData: null });
	},
	setFromSettings: (value) => {
		set({ isFromSettings: value });
	},
	setNavigationTarget: (target) => {
		set({ navigationTarget: target });
	},
	reset: () => {
		set({
			draftData: null,
			isFromSettings: false,
			navigationTarget: null
		});
	}
}));
//#endregion
//#region ../../products/core/src/utils/product-helpers.ts
function getProductImageUrl(product) {
	if (!product) return null;
	if (Array.isArray(product.images) && product.images.length > 0) {
		const primaryImage = [...product.images].sort((a, b) => (a.position ?? 0) - (b.position ?? 0))[0];
		if (primaryImage?.image_url) return primaryImage.image_url;
	}
	return product.image_url ?? null;
}
//#endregion
//#region ../../products/core/src/utils/product-price.ts
function stripParentheticalText(text) {
	if (!text) return null;
	return text.replace(/\s*\([^)]*\)/g, "").trim();
}
function isShopVariantCountry(vc) {
	return vc !== void 0 && "display_wholesale_subscription_price" in vc;
}
function isAdminProduct(product) {
	return "display_price" in product;
}
function isVariantCountriesRecord(vc) {
	return vc !== null && typeof vc === "object" && !Array.isArray(vc);
}
function determineProductPrice(product, countryIso) {
	const { variants } = product;
	const selectedVariant = variants?.find((v) => {
		if (isVariantCountriesRecord(v.variant_countries)) return v.variant_countries[countryIso]?.active;
		return false;
	}) || variants?.[0] || null;
	let variantCountry;
	if (countryIso && selectedVariant?.variant_countries) {
		const variantCountries = selectedVariant.variant_countries;
		if (Array.isArray(variantCountries)) variantCountry = variantCountries.find((v) => v?.country?.iso === countryIso);
		else if (isVariantCountriesRecord(variantCountries)) variantCountry = variantCountries[countryIso];
	}
	if (selectedVariant?.subscription_only) return { repPrice: isShopVariantCountry(variantCountry) ? variantCountry.display_wholesale_subscription_price : void 0 };
	const price = isShopVariantCountry(variantCountry) ? variantCountry.display_price : isAdminProduct(product) ? product.display_price : void 0;
	const repPrice = isShopVariantCountry(variantCountry) ? variantCountry.display_wholesale : void 0;
	return {
		repPrice: stripParentheticalText(repPrice),
		price: price === repPrice ? null : stripParentheticalText(price)
	};
}
//#endregion
//#region src/adapters/products-api-adapter.ts
/**
* Creates a PortalProductsApi-compatible adapter from a portal-tenant FetchClient.
*
* This bridges the auto-generated portal-tenant API client to the abstract
* PortalProductsApi interface defined in @fluid-app/products-core, closing
* over the FetchClient so consumers don't need to pass it per-call.
*
* Each method maps the BFF response to the port type at runtime rather than
* using type assertions, so TypeScript catches schema drift between the
* generated client and the hand-authored port types at compile time.
*/
function createPortalProductsApiAdapter(client) {
	return {
		listProducts: async (params) => {
			const response = await require_portal_tenant.products_list(client, {
				"page[cursor]": params?.cursor,
				"page[limit]": params?.limit,
				sort: params?.sort
			});
			return {
				products: response.products ?? [],
				meta: response.meta
			};
		},
		getProduct: async (id) => {
			const response = await require_portal_tenant.products_show(client, id);
			return {
				product: response.product ?? {},
				meta: response.meta
			};
		},
		searchProducts: async (query, params) => {
			const response = await require_portal_tenant.products_search(client, {
				q: query,
				"page[cursor]": params?.cursor,
				"page[limit]": params?.limit
			});
			return {
				products: response.products ?? [],
				meta: response.meta
			};
		},
		getProductMedia: async (productId) => {
			const response = await require_portal_tenant.products_media_list(client, productId);
			return {
				media: response.media ?? [],
				meta: response.meta
			};
		},
		listVisitedMetrics: async (params) => {
			const response = await require_portal_tenant.product_by_visits(client, {
				period: params?.period,
				limit: params?.limit
			});
			return {
				resources: response.resources ?? [],
				meta: response.meta
			};
		},
		listShareVisitedMetrics: async (params) => {
			const response = await require_portal_tenant.product_by_shares(client, {
				period: params?.period,
				limit: params?.limit
			});
			return {
				resources: response.resources ?? [],
				meta: response.meta
			};
		}
	};
}
//#endregion
//#region src/products/PortalProductsApiProvider.tsx
function PortalProductsApiProvider({ children }) {
	const client = require_PortalTenantClientProvider.usePortalTenantClient();
	return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(PortalProductsCoreProvider, {
		api: (0, react.useMemo)(() => createPortalProductsApiAdapter(client), [client]),
		children
	});
}
//#endregion
Object.defineProperty(exports, "PortalProductsApiProvider", {
	enumerable: true,
	get: function() {
		return PortalProductsApiProvider;
	}
});
Object.defineProperty(exports, "SearchSort", {
	enumerable: true,
	get: function() {
		return SearchSort;
	}
});
Object.defineProperty(exports, "determineProductPrice", {
	enumerable: true,
	get: function() {
		return determineProductPrice;
	}
});
Object.defineProperty(exports, "getProductImageUrl", {
	enumerable: true,
	get: function() {
		return getProductImageUrl;
	}
});
Object.defineProperty(exports, "usePortalProductCatalog", {
	enumerable: true,
	get: function() {
		return usePortalProductCatalog;
	}
});
Object.defineProperty(exports, "usePortalProductDetail", {
	enumerable: true,
	get: function() {
		return usePortalProductDetail;
	}
});
Object.defineProperty(exports, "usePortalProductsApi", {
	enumerable: true,
	get: function() {
		return usePortalProductsApi;
	}
});

//# sourceMappingURL=PortalProductsApiProvider-BNsaexxl.cjs.map