import { vt as __exportAll } from "./PortalTenantClientProvider-BmRtQAbi.mjs";
import { n as useWidgetInteraction } from "./WidgetInteractionContext-BWH7njU7.mjs";
import { i as getBorderColorField, l as getColorField, m as getPaddingField, n as borderWidthClasses, o as getBorderRadiusField, s as getBorderWidthField, t as borderColorClasses, u as getFontSizeField } from "./registries-59Barbhg.mjs";
import { n as getMediaPropsFromShareable, t as MediaRenderer } from "./MediaRenderer-Db1KsIza.mjs";
import { k as Input } from "./src-CJw6JbdS.mjs";
import { useMemo, useState } from "react";
import { Fragment as Fragment$1, jsx, jsxs } from "react/jsx-runtime";
//#region ../widgets/src/widgets/TableWidget.tsx
var TableWidget_exports = /* @__PURE__ */ __exportAll({
	TableWidget: () => TableWidget,
	tableWidgetPropertySchema: () => tableWidgetPropertySchema
});
const DEFAULT_DATA = [];
function ImageCellRenderer(_value, item) {
	return /* @__PURE__ */ jsx("div", {
		className: "size-10 overflow-hidden rounded",
		children: /* @__PURE__ */ jsx(MediaRenderer, { ...getMediaPropsFromShareable(item) })
	});
}
function PriceCellRenderer(_value, item) {
	return (item.display_price ?? item.price) || "-";
}
function StatusCellRenderer(value) {
	return /* @__PURE__ */ jsx("span", {
		className: `inline-flex rounded-full px-2 py-1 text-xs font-medium ${{
			active: "bg-primary text-primary-foreground",
			paid: "bg-primary text-primary-foreground",
			inactive: "bg-secondary text-secondary-foreground",
			paused: "bg-secondary text-secondary-foreground",
			unknown: "bg-muted text-muted-foreground",
			unpaid: "bg-destructive text-destructive-foreground",
			refunded: "bg-muted text-muted-foreground",
			cancelled: "bg-destructive text-destructive-foreground"
		}[String(value || "unknown").toLowerCase()] || "bg-muted text-foreground"}`,
		children: String(value || "Unknown")
	});
}
/** Map of column keys to custom cell renderers */
const CELL_RENDERERS = {
	imageUrl: ImageCellRenderer,
	price: PriceCellRenderer,
	display_price: PriceCellRenderer,
	status: StatusCellRenderer
};
/** Resolve plain column definitions from a data source into full ColumnDefs with renderers */
function resolveColumns(columns) {
	return columns.map((col) => {
		const render = CELL_RENDERERS[col.key];
		return render ? {
			...col,
			render
		} : { ...col };
	});
}
const defaultColumns = [
	{
		key: "imageUrl",
		label: "Image",
		sortable: false,
		render: ImageCellRenderer
	},
	{
		key: "title",
		label: "Title",
		sortable: true
	},
	{
		key: "price",
		label: "Price",
		sortable: true,
		render: PriceCellRenderer
	},
	{
		key: "status",
		label: "Status",
		sortable: true,
		render: StatusCellRenderer
	}
];
function TableWidget({ titleEnabled = true, titleText = "Products", titleFontSize = "xl", titleColor = "foreground", background = {
	type: "solid",
	color: "background"
}, alternatingColorEnabled = true, textColor = "foreground", headerBackgroundColor = "muted", headerTextColor = "foreground", padding = 4, borderRadius = "md", borderWidth = "none", borderColor = "muted", data = DEFAULT_DATA, columns: columnsProp, filterEnabled = true, sortingEnabled = true, paginationEnabled = true, maxRowsPerPage = 5, className, ...props }) {
	const backgroundColor = background.color || "background";
	const isImageBackground = background.type === "image";
	const backgroundImage = (background.resource?.image_url || background.resource?.imageUrl) && isImageBackground ? `url(${background.resource.image_url || background.resource.imageUrl})` : "none";
	const pageSize = maxRowsPerPage;
	const isTransparentBg = backgroundColor === "transparent";
	const useTransparentInner = isImageBackground || isTransparentBg;
	const innerBg = useTransparentInner ? "bg-transparent" : `bg-${backgroundColor}`;
	const innerBgAlt = useTransparentInner ? "bg-black/5" : `bg-${backgroundColor}/40`;
	const transparentBorder = isTransparentBg ? "border-black/20" : "border-white/20";
	const innerBorder = useTransparentInner ? transparentBorder : `border-${backgroundColor}/60`;
	const headerBg = useTransparentInner ? "bg-black/10" : `bg-${headerBackgroundColor}/40`;
	const headerBorder = useTransparentInner ? transparentBorder : `border-${headerBackgroundColor}/60`;
	const paginationBg = useTransparentInner ? "bg-black/10" : `bg-${backgroundColor}/40`;
	const [globalFilter, setGlobalFilter] = useState("");
	const [sortConfig, setSortConfig] = useState(null);
	const [currentPage, setCurrentPage] = useState(1);
	const firstCol = columnsProp?.[0];
	const validColumnsProp = firstCol && typeof firstCol.key === "string" && firstCol.key !== "" ? columnsProp : void 0;
	const columns = useMemo(() => validColumnsProp ? resolveColumns(validColumnsProp) : defaultColumns, [validColumnsProp]);
	const filteredData = useMemo(() => {
		let result = [...data];
		if (globalFilter) {
			const lowerFilter = globalFilter.toLowerCase();
			result = result.filter((item) => columns.some((col) => {
				const value = item[col.key];
				return String(value ?? "").toLowerCase().includes(lowerFilter);
			}));
		}
		return result;
	}, [
		data,
		globalFilter,
		columns
	]);
	const sortedData = useMemo(() => {
		if (!sortConfig) return filteredData;
		return filteredData.toSorted((a, b) => {
			const aValue = a[sortConfig.key];
			const bValue = b[sortConfig.key];
			if (aValue == null && bValue == null) return 0;
			if (aValue == null) return sortConfig.direction === "asc" ? 1 : -1;
			if (bValue == null) return sortConfig.direction === "asc" ? -1 : 1;
			let comparison = 0;
			if (typeof aValue === "number" && typeof bValue === "number") comparison = aValue - bValue;
			else comparison = String(aValue).localeCompare(String(bValue));
			return sortConfig.direction === "asc" ? comparison : -comparison;
		});
	}, [filteredData, sortConfig]);
	const paginatedData = useMemo(() => {
		if (!paginationEnabled) return sortedData;
		const startIndex = (currentPage - 1) * pageSize;
		return sortedData.slice(startIndex, startIndex + pageSize);
	}, [
		sortedData,
		currentPage,
		pageSize,
		paginationEnabled
	]);
	const totalPages = Math.ceil(sortedData.length / pageSize);
	const handleGlobalFilterChange = (value) => {
		setGlobalFilter(value);
		setCurrentPage(1);
	};
	const handleSort = (key) => {
		if (!sortingEnabled) return;
		setSortConfig((prev) => {
			if (prev?.key !== key) return {
				key,
				direction: "asc"
			};
			if (prev.direction === "asc") return {
				key,
				direction: "desc"
			};
			return null;
		});
	};
	const getSortIndicator = (key) => {
		if (sortConfig?.key !== key) return null;
		return sortConfig.direction === "asc" ? " ↑" : " ↓";
	};
	const { onItemClick } = useWidgetInteraction();
	return /* @__PURE__ */ jsxs("div", {
		className: `@container overflow-hidden ${paginationEnabled ? "" : "overflow-y-auto"} rounded-${borderRadius} ${borderWidthClasses[borderWidth]} ${borderWidth !== "none" ? borderColorClasses[borderColor] : ""} bg-${backgroundColor} bg-cover bg-center text-${textColor} ${className}`,
		style: { backgroundImage },
		...props,
		children: [
			/* @__PURE__ */ jsxs("div", {
				className: `flex items-center justify-between p-${padding} ${innerBg} space-x-2`,
				children: [titleEnabled && titleText && /* @__PURE__ */ jsx("h2", {
					className: `text-${titleFontSize === "md" ? "base" : titleFontSize} font-header font-bold text-${titleColor} min-w-0 truncate`,
					children: titleText
				}), filterEnabled && /* @__PURE__ */ jsx(Input, {
					type: "text",
					placeholder: "Search all columns...",
					value: globalFilter,
					onChange: (e) => handleGlobalFilterChange(e.target.value),
					className: `w-full rounded-md border ${headerBorder} ${headerBg} ring-offset-muted px-3 py-2 text-sm placeholder:text-${headerTextColor}/40 focus-visible:ring-primary focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:outline-none md:w-64`
				})]
			}),
			/* @__PURE__ */ jsx("div", {
				className: "overflow-x-auto",
				children: /* @__PURE__ */ jsxs("table", {
					className: "w-full border-collapse",
					children: [/* @__PURE__ */ jsx("thead", { children: /* @__PURE__ */ jsx("tr", {
						className: `${headerBg} ${headerBorder} border-y`,
						children: columns.map((col) => /* @__PURE__ */ jsx("th", {
							className: `px-4 py-3 text-left text-sm font-semibold text-${headerTextColor} ${col.sortable && sortingEnabled ? "cursor-pointer select-none hover:opacity-80" : ""}`,
							...col.sortable && sortingEnabled ? {
								role: "button",
								tabIndex: 0,
								onClick: () => handleSort(col.key),
								onKeyDown: (e) => {
									if (e.key === "Enter" || e.key === " ") {
										e.preventDefault();
										handleSort(col.key);
									}
								}
							} : {},
							children: /* @__PURE__ */ jsx("div", {
								className: "flex flex-col gap-1",
								children: /* @__PURE__ */ jsxs("span", { children: [col.label, col.sortable && sortingEnabled && getSortIndicator(col.key)] })
							})
						}, col.key))
					}) }), /* @__PURE__ */ jsx("tbody", { children: data.length === 0 ? /* @__PURE__ */ jsx("tr", { children: /* @__PURE__ */ jsx("td", {
						colSpan: columns.length,
						children: /* @__PURE__ */ jsxs("div", {
							className: "text-muted-foreground flex min-h-[200px] flex-col items-center justify-center gap-2",
							children: [
								/* @__PURE__ */ jsx("div", {
									className: "text-4xl",
									children: "📋"
								}),
								/* @__PURE__ */ jsx("p", {
									className: "text-sm",
									children: "No data available"
								}),
								/* @__PURE__ */ jsx("p", {
									className: "text-muted-foreground/70 text-xs",
									children: "Connect a data source to display table data"
								})
							]
						})
					}) }) : paginatedData.length === 0 ? /* @__PURE__ */ jsx("tr", { children: /* @__PURE__ */ jsx("td", {
						colSpan: columns.length,
						children: /* @__PURE__ */ jsxs("div", {
							className: "py-8 text-center",
							children: [/* @__PURE__ */ jsx("p", {
								className: "text-sm",
								children: "No results found"
							}), /* @__PURE__ */ jsx("p", {
								className: "text-xs",
								children: "Try adjusting your search"
							})]
						})
					}) }) : /* @__PURE__ */ jsxs(Fragment$1, { children: [paginatedData.map((item, index) => /* @__PURE__ */ jsx("tr", {
						className: `h-17 border-b ${innerBorder} last:border-none ${innerBg} ${alternatingColorEnabled ? `even:${innerBgAlt}` : ""} ${onItemClick ? "cursor-pointer hover:opacity-80" : ""}`,
						...onItemClick ? {
							tabIndex: 0,
							onClick: () => onItemClick(item),
							onKeyDown: (e) => {
								if (e.key === "Enter" || e.key === " ") {
									e.preventDefault();
									onItemClick(item);
								}
							}
						} : {},
						children: columns.map((col) => /* @__PURE__ */ jsx("td", {
							className: "px-4 py-3 text-sm",
							children: col.render ? col.render(item[col.key], item) : String(item[col.key] ?? "-")
						}, col.key))
					}, item.id ?? index)), paginationEnabled && paginatedData.length < pageSize && paginatedData.length > 0 && Array.from({ length: pageSize - paginatedData.length }).map((_, index) => /* @__PURE__ */ jsx("tr", {
						className: `h-17 border-b ${innerBorder} last:border-none ${innerBg} ${alternatingColorEnabled ? `even:${innerBgAlt}` : ""}`,
						children: columns.map((col) => /* @__PURE__ */ jsx("td", {
							className: "px-4 py-3 text-sm",
							children: "\xA0"
						}, col.key))
					}, `empty-${index}`))] }) })]
				})
			}),
			paginationEnabled && totalPages > 1 && /* @__PURE__ */ jsxs("div", {
				className: `flex flex-col items-center justify-between gap-2 border-t ${innerBorder} p-${padding} @md:flex-row ${paginationBg} text-${textColor}`,
				children: [/* @__PURE__ */ jsxs("p", {
					className: "text-sm",
					children: [
						"Showing ",
						(currentPage - 1) * pageSize + 1,
						"-",
						Math.min(currentPage * pageSize, sortedData.length),
						" of",
						" ",
						sortedData.length,
						" results"
					]
				}), /* @__PURE__ */ jsxs("div", {
					className: "flex items-center gap-2",
					children: [
						/* @__PURE__ */ jsx("button", {
							onClick: () => setCurrentPage((p) => Math.max(1, p - 1)),
							disabled: currentPage === 1,
							className: `rounded-md border border-${headerBackgroundColor}/60 bg-${headerBackgroundColor} ring-offset-muted placeholder:text-muted-foreground focus-visible:ring-primary px-3 py-1 text-sm transition-opacity hover:opacity-80 focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50`,
							children: "Previous"
						}),
						/* @__PURE__ */ jsxs("span", {
							className: "text-sm",
							children: [
								"Page ",
								currentPage,
								" of ",
								totalPages
							]
						}),
						/* @__PURE__ */ jsx("button", {
							onClick: () => setCurrentPage((p) => Math.min(totalPages, p + 1)),
							disabled: currentPage === totalPages,
							className: `rounded-md border border-${headerBackgroundColor}/60 bg-${headerBackgroundColor} ring-offset-muted placeholder:text-muted-foreground focus-visible:ring-primary px-3 py-1 text-sm transition-opacity hover:opacity-80 focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50`,
							children: "Next"
						})
					]
				})]
			})
		]
	});
}
const tableWidgetPropertySchema = {
	widgetType: "TableWidget",
	displayName: "Table Widget",
	tabsConfig: [
		{
			id: "styling",
			label: "Styling"
		},
		{
			id: "behavior",
			label: "Behavior"
		},
		{
			id: "data",
			label: "Data"
		}
	],
	dataSourceTargetProps: ["data", "columns"],
	fields: [
		{
			key: "titleEnabled",
			label: "Widget Title",
			type: "boolean",
			description: "Enable the title displayed above the table",
			defaultValue: true,
			tab: "styling",
			group: "Title"
		},
		{
			key: "titleText",
			label: "Title",
			type: "text",
			description: "Title text displayed above the table",
			defaultValue: "Products",
			tab: "styling",
			group: "Title",
			requiresKeyToBeTrue: "titleEnabled"
		},
		getFontSizeField({
			label: "Title Font Size",
			defaultValue: "xl",
			key: "titleFontSize",
			description: "Font size for the widget title",
			tab: "styling",
			group: "Title",
			requiresKeyToBeTrue: "titleEnabled"
		}),
		getColorField({
			key: "titleColor",
			label: "Title Color",
			description: "Color for the widget title",
			defaultValue: "foreground",
			tab: "styling",
			group: "Title",
			requiresKeyToBeTrue: "titleEnabled"
		}),
		{
			type: "background",
			key: "background",
			label: "Background",
			description: "Background for the table container",
			defaultValue: "background",
			tab: "styling",
			group: "Design"
		},
		{
			key: "alternatingColorEnabled",
			label: "Enable Alternating Colors",
			type: "boolean",
			description: "Enable alternating colors for table rows",
			defaultValue: true,
			tab: "styling",
			group: "Design"
		},
		getColorField({
			key: "headerBackgroundColor",
			label: "Header Background",
			description: "Background color for the table header",
			defaultValue: "muted",
			tab: "styling",
			group: "Design"
		}),
		getColorField({
			key: "textColor",
			label: "Text Color",
			description: "Default text color for table content",
			defaultValue: "foreground",
			tab: "styling",
			group: "Design"
		}),
		getColorField({
			key: "headerTextColor",
			label: "Header Text Color",
			description: "Text color for the table header",
			defaultValue: "foreground",
			tab: "styling",
			group: "Design"
		}),
		{
			key: "separator",
			type: "separator",
			label: "Separator",
			tab: "styling",
			group: "Design"
		},
		getPaddingField({
			key: "padding",
			label: "Padding",
			description: "Padding around the table container",
			defaultValue: 4,
			tab: "styling",
			group: "Design"
		}),
		getBorderRadiusField({
			key: "borderRadius",
			label: "Border Radius",
			description: "Border radius for the table container",
			defaultValue: "md",
			tab: "styling",
			group: "Design"
		}),
		getBorderWidthField({
			key: "borderWidth",
			label: "Border Width",
			description: "Border width for the widget",
			defaultValue: "none",
			tab: "styling",
			group: "Design"
		}),
		getBorderColorField({
			key: "borderColor",
			label: "Border Color",
			description: "Border color for the widget",
			defaultValue: "muted",
			tab: "styling",
			group: "Design"
		}),
		{
			key: "filterEnabled",
			label: "Enable Filters",
			type: "boolean",
			description: "Show global search and column filters",
			defaultValue: true,
			tab: "behavior",
			group: "Features"
		},
		{
			key: "sortingEnabled",
			label: "Enable Sorting",
			type: "boolean",
			description: "Allow sorting by clicking column headers",
			defaultValue: true,
			tab: "behavior",
			group: "Features"
		},
		{
			key: "paginationEnabled",
			label: "Enable Pagination",
			type: "boolean",
			description: "Split data into pages",
			defaultValue: true,
			tab: "behavior",
			group: "Features"
		},
		{
			key: "maxRowsPerPage",
			label: "Max Rows Per Page",
			type: "number",
			description: "Maximum number of rows to display per page",
			min: 1,
			max: 50,
			step: 1,
			defaultValue: 5,
			tab: "behavior",
			group: "Features",
			requiresKeyToBeTrue: "paginationEnabled"
		},
		{
			key: "dataSource",
			label: "Data Source",
			type: "dataSource",
			description: "Configure data source for the table",
			tab: "data",
			group: "Data Configuration"
		}
	]
};
//#endregion
export { TableWidget_exports as n, tableWidgetPropertySchema as r, TableWidget as t };

//# sourceMappingURL=TableWidget-CpHI9CGQ.mjs.map