import { n as __exportAll } from "./chunk-B-1-B7_t.js";
import { n as cn } from "./utils-DXzSsU1e.js";
import { n as Button_default } from "./button-B9CnnuTu.js";
import { a as useFormDataStore, n as FORM_ID_KEY } from "./ElementRenderer-DV1pZRd4.js";
import { t as RepeatableRow_default } from "./RepeatableRow-DZCxBLVk.js";
import { Fragment, computed, createBlock, createCommentVNode, createElementBlock, createElementVNode, createTextVNode, createVNode, defineComponent, inject, nextTick, normalizeClass, openBlock, ref, renderList, toDisplayString, unref, watch, withCtx, withModifiers } from "vue";
import { ChevronDown, ChevronRight, Plus, Trash2 } from "@lucide/vue";
//#region src/components/compositions/elements/configuration-block/RepeatableBlock.vue?vue&type=script&setup=true&lang.ts
var _hoisted_1 = ["data-element-name"];
var _hoisted_2 = {
	key: 0,
	class: "flex flex-col gap-2"
};
var _hoisted_3 = ["onClick"];
var _hoisted_4 = { class: "flex items-center gap-1.5 text-sm font-medium" };
var _hoisted_5 = {
	key: 0,
	class: "border-t px-3 py-3"
};
var RepeatableBlock_vue_vue_type_script_setup_true_lang_default = /* @__PURE__ */ defineComponent({
	__name: "RepeatableBlock",
	props: {
		label: { default: "Repeatable" },
		name: {},
		modelValue: { default: () => [] },
		nestedElements: { default: () => [] },
		addButtonLabel: { default: "Add row" },
		optionLabelFields: { default: () => [] },
		collapsedByDefault: {
			type: Boolean,
			default: false
		},
		item: { default: () => ({}) },
		classList: {}
	},
	emits: ["update:modelValue"],
	setup(__props, { emit: __emit }) {
		const props = __props;
		const emit = __emit;
		const parentFormId = inject(FORM_ID_KEY, "default");
		const store = useFormDataStore();
		const rowSchema = computed(() => (props.nestedElements ?? []).filter((entry) => typeof entry === "object" && entry !== null && typeof entry.type === "string"));
		let nextRowId = 0;
		function makeRowFormId(rowId) {
			return `${parentFormId}__${props.name ?? "repeatable"}__${rowId}`;
		}
		function makeRow(initialData) {
			const id = nextRowId++;
			const formId = makeRowFormId(id);
			store.ensureForm(formId);
			if (initialData && Object.keys(initialData).length > 0) store.setInitialValues(formId, initialData);
			return {
				id,
				formId,
				collapsed: props.collapsedByDefault
			};
		}
		function buildRows(data) {
			return data.map((d) => makeRow(typeof d === "object" && d !== null ? d : {}));
		}
		const rows = ref(Array.isArray(props.modelValue) && props.modelValue.length > 0 ? buildRows(props.modelValue) : []);
		function collectRowData() {
			return rows.value.map((row) => ({ ...store.forms[row.formId]?.values ?? {} }));
		}
		function rowLabel(row, index) {
			const labelFields = props.optionLabelFields ?? [];
			if (labelFields.length > 0) {
				const values = store.forms[row.formId]?.values ?? {};
				const parts = labelFields.map((f) => values[f]).filter((v) => typeof v === "string" && v.trim() !== "").join(" ");
				if (parts) return parts;
			}
			return `${props.label} ${index + 1}`;
		}
		let suppressSync = false;
		watch(() => rows.value.map((r) => ({ ...store.forms[r.formId]?.values })), () => {
			if (suppressSync) return;
			suppressSync = true;
			emit("update:modelValue", collectRowData());
			nextTick(() => {
				suppressSync = false;
			});
		}, { deep: true });
		watch(() => props.modelValue, (next) => {
			if (suppressSync || !Array.isArray(next)) return;
			if (next.length === rows.value.length) return;
			suppressSync = true;
			if (next.length > rows.value.length) while (rows.value.length < next.length) {
				const d = next[rows.value.length];
				rows.value.push(makeRow(typeof d === "object" && d !== null ? d : {}));
			}
			else rows.value.splice(next.length).forEach((r) => store.resetForm(r.formId));
			nextTick(() => {
				suppressSync = false;
			});
		});
		function addRow() {
			rows.value.push(makeRow());
		}
		function removeRow(rowId) {
			const idx = rows.value.findIndex((r) => r.id === rowId);
			if (idx < 0) return;
			const [removed] = rows.value.splice(idx, 1);
			store.resetForm(removed.formId);
		}
		function toggleRow(rowId) {
			const row = rows.value.find((r) => r.id === rowId);
			if (row) row.collapsed = !row.collapsed;
		}
		return (_ctx, _cache) => {
			return openBlock(), createElementBlock("div", {
				class: normalizeClass(unref(cn)("flex flex-col gap-1", props.classList)),
				"data-element-name": props.name ?? void 0
			}, [rows.value.length ? (openBlock(), createElementBlock("div", _hoisted_2, [(openBlock(true), createElementBlock(Fragment, null, renderList(rows.value, (row, index) => {
				return openBlock(), createElementBlock("div", {
					key: row.id,
					class: "rounded-md border bg-card",
					"data-testid": "repeatable-row"
				}, [createElementVNode("div", {
					class: "flex cursor-pointer items-center justify-between gap-2 px-3 py-2",
					onClick: ($event) => toggleRow(row.id)
				}, [createElementVNode("div", _hoisted_4, [!row.collapsed ? (openBlock(), createBlock(unref(ChevronDown), {
					key: 0,
					class: "size-3.5 shrink-0 text-muted-foreground"
				})) : (openBlock(), createBlock(unref(ChevronRight), {
					key: 1,
					class: "size-3.5 shrink-0 text-muted-foreground"
				})), createElementVNode("span", null, toDisplayString(rowLabel(row, index)), 1)]), createVNode(unref(Button_default), {
					variant: "ghost",
					size: "icon-sm",
					type: "button",
					"aria-label": "Remove row",
					class: "shrink-0 text-muted-foreground hover:text-destructive",
					onClick: withModifiers(($event) => removeRow(row.id), ["stop"])
				}, {
					default: withCtx(() => [createVNode(unref(Trash2), { class: "size-3.5" })]),
					_: 1
				}, 8, ["onClick"])], 8, _hoisted_3), !row.collapsed && rowSchema.value.length ? (openBlock(), createElementBlock("div", _hoisted_5, [createVNode(RepeatableRow_default, {
					"form-id": row.formId,
					schema: rowSchema.value,
					item: props.item
				}, null, 8, [
					"form-id",
					"schema",
					"item"
				])])) : createCommentVNode("", true)]);
			}), 128))])) : createCommentVNode("", true), createVNode(unref(Button_default), {
				type: "button",
				variant: "outline",
				size: "sm",
				class: "self-start",
				"data-testid": "repeatable-add",
				onClick: addRow
			}, {
				default: withCtx(() => [createVNode(unref(Plus), { class: "size-3.5" }), createTextVNode(" " + toDisplayString(props.addButtonLabel), 1)]),
				_: 1
			})], 10, _hoisted_1);
		};
	}
});
//#endregion
//#region src/components/compositions/elements/configuration-block/RepeatableBlock.vue
var RepeatableBlock_exports = /* @__PURE__ */ __exportAll({ default: () => RepeatableBlock_default });
var RepeatableBlock_default = RepeatableBlock_vue_vue_type_script_setup_true_lang_default;
//#endregion
export { RepeatableBlock_exports as n, RepeatableBlock_default as t };

//# sourceMappingURL=RepeatableBlock-Do7zdZfl.js.map