import ServerVariablesForm_default from "../../../../components/Server/ServerVariablesForm.vue.js";
import DeleteSidebarListElement_default from "../../../../components/Sidebar/Actions/DeleteSidebarListElement.vue.js";
import Section_default from "../../settings/components/Section.vue.js";
import Form_default from "./Form.vue.js";
import { Fragment, computed, createBlock, createCommentVNode, createElementBlock, createElementVNode, createSlots, createTextVNode, createVNode, defineComponent, normalizeClass, openBlock, ref, renderList, toDisplayString, unref, watchEffect, withCtx } from "vue";
import { ScalarButton, ScalarMarkdown, ScalarModal, ScalarToggle, useModal } from "@scalar/components";
import { ScalarIconPlus, ScalarIconTrash } from "@scalar/icons";
import { getResolvedRef } from "@scalar/workspace-store/helpers/get-resolved-ref";
import { isHttpMethod } from "@scalar/helpers/http/is-http-method";
import { debounce } from "@scalar/helpers/general/debounce";
//#region src/v2/features/collection/components/Servers.vue?vue&type=script&setup=true&lang.ts
var _hoisted_1 = { class: "flex h-8 items-center" };
var _hoisted_2 = { class: "flex flex-col gap-4" };
var _hoisted_3 = { class: "bg-b-2 flex items-center justify-between rounded-t-lg px-3 py-1 text-sm" };
var _hoisted_4 = {
	key: 1,
	class: "self-center"
};
var _hoisted_5 = { class: "divide-0 flex w-full flex-col divide-y rounded-b-lg text-sm" };
var _hoisted_6 = { class: "text-c-3 flex h-full items-center justify-center rounded-lg border p-4" };
var Servers_vue_vue_type_script_setup_true_lang_default = /* @__PURE__ */ defineComponent({
	__name: "Servers",
	props: {
		documentSlug: {},
		document: {},
		eventBus: {},
		layout: {},
		path: {},
		method: {},
		exampleName: {},
		environment: {},
		securitySchemes: {},
		workspaceStore: {},
		activeWorkspace: {},
		plugins: {},
		customThemes: {},
		currentTheme: {},
		isDarkMode: { type: Boolean },
		fetchRegistryDocument: { type: Function },
		telemetry: { type: Boolean },
		onUpdateTelemetry: { type: Function },
		collectionType: {}
	},
	setup(__props) {
		const deleteModal = useModal();
		const selectedServerIndex = ref(-1);
		const isOperation = computed(() => __props.collectionType === "operation");
		const operation = computed(() => {
			if (!isOperation.value) return null;
			if (!__props.path || !isHttpMethod(__props.method)) return null;
			return getResolvedRef(__props.document?.paths?.[__props.path]?.[__props.method]);
		});
		const useOperationServers = ref(false);
		watchEffect(() => {
			useOperationServers.value = operation.value?.servers !== void 0;
		});
		/** Grab the servers for the collection */
		const servers = computed(() => {
			if (__props.collectionType === "operation" && operation.value) return operation.value.servers ?? [];
			return __props.document?.servers ?? [];
		});
		/** Grab whichever server we are working on */
		const selectedServer = computed(() => servers.value[selectedServerIndex.value]);
		/** Meta for server events: document-level or operation-level based on collection type */
		const serverMeta = computed(() => {
			if (__props.collectionType === "operation" && __props.path && isHttpMethod(__props.method)) return {
				type: "operation",
				path: __props.path,
				method: __props.method
			};
			return { type: "document" };
		});
		const FORM_OPTIONS = [{
			label: "URL",
			key: "url",
			placeholder: "https://void.scalar.com"
		}, {
			label: "Description",
			key: "description",
			placeholder: "Production",
			lineWrapping: true
		}];
		/** Opens the delete confirmation modal for a server */
		const openDeleteModal = (index) => {
			selectedServerIndex.value = index;
			deleteModal.show();
		};
		/** Closes the delete modal and resets the selected server */
		const resetState = () => {
			deleteModal.hide();
			selectedServerIndex.value = -1;
		};
		/** Handles server deletion */
		const handleDeleteServer = () => {
			if (selectedServerIndex.value < 0) return;
			__props.eventBus.emit("server:delete:server", {
				index: selectedServerIndex.value,
				meta: serverMeta.value
			});
			resetState();
		};
		/** Debounced execute function for server updates, keyed so we only debounce by server + key */
		const { execute } = debounce({
			delay: 328,
			maxWait: 1e3
		});
		/** Handles server property updates with debouncing */
		const handleServerUpdate = (index, key, value) => execute(`${index}-${key}-${serverMeta.value.type}`, () => __props.eventBus.emit("server:update:server", {
			index,
			server: { [key]: value },
			meta: serverMeta.value
		}));
		/** Handles server variable updates with debouncing */
		const handleVariableUpdate = (index, key, value) => execute(`${index}-${key}-${serverMeta.value.type}`, () => __props.eventBus.emit("server:update:variables", {
			index,
			key,
			value,
			meta: serverMeta.value
		}));
		/** Handles adding a new server */
		const handleAddServer = () => __props.eventBus.emit("server:add:server", { meta: serverMeta.value });
		/**
		* Gets the display name for a server
		*/
		const getServerDisplayName = (server, index = 0) => server?.description || `Server ${index + 1}`;
		/** Handles toggling the operation servers */
		const handleToggleOperationServers = (value) => {
			if (serverMeta.value.type !== "operation") return;
			useOperationServers.value = value;
			if (value) return __props.eventBus.emit("server:initialize:servers", { meta: serverMeta.value });
			return __props.eventBus.emit("server:clear:servers", { meta: serverMeta.value });
		};
		return (_ctx, _cache) => {
			return openBlock(), createElementBlock(Fragment, null, [createVNode(Section_default, null, createSlots({
				title: withCtx(() => [_cache[0] || (_cache[0] = createTextVNode("Servers", -1))]),
				description: withCtx(() => [isOperation.value ? (openBlock(), createElementBlock(Fragment, { key: 0 }, [
					_cache[1] || (_cache[1] = createElementVNode("span", { class: "block" }, " Override servers for this operation with the toggle. ", -1)),
					_cache[2] || (_cache[2] = createElementVNode("span", { class: "mt-1 block" }, [createElementVNode("strong", null, "On"), createTextVNode(" — Servers below apply only to this operation. ")], -1)),
					_cache[3] || (_cache[3] = createElementVNode("span", { class: "mt-1 block" }, [createElementVNode("strong", null, "Off"), createTextVNode(" — Removes operation servers; this operation uses document or path servers from the OpenAPI spec. ")], -1)),
					_cache[4] || (_cache[4] = createElementVNode("span", { class: "text-c-3 mt-1 block" }, [
						createTextVNode(" Use "),
						createElementVNode("code", { class: "font-code text-c-2" }, "{variables}"),
						createTextVNode(" for dynamic URL parts. ")
					], -1))
				], 64)) : (openBlock(), createElementBlock(Fragment, { key: 1 }, [
					_cache[5] || (_cache[5] = createTextVNode(" Add different base URLs for your API. Use ", -1)),
					_cache[6] || (_cache[6] = createElementVNode("code", { class: "font-code text-c-2" }, "{variables}", -1)),
					_cache[7] || (_cache[7] = createTextVNode(" for dynamic parts. ", -1))
				], 64))]),
				default: withCtx(() => [createElementVNode("div", { class: normalizeClass(isOperation.value && !useOperationServers.value && "cursor-not-allowed") }, [createElementVNode("div", { class: normalizeClass(["flex flex-col gap-4", isOperation.value && !useOperationServers.value && "pointer-events-none cursor-not-allowed opacity-50 mix-blend-luminosity"]) }, [createElementVNode("div", _hoisted_2, [(openBlock(true), createElementBlock(Fragment, null, renderList(servers.value, (server, index) => {
					return openBlock(), createElementBlock("div", {
						key: index,
						class: "rounded-lg border"
					}, [createElementVNode("div", _hoisted_3, [server.description ? (openBlock(), createBlock(unref(ScalarMarkdown), {
						key: 0,
						class: "self-center",
						value: server.description
					}, null, 8, ["value"])) : (openBlock(), createElementBlock("span", _hoisted_4, toDisplayString(getServerDisplayName(server, index)), 1)), createVNode(unref(ScalarButton), {
						class: "hover:bg-b-3 hover:text-c-1 h-fit p-1.25",
						"data-testid": "delete-server-button",
						variant: "ghost",
						onClick: ($event) => openDeleteModal(index)
					}, {
						default: withCtx(() => [createVNode(unref(ScalarIconTrash), { class: "size-3.5" })]),
						_: 1
					}, 8, ["onClick"])]), createElementVNode("div", _hoisted_5, [createVNode(Form_default, {
						data: server,
						environment: __props.environment,
						onUpdate: (key, value) => handleServerUpdate(index, key, value),
						options: FORM_OPTIONS
					}, null, 8, [
						"data",
						"environment",
						"onUpdate"
					]), server.variables ? (openBlock(), createBlock(unref(ServerVariablesForm_default), {
						key: 0,
						variables: server.variables,
						"onUpdate:variable": (name, value) => handleVariableUpdate(index, name, value)
					}, null, 8, ["variables", "onUpdate:variable"])) : createCommentVNode("", true)])]);
				}), 128))]), createElementVNode("div", _hoisted_6, [createVNode(unref(ScalarButton), {
					class: "hover:bg-b-2 hover:text-c-1 flex items-center gap-2",
					size: "sm",
					variant: "ghost",
					onClick: handleAddServer
				}, {
					default: withCtx(() => [createVNode(unref(ScalarIconPlus)), _cache[8] || (_cache[8] = createElementVNode("span", null, "Add Server", -1))]),
					_: 1
				})])], 2)], 2)]),
				_: 2
			}, [isOperation.value ? {
				name: "actions",
				fn: withCtx(() => [createElementVNode("div", _hoisted_1, [createVNode(unref(ScalarToggle), {
					class: "w-4",
					modelValue: useOperationServers.value,
					"onUpdate:modelValue": handleToggleOperationServers
				}, null, 8, ["modelValue"])])]),
				key: "0"
			} : void 0]), 1024), createVNode(unref(ScalarModal), {
				size: "xxs",
				state: unref(deleteModal),
				title: `Delete ${getServerDisplayName(selectedServer.value, selectedServerIndex.value)}`
			}, {
				default: withCtx(() => [createVNode(DeleteSidebarListElement_default, {
					variableName: "Server",
					warningMessage: "Are you sure you want to delete this server? This action cannot be undone.",
					onClose: resetState,
					onDelete: handleDeleteServer
				})]),
				_: 1
			}, 8, ["state", "title"])], 64);
		};
	}
});
//#endregion
export { Servers_vue_vue_type_script_setup_true_lang_default as default };

//# sourceMappingURL=Servers.vue.script.js.map