import { r as useWorkspace, w as useActiveEntities } from "./store-DpSUVhjp.js";
import { t as _plugin_vue_export_helper_default } from "./_plugin-vue_export-helper-BmmBcIzD.js";
import { t as CodeInput_default } from "./CodeInput-C-igR77V.js";
import { n as DataTableCell_default, r as DataTable_default, t as DataTableRow_default } from "./DataTableRow-c3XveEUO.js";
import { t as DataTableHeader_default } from "./DataTableHeader-DJVB0jCZ.js";
import { t as ViewLayoutSection_default } from "./ViewLayoutSection-mUqKbQry.js";
import { t as DeleteSidebarListElement_default } from "./DeleteSidebarListElement-C-p87d03.js";
import { t as EditSidebarListElement_default } from "./EditSidebarListElement-CodWPnM6.js";
import { n as EnvironmentColorModal_default, t as EnvironmentModal_default } from "./EnvironmentModal-DBEJ4Kzj.js";
import { Fragment, computed, createBlock, createCommentVNode, createElementBlock, createElementVNode, createSlots, createTextVNode, createVNode, defineComponent, nextTick, normalizeClass, normalizeStyle, onMounted, openBlock, ref, renderList, toDisplayString, unref, watch, withCtx, withModifiers } from "vue";
import { ScalarButton, ScalarIcon, ScalarModal, useModal } from "@scalar/components";
import { ScalarIconTrash, ScalarIconWarning } from "@scalar/icons";
import { Draggable } from "@scalar/draggable";
//#endregion
//#region src/views/Collection/components/EnvironmentForm.vue
var EnvironmentForm_default = /* @__PURE__ */ _plugin_vue_export_helper_default(/* @__PURE__ */ defineComponent({
	__name: "EnvironmentForm",
	props: {
		collection: {},
		environment: {},
		workspace: {},
		envVariables: {}
	},
	setup(__props) {
		const { collectionMutators } = useWorkspace();
		const localVariables = ref([]);
		const collectionKeys = ref(/* @__PURE__ */ new Set());
		const tempKeys = ref(/* @__PURE__ */ new Map());
		const isUpdating = ref(false);
		const variables = computed(() => {
			if (!__props.environment?.value) return [{
				key: "",
				value: ""
			}];
			try {
				const parsedObject = JSON.parse(__props.environment.value);
				const entries = Object.entries(parsedObject).map(([key, val]) => ({
					key,
					value: String(val)
				}));
				if (entries.length === 0) return [{
					key: "",
					value: ""
				}];
				return entries;
			} catch (_) {
				return [{
					key: "",
					value: ""
				}];
			}
		});
		const environmentVariables = computed(() => {
			const lastRow = localVariables.value[localVariables.value.length - 1];
			if (!lastRow) return [{
				key: "",
				value: ""
			}];
			if (lastRow.key || lastRow.value) return [...localVariables.value, {
				key: "",
				value: ""
			}];
			return localVariables.value;
		});
		const getDuplicateKeyIndexes = computed(() => {
			const keyCounts = /* @__PURE__ */ new Map();
			localVariables.value.forEach((v, index) => {
				if (v.key) {
					const indexes = keyCounts.get(v.key) || [];
					indexes.push(index);
					keyCounts.set(v.key, indexes);
				}
			});
			tempKeys.value.forEach((key, index) => {
				if (key) {
					const indexes = keyCounts.get(key) || [];
					indexes.push(index);
					keyCounts.set(key, indexes);
				}
			});
			return Array.from(keyCounts.values()).filter((indexes) => indexes.length > 1).flat();
		});
		watch(variables, (newVars) => {
			localVariables.value = [...newVars];
			collectionKeys.value = new Set(newVars.map((v) => v.key).filter(Boolean));
		}, { immediate: true });
		const handleUpdateRow = async (index, field, value) => {
			if (isUpdating.value) return;
			if (field === "key") {
				tempKeys.value.set(index, value);
				const otherKeys = new Set(collectionKeys.value);
				const currentItem = localVariables.value[index];
				if (currentItem) otherKeys.delete(currentItem.key);
				if (otherKeys.has(value)) return;
			}
			isUpdating.value = true;
			try {
				const newVariables = [...localVariables.value];
				const currentItem = newVariables[index];
				if (!currentItem) return;
				newVariables[index] = {
					key: field === "key" ? value : currentItem.key,
					value: field === "value" ? value : currentItem.value
				};
				if (!newVariables[index].key && !newVariables[index].value && index !== newVariables.length - 1) newVariables.splice(index, 1);
				const updatedValue = newVariables.reduce((acc, { key, value }) => {
					if (key || value) acc[key] = value;
					return acc;
				}, {});
				if (__props.collection) {
					const environments = {
						...__props.collection["x-scalar-environments"],
						[__props.environment.name]: {
							...__props.collection["x-scalar-environments"]?.[__props.environment.name],
							variables: updatedValue
						}
					};
					await collectionMutators.edit(__props.collection.uid, "x-scalar-environments", environments);
				}
				if (index === localVariables.value.length - 1) {
					const lastRow = newVariables[newVariables.length - 1];
					if (lastRow && (lastRow.key || lastRow.value)) await addRow();
				}
				await nextTick();
				localVariables.value = newVariables;
				if (field === "key") {
					collectionKeys.value = new Set(newVariables.map((v) => v.key).filter(Boolean));
					tempKeys.value.delete(index);
				}
			} finally {
				isUpdating.value = false;
			}
		};
		const addRow = async () => {
			if (isUpdating.value) return;
			isUpdating.value = true;
			try {
				const newVariables = [...localVariables.value, {
					key: "",
					value: ""
				}];
				const updatedValue = newVariables.reduce((acc, { key, value }) => {
					if (key || value) acc[key] = value;
					return acc;
				}, {});
				if (__props.collection) {
					const environments = {
						...__props.collection["x-scalar-environments"],
						[__props.environment.name]: {
							...__props.collection["x-scalar-environments"]?.[__props.environment.name],
							variables: updatedValue
						}
					};
					await collectionMutators.edit(__props.collection.uid, "x-scalar-environments", environments);
				}
				await nextTick();
				localVariables.value = newVariables;
			} finally {
				isUpdating.value = false;
			}
		};
		const handleDeleteRow = async (index) => {
			if (isUpdating.value) return;
			isUpdating.value = true;
			try {
				const newVariables = [...localVariables.value];
				newVariables.splice(index, 1);
				const updatedValue = newVariables.reduce((acc, { key, value }) => {
					if (key || value) acc[key] = value;
					return acc;
				}, {});
				if (__props.collection) {
					const environments = {
						...__props.collection["x-scalar-environments"],
						[__props.environment.name]: {
							...__props.collection["x-scalar-environments"]?.[__props.environment.name],
							variables: updatedValue
						}
					};
					await collectionMutators.edit(__props.collection.uid, "x-scalar-environments", environments);
				}
				await nextTick();
				localVariables.value = newVariables;
			} finally {
				isUpdating.value = false;
			}
		};
		const defaultRow = async () => {
			if (localVariables.value.length === 0) await addRow();
			else if (localVariables.value.length >= 1) {
				const lastRow = localVariables.value[localVariables.value.length - 1];
				if (lastRow && (lastRow.key || lastRow.value)) await addRow();
			}
		};
		onMounted(() => {
			defaultRow();
		});
		watch(() => localVariables.value, () => {
			defaultRow();
		});
		return (_ctx, _cache) => {
			return openBlock(), createBlock(DataTable_default, {
				class: "group/table flex-1",
				columns: ["", ""]
			}, {
				default: withCtx(() => [createVNode(DataTableRow_default, { class: "sr-only !block" }, {
					default: withCtx(() => [createVNode(DataTableHeader_default, null, {
						default: withCtx(() => [..._cache[0] || (_cache[0] = [createTextVNode("Key", -1)])]),
						_: 1
					}), createVNode(DataTableHeader_default, null, {
						default: withCtx(() => [..._cache[1] || (_cache[1] = [createTextVNode("Value", -1)])]),
						_: 1
					})]),
					_: 1
				}), (openBlock(true), createElementBlock(Fragment, null, renderList(environmentVariables.value, (variable, index) => {
					return openBlock(), createBlock(DataTableRow_default, {
						key: index,
						class: normalizeClass({ error: getDuplicateKeyIndexes.value.includes(index) })
					}, {
						default: withCtx(() => [createVNode(DataTableCell_default, null, {
							default: withCtx(() => [createVNode(CodeInput_default, {
								disableCloseBrackets: "",
								disableEnter: "",
								disableTabIndent: "",
								lineWrapping: "",
								environment: __props.environment,
								envVariables: __props.envVariables,
								modelValue: variable.key,
								placeholder: "Key",
								workspace: __props.workspace,
								"onUpdate:modelValue": (v) => handleUpdateRow(index, "key", v)
							}, createSlots({ _: 2 }, [getDuplicateKeyIndexes.value.includes(index) ? {
								name: "icon",
								fn: withCtx(() => [createVNode(unref(ScalarIconWarning), { class: "text-red mr-0.75 size-3.5 brightness-[.9]" })]),
								key: "0"
							} : void 0]), 1032, [
								"environment",
								"envVariables",
								"modelValue",
								"workspace",
								"onUpdate:modelValue"
							])]),
							_: 2
						}, 1024), createVNode(DataTableCell_default, null, {
							default: withCtx(() => [createVNode(CodeInput_default, {
								class: "pr-6 group-hover:pr-10 group-has-[.cm-focused]:pr-10",
								disableCloseBrackets: "",
								disableEnter: "",
								disableTabIndent: "",
								lineWrapping: "",
								environment: __props.environment,
								envVariables: __props.envVariables,
								modelValue: variable.value,
								placeholder: "Value",
								workspace: __props.workspace,
								"onUpdate:modelValue": (v) => handleUpdateRow(index, "value", v)
							}, {
								icon: withCtx(() => [variable.key || variable.value ? (openBlock(), createBlock(unref(ScalarButton), {
									key: 0,
									class: "text-c-2 hover:text-c-1 hover:bg-b-2 z-context hidden h-fit rounded p-1 group-hover:flex group-has-[.cm-focused]:flex",
									size: "sm",
									variant: "ghost",
									onClick: withModifiers(($event) => handleDeleteRow(index), ["stop"])
								}, {
									default: withCtx(() => [createVNode(unref(ScalarIconTrash), { class: "size-3.5" })]),
									_: 1
								}, 8, ["onClick"])) : createCommentVNode("", true)]),
								_: 2
							}, 1032, [
								"environment",
								"envVariables",
								"modelValue",
								"workspace",
								"onUpdate:modelValue"
							])]),
							_: 2
						}, 1024)]),
						_: 2
					}, 1032, ["class"]);
				}), 128))]),
				_: 1
			});
		};
	}
}), [["__scopeId", "data-v-83bfcc8a"]]);
//#endregion
//#region src/views/Collection/CollectionEnvironment.vue?vue&type=script&setup=true&lang.ts
var _hoisted_1 = { class: "flex h-full w-full flex-col gap-12 px-1.5 pt-8" };
var _hoisted_2 = { class: "flex flex-col gap-4" };
var _hoisted_3 = { class: "rounded-lg border" };
var _hoisted_4 = { class: "bg-b-2 flex cursor-grab items-center justify-between rounded-t-lg px-1 py-1 text-sm" };
var _hoisted_5 = { class: "flex items-center" };
var _hoisted_6 = ["onClick"];
var _hoisted_7 = { class: "text-c-3 flex h-full items-center justify-center rounded-lg border p-4" };
//#endregion
//#region src/views/Collection/CollectionEnvironment.vue
var CollectionEnvironment_default = /* @__PURE__ */ defineComponent({
	__name: "CollectionEnvironment",
	setup(__props) {
		const { activeCollection, activeWorkspace, activeEnvVariables } = useActiveEntities();
		const { collectionMutators } = useWorkspace();
		const colorModal = useModal();
		const deleteModal = useModal();
		const environmentModal = useModal();
		const editModal = useModal();
		const selectedColor = ref("");
		const selectedEnvironmentName = ref(null);
		const tempEnvironmentName = ref(void 0);
		const collectionEnvironments = computed(() => {
			if (!activeCollection.value?.["x-scalar-environments"]) return [];
			return Object.entries(activeCollection.value["x-scalar-environments"]).map(([name, environment]) => ({
				uid: name,
				name,
				value: JSON.stringify(environment.variables || {}),
				color: environment.color || "#FFFFFF"
			}));
		});
		const deleteEnvironment = () => {
			if (!activeCollection.value?.uid || !selectedEnvironmentName.value) return;
			collectionMutators.removeEnvironment(selectedEnvironmentName.value, activeCollection.value.uid);
			deleteModal.hide();
		};
		const openDeleteModal = (environmentName) => {
			selectedEnvironmentName.value = environmentName;
			deleteModal.show();
		};
		const handleEnvironmentSubmit = (environment) => {
			if (!activeCollection.value?.uid) return;
			collectionMutators.addEnvironment(environment.name, {
				variables: {},
				color: environment.color
			}, activeCollection.value.uid);
			environmentModal.hide();
		};
		const handleOpenColorModal = (environment) => {
			selectedEnvironmentName.value = environment.name;
			selectedColor.value = environment.color || "#FFFFFF";
			colorModal.show();
		};
		const submitColorChange = (color) => {
			if (!activeCollection.value?.uid || !selectedEnvironmentName.value) return;
			const environments = {
				...activeCollection.value["x-scalar-environments"],
				[selectedEnvironmentName.value]: {
					variables: activeCollection.value["x-scalar-environments"]?.[selectedEnvironmentName.value]?.variables || {},
					color
				}
			};
			collectionMutators.edit(activeCollection.value.uid, "x-scalar-environments", environments);
			colorModal.hide();
		};
		const openRenameModal = (environmentName) => {
			selectedEnvironmentName.value = environmentName;
			tempEnvironmentName.value = environmentName;
			editModal.show();
		};
		const closeRenameModal = () => {
			selectedEnvironmentName.value = null;
			tempEnvironmentName.value = void 0;
			editModal.hide();
		};
		const handleRename = (newName) => {
			if (!activeCollection.value?.uid || !selectedEnvironmentName.value) return;
			const environments = { ...activeCollection.value["x-scalar-environments"] };
			if (!environments[selectedEnvironmentName.value]) return;
			const orderedEnvs = {};
			const envEntries = Object.entries(environments);
			const envIndex = envEntries.findIndex(([key]) => key === selectedEnvironmentName.value);
			envEntries.forEach(([key, value], index) => {
				if (index === envIndex) orderedEnvs[newName] = value;
				else orderedEnvs[key] = value;
			});
			collectionMutators.edit(activeCollection.value.uid, "x-scalar-environments", orderedEnvs);
			selectedEnvironmentName.value = null;
			tempEnvironmentName.value = void 0;
			editModal.hide();
		};
		const handleDragEnd = (draggingItem, hoveredItem) => {
			if (!activeCollection.value?.uid) return;
			const environments = { ...activeCollection.value["x-scalar-environments"] };
			const orderedEnvs = {};
			const envEntries = Object.entries(environments);
			const dragIndex = envEntries.findIndex(([key]) => key === draggingItem.id);
			const hoverIndex = envEntries.findIndex(([key]) => key === hoveredItem.id);
			if (dragIndex === -1 || hoverIndex === -1) return;
			const draggedEnv = envEntries[dragIndex];
			if (!draggedEnv) return;
			envEntries.splice(dragIndex, 1);
			envEntries.splice(hoverIndex, 0, draggedEnv);
			envEntries.forEach(([key, value]) => {
				orderedEnvs[key] = value;
			});
			collectionMutators.edit(activeCollection.value.uid, "x-scalar-environments", orderedEnvs);
		};
		return (_ctx, _cache) => {
			return openBlock(), createBlock(ViewLayoutSection_default, null, {
				default: withCtx(() => [createElementVNode("div", _hoisted_1, [
					createElementVNode("div", _hoisted_2, [
						_cache[5] || (_cache[5] = createElementVNode("div", { class: "flex items-start justify-between gap-2" }, [createElementVNode("div", { class: "flex flex-col gap-2" }, [createElementVNode("div", { class: "flex h-8 items-center" }, [createElementVNode("h3", { class: "font-bold" }, "Environment Variables")]), createElementVNode("p", { class: "text-sm" }, [
							createTextVNode(" Set environment variables at your collection level. Use "),
							createElementVNode("code", { class: "font-code text-c-2" }, "{{ variable }}"),
							createTextVNode(" to add / search among the selected environment's variables in your request inputs. ")
						])])], -1)),
						(openBlock(true), createElementBlock(Fragment, null, renderList(collectionEnvironments.value, (environment) => {
							return openBlock(), createBlock(unref(Draggable), {
								key: environment.name,
								id: environment.name,
								isDraggable: true,
								isDroppable: true,
								parentIds: [],
								onOnDragEnd: handleDragEnd
							}, {
								default: withCtx(() => [createElementVNode("div", _hoisted_3, [createElementVNode("div", _hoisted_4, [createElementVNode("div", _hoisted_5, [createVNode(unref(ScalarButton), {
									class: "hover:bg-b-3 flex h-6 w-6 p-1",
									onClick: ($event) => handleOpenColorModal(environment),
									variant: "ghost"
								}, {
									default: withCtx(() => [createElementVNode("span", {
										style: normalizeStyle({ backgroundColor: environment.color || "#FFFFFF" }),
										class: "h-2.5 w-2.5 rounded-full"
									}, null, 4)]),
									_: 2
								}, 1032, ["onClick"]), createElementVNode("button", {
									class: "hover:bg-b-3 rounded px-1 py-0.5 text-sm",
									onClick: ($event) => openRenameModal(environment.name)
								}, toDisplayString(environment.name), 9, _hoisted_6)]), createVNode(unref(ScalarButton), {
									class: "hover:bg-b-3 hover:text-c-1 h-fit p-1.25",
									variant: "ghost",
									onClick: ($event) => openDeleteModal(environment.name)
								}, {
									default: withCtx(() => [createVNode(unref(ScalarIconTrash), { class: "size-3.5" })]),
									_: 1
								}, 8, ["onClick"])]), unref(activeCollection) && unref(activeWorkspace) ? (openBlock(), createBlock(EnvironmentForm_default, {
									key: 0,
									collection: unref(activeCollection),
									environment,
									envVariables: unref(activeEnvVariables),
									workspace: unref(activeWorkspace)
								}, null, 8, [
									"collection",
									"environment",
									"envVariables",
									"workspace"
								])) : createCommentVNode("", true)])]),
								_: 2
							}, 1032, ["id"]);
						}), 128)),
						createElementVNode("div", _hoisted_7, [createVNode(unref(ScalarButton), {
							class: "hover:bg-b-2 hover:text-c-1 flex items-center gap-2",
							size: "sm",
							variant: "ghost",
							onClick: _cache[0] || (_cache[0] = ($event) => unref(environmentModal).show())
						}, {
							default: withCtx(() => [createVNode(unref(ScalarIcon), {
								class: "inline-flex",
								icon: "Add",
								size: "sm",
								thickness: "1.5"
							}), _cache[4] || (_cache[4] = createElementVNode("span", null, "Add Environment", -1))]),
							_: 1
						})])
					]),
					createVNode(unref(ScalarModal), {
						size: "xxs",
						state: unref(deleteModal),
						title: `Delete ${selectedEnvironmentName.value || "Environment"}`
					}, {
						default: withCtx(() => [createVNode(DeleteSidebarListElement_default, {
							variableName: "Environment",
							warningMessage: "Are you sure you want to delete this environment? This action cannot be undone.",
							onClose: _cache[1] || (_cache[1] = ($event) => unref(deleteModal).hide()),
							onDelete: deleteEnvironment
						})]),
						_: 1
					}, 8, ["state", "title"]),
					createVNode(EnvironmentModal_default, {
						activeWorkspaceCollections: unref(activeCollection) ? [unref(activeCollection)] : [],
						collectionId: unref(activeCollection)?.uid,
						state: unref(environmentModal),
						onCancel: _cache[2] || (_cache[2] = ($event) => unref(environmentModal).hide()),
						onSubmit: handleEnvironmentSubmit
					}, null, 8, [
						"activeWorkspaceCollections",
						"collectionId",
						"state"
					]),
					createVNode(EnvironmentColorModal_default, {
						selectedColor: selectedColor.value,
						state: unref(colorModal),
						onCancel: _cache[3] || (_cache[3] = ($event) => unref(colorModal).hide()),
						onSubmit: submitColorChange
					}, null, 8, ["selectedColor", "state"]),
					createVNode(unref(ScalarModal), {
						size: "xxs",
						state: unref(editModal),
						title: `Edit ${selectedEnvironmentName.value}`
					}, {
						default: withCtx(() => [createVNode(EditSidebarListElement_default, {
							name: tempEnvironmentName.value ?? "",
							onClose: closeRenameModal,
							onEdit: handleRename
						}, null, 8, ["name"])]),
						_: 1
					}, 8, ["state", "title"])
				])]),
				_: 1
			});
		};
	}
});
//#endregion
export { CollectionEnvironment_default as default };

//# sourceMappingURL=CollectionEnvironment-Dw35vIqo.js.map