import { ROUTES } from "../../constants.js";
import { PathId } from "../../routes.js";
import { useActiveEntities } from "../../store/active-entities.js";
import { useWorkspace } from "../../store/store.js";
import { importCurlCommand } from "../../libs/importers/curl.js";
import CommandPaletteCollection_default from "./CommandPaletteCollection.vue.js";
import CommandPaletteExample_default from "./CommandPaletteExample.vue.js";
import CommandPaletteImport_default from "./CommandPaletteImport.vue.js";
import CommandPaletteImportCurl_default from "./CommandPaletteImportCurl.vue.js";
import CommandPaletteServer_default from "./CommandPaletteServer.vue.js";
import CommandPaletteTag_default from "./CommandPaletteTag.vue.js";
import CommandPaletteWorkspace_default from "./CommandPaletteWorkspace.vue.js";
import { Fragment, computed, createBlock, createCommentVNode, createElementBlock, createElementVNode, createTextVNode, createVNode, defineComponent, mergeProps, nextTick, normalizeClass, onBeforeUnmount, onMounted, openBlock, ref, renderList, resolveDynamicComponent, toDisplayString, unref, vShow, watch, withCtx, withDirectives, withKeys, withModifiers } from "vue";
import { ScalarIcon, useModal } from "@scalar/components";
import { useRouter } from "vue-router";
import { Dialog, DialogPanel, DialogTitle } from "@headlessui/vue";
//#region src/components/CommandPalette/TheCommandPalette.vue?vue&type=script&setup=true&lang.ts
var _hoisted_1 = {
	key: 0,
	class: "custom-scroll max-h-[50dvh] min-h-0 flex-1 rounded-lg p-1.5"
};
var _hoisted_2 = { class: "bg-b-2 focus-within:bg-b-1 sticky top-0 flex items-center rounded-md border border-transparent pl-2 shadow-[0_-8px_0_8px_var(--scalar-background-1),0_0_8px_8px_var(--scalar-background-1)] focus-within:border-(--scalar-background-3)" };
var _hoisted_3 = { for: "commandmenu" };
var _hoisted_4 = ["value", "onKeydown"];
var _hoisted_5 = ["onClick"];
var _hoisted_6 = {
	key: 0,
	class: "text-c-3 p-2 pt-3 text-center text-sm"
};
var _hoisted_7 = {
	key: 1,
	class: "flex-1 p-1.5"
};
/**
* The Command Palette
*
* This component is a singleton so should only exist in our app once we will use the event bus to trigger it
*/
var __default__ = { name: "TheCommandPalette" };
var PaletteComponents = {
	"Import from OpenAPI/Swagger/Postman/cURL": CommandPaletteImport_default,
	"Create Request": "",
	"Create Workspace": CommandPaletteWorkspace_default,
	"Add Tag": CommandPaletteTag_default,
	"Add Server": CommandPaletteServer_default,
	"Create Collection": CommandPaletteCollection_default,
	"Add Example": CommandPaletteExample_default,
	"Import from cURL": CommandPaletteImportCurl_default
};
var TheCommandPalette_vue_vue_type_script_setup_true_lang_default = /* @__PURE__ */ defineComponent({
	...__default__,
	setup(__props) {
		const modalState = useModal();
		const router = useRouter();
		const { activeWorkspace, activeWorkspaceCollections, activeCollection } = useActiveEntities();
		const { events, requestMutators } = useWorkspace();
		/** Available Commands for the Command Palette */
		const availableCommands = [
			{
				label: "",
				commands: [
					{
						name: "Import from OpenAPI/Swagger/Postman/cURL",
						icon: "Import"
					},
					{
						name: "Create Request",
						icon: "ExternalLink"
					},
					{
						name: "Create Collection",
						icon: "Collection"
					},
					{
						name: "Add Tag",
						icon: "Folder"
					},
					{
						name: "Add Example",
						icon: "Example"
					},
					{
						name: "Add Server",
						icon: "Server"
					}
				]
			},
			{
				label: "More Actions",
				commands: [
					{
						name: "Create Workspace",
						icon: "Workspace"
					},
					{
						name: "Add Environment",
						icon: "Brackets",
						path: {
							name: "environment.default",
							params: { [PathId.Workspace]: activeWorkspace?.value?.uid ?? "default" },
							query: { openEnvironmentModal: "true" }
						}
					},
					{
						name: "Add Cookie",
						icon: "Cookie",
						path: {
							name: "cookies.default",
							params: { [PathId.Workspace]: activeWorkspace?.value?.uid ?? "default" },
							query: { openCookieModal: "true" }
						}
					}
				]
			},
			{
				label: "Pages",
				commands: ROUTES.map((route) => ({
					name: route.displayName,
					icon: route.icon,
					path: router.resolve({
						...route.to,
						params: { [PathId.Workspace]: activeWorkspace?.value?.uid ?? "default" }
					}).href
				}))
			}
		];
		const metaData = ref();
		const commandQuery = ref("");
		const activeCommand = ref(null);
		const selectedSearchResult = ref(-1);
		const commandRefs = ref([]);
		const searchResultsWithPlaceholderResults = computed(() => availableCommands.reduce((acc, group) => {
			const filteredGroupCommands = group.commands.filter((command) => command.name.toLowerCase().includes(commandQuery.value.toLowerCase()));
			return [...acc, ...filteredGroupCommands];
		}, []));
		/** Reset state on close */
		const closeHandler = () => {
			modalState.hide();
			commandQuery.value = "";
			activeCommand.value = null;
			selectedSearchResult.value = -1;
		};
		/** Reset state on back */
		const backHandler = (event) => {
			if (commandQuery.value !== "") event?.preventDefault();
			activeCommand.value = null;
			nextTick(() => commandInputRef.value?.focus());
		};
		/** Handle execution of the command, some have routes while others show another palette */
		const executeCommand = (command) => {
			if ("path" in command) {
				router.push(command.path);
				closeHandler();
			} else if (command.name === "Create Request") {
				const draftsCollection = activeWorkspaceCollections.value.find((collection) => collection.info?.title === "Drafts");
				if (draftsCollection) {
					const newRequest = requestMutators.add({}, draftsCollection.uid);
					if (newRequest) {
						router.push({
							name: "request",
							params: {
								workspace: activeWorkspace.value?.uid,
								request: newRequest.uid
							}
						});
						closeHandler();
						nextTick(() => {
							events.hotKeys.emit({ focusAddressBar: new KeyboardEvent("keydown", { key: "l" }) });
						});
					}
				} else closeHandler();
			} else activeCommand.value = command.name;
		};
		const commandInputRef = ref();
		/** Handles opening the command pallete to the correct palette */
		const openCommandPalette = ({ commandName, metaData: _metaData } = {}) => {
			activeCommand.value = commandName ?? null;
			metaData.value = _metaData;
			modalState.show();
			nextTick(() => commandInputRef.value?.focus());
		};
		/** Focus on first result when conducting a search */
		watch(commandQuery, (newQuery) => {
			if (newQuery && searchResultsWithPlaceholderResults.value.length > 0) selectedSearchResult.value = 0;
		});
		/** Handle up and down arrow keys in the menu */
		const handleArrowKey = (direction, ev) => {
			if (!modalState.open) return;
			ev.preventDefault();
			const offset = direction === "up" ? -1 : 1;
			const length = searchResultsWithPlaceholderResults.value.length;
			selectedSearchResult.value = (selectedSearchResult.value + offset + length) % length;
			nextTick(() => {
				const container = commandInputRef.value?.closest(".custom-scroll");
				if (!container) return;
				if (selectedSearchResult.value === 0) {
					container.scrollTop = 0;
					return;
				}
				const commandElement = commandRefs.value[selectedSearchResult.value];
				if (!commandElement) return;
				const stickyHeaderHeight = (container.querySelector(".sticky")?.clientHeight || 0) + 16;
				const bottomMargin = 6;
				const elementTop = commandElement.offsetTop;
				const elementBottom = elementTop + commandElement.clientHeight;
				const viewportTop = container.scrollTop + stickyHeaderHeight;
				const viewportBottom = container.scrollTop + container.clientHeight - bottomMargin;
				if (elementTop < viewportTop) container.scrollTop = elementTop - stickyHeaderHeight;
				else if (elementBottom > viewportBottom) container.scrollTop = elementBottom - container.clientHeight + bottomMargin;
			});
		};
		/** The currently selected command */
		const selectedCommand = computed(() => searchResultsWithPlaceholderResults.value[selectedSearchResult.value]);
		/** Handle enter keydown in the menu */
		const handleSelect = (ev) => {
			if (!selectedCommand.value || activeCommand.value) return;
			ev.preventDefault();
			ev.stopPropagation();
			executeCommand(selectedCommand.value);
		};
		/** Handle hotkeys */
		const handleHotKey = (event) => {
			if (!modalState.open) return;
			if (event?.closeModal) closeHandler();
		};
		const handleInput = (value) => {
			if (value.trim().toLowerCase().startsWith("curl")) {
				events.commandPalette.emit({
					commandName: "Import from cURL",
					metaData: {
						parsedCurl: importCurlCommand(value),
						collectionUid: activeCollection.value?.uid
					}
				});
				return;
			}
			commandQuery.value = value;
		};
		onMounted(() => {
			events.commandPalette.on(openCommandPalette);
			events.hotKeys.on(handleHotKey);
		});
		onBeforeUnmount(() => {
			events.commandPalette.off(openCommandPalette);
			events.hotKeys.off(handleHotKey);
		});
		return (_ctx, _cache) => {
			return openBlock(), createBlock(unref(Dialog), {
				open: unref(modalState).open,
				onClose: _cache[5] || (_cache[5] = ($event) => closeHandler())
			}, {
				default: withCtx(() => [_cache[7] || (_cache[7] = createElementVNode("div", { class: "commandmenu-overlay z-overlay" }, null, -1)), createVNode(unref(DialogPanel), { class: "commandmenu z-overlay flex flex-col" }, {
					default: withCtx(() => [createVNode(unref(DialogTitle), { class: "sr-only" }, {
						default: withCtx(() => [..._cache[6] || (_cache[6] = [createTextVNode("API Client Command Menu", -1)])]),
						_: 1
					}), !activeCommand.value ? (openBlock(), createElementBlock("div", _hoisted_1, [
						createElementVNode("div", _hoisted_2, [createElementVNode("label", _hoisted_3, [createVNode(unref(ScalarIcon), {
							class: "text-c-2 mr-2.5",
							icon: "Search",
							size: "md",
							thickness: "1.5"
						})]), createElementVNode("input", {
							id: "commandmenu",
							ref_key: "commandInputRef",
							ref: commandInputRef,
							autocomplete: "off",
							autofocus: "",
							class: "w-full rounded border-none bg-none py-1.5 text-sm focus:outline-none",
							placeholder: "Search commands...",
							type: "text",
							value: commandQuery.value,
							onInput: _cache[0] || (_cache[0] = ($event) => handleInput($event.target.value)),
							onKeydown: [
								_cache[1] || (_cache[1] = withKeys(withModifiers(($event) => handleArrowKey("down", $event), ["stop"]), ["down"])),
								withKeys(withModifiers(handleSelect, ["stop"]), ["enter"]),
								_cache[2] || (_cache[2] = withKeys(withModifiers(($event) => handleArrowKey("up", $event), ["stop"]), ["up"]))
							]
						}, null, 40, _hoisted_4)]),
						(openBlock(), createElementBlock(Fragment, null, renderList(availableCommands, (group) => {
							return openBlock(), createElementBlock(Fragment, { key: group.label }, [withDirectives(createElementVNode("div", { class: "text-c-3 mt-2 mb-1 px-2 text-xs font-medium" }, toDisplayString(group.label), 513), [[vShow, group.commands.filter((command) => command.name.toLowerCase().includes(commandQuery.value.toLowerCase())).length > 0]]), (openBlock(true), createElementBlock(Fragment, null, renderList(group.commands.filter((command) => command.name.toLowerCase().includes(commandQuery.value.toLowerCase())), (command) => {
								return openBlock(), createElementBlock("div", {
									key: command.name,
									ref_for: true,
									ref: (el) => {
										if (el) {
											const index = searchResultsWithPlaceholderResults.value.findIndex((c) => c.name === command.name);
											if (index !== -1) commandRefs.value[index] = el;
										}
									},
									class: normalizeClass(["commandmenu-item hover:bg-b-2 flex cursor-pointer items-center rounded px-2 py-1.5 text-sm", { "bg-b-2": command.name === selectedCommand.value?.name }]),
									onClick: ($event) => executeCommand(command)
								}, [createVNode(unref(ScalarIcon), {
									class: "text-c-2 mr-2.5",
									icon: command.icon,
									size: "md",
									thickness: "1.5"
								}, null, 8, ["icon"]), createTextVNode(" " + toDisplayString(command.name), 1)], 10, _hoisted_5);
							}), 128))], 64);
						}), 64)),
						!searchResultsWithPlaceholderResults.value.length ? (openBlock(), createElementBlock("div", _hoisted_6, " No commands found ")) : createCommentVNode("", true)
					])) : (openBlock(), createElementBlock("div", _hoisted_7, [createElementVNode("button", {
						class: "hover:bg-b-3 text-c-3 active:text-c-1 absolute z-1 mt-[0.5px] rounded p-1.5",
						type: "button",
						onClick: _cache[3] || (_cache[3] = ($event) => activeCommand.value = null)
					}, [createVNode(unref(ScalarIcon), {
						icon: "ChevronLeft",
						size: "md",
						thickness: "1.5"
					})]), (openBlock(), createBlock(resolveDynamicComponent(PaletteComponents[activeCommand.value]), mergeProps(metaData.value ? { metaData: metaData.value } : {}, {
						onBack: _cache[4] || (_cache[4] = ($event) => backHandler($event)),
						onClose: closeHandler
					}), null, 16))]))]),
					_: 1
				})]),
				_: 1
			}, 8, ["open"]);
		};
	}
});
//#endregion
export { TheCommandPalette_vue_vue_type_script_setup_true_lang_default as default };

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