import { useFileDialog } from "../../../../hooks/useFileDialog.js";
import CommandActionForm_default from "./CommandActionForm.vue.js";
import CommandActionInput_default from "./CommandActionInput.vue.js";
import { isUrl } from "../../../helpers/is-url.js";
import { getOpenApiDocumentDetails } from "../helpers/get-openapi-document-details.js";
import { importDocumentToWorkspace } from "../helpers/import-document-to-workspace.js";
import { isPostmanCollection } from "../helpers/is-postman-collection.js";
import { loadDocumentFromSource } from "../helpers/load-document-from-source.js";
import WatchModeToggle_default from "./WatchModeToggle.vue.js";
import { Fragment, computed, createBlock, createCommentVNode, createElementBlock, createElementVNode, createTextVNode, createVNode, defineComponent, openBlock, ref, renderSlot, toDisplayString, unref, watch, withCtx } from "vue";
import { ScalarButton, ScalarCodeBlock, ScalarIcon, ScalarTooltip, useLoadingState } from "@scalar/components";
import { useToasts } from "@scalar/use-toasts";
import { useRouter } from "vue-router";
import { createWorkspaceStore } from "@scalar/workspace-store/client";
import { isLocalUrl } from "@scalar/helpers/url/is-local-url";
//#region src/v2/features/command-palette/components/CommandPaletteImport.vue?vue&type=script&setup=true&lang.ts
var _hoisted_1 = { class: "flex justify-between" };
var _hoisted_2 = { class: "flex w-full flex-row items-center justify-between gap-3" };
var CommandPaletteImport_vue_vue_type_script_setup_true_lang_default = /* @__PURE__ */ defineComponent({
	name: "CommandPaletteImport",
	props: {
		workspaceStore: {},
		eventBus: {},
		fileLoader: {}
	},
	emits: ["close", "back"],
	setup(__props, { emit: __emit }) {
		const emit = __emit;
		const { toast } = useToasts();
		const router = useRouter();
		const loader = useLoadingState();
		const inputContent = ref("");
		const watchMode = ref(false);
		/** Check if the input content is a URL */
		const isUrlInput = computed(() => isUrl(inputContent.value));
		const isLocalUrlInput = computed(() => isUrlInput.value && isLocalUrl(inputContent.value));
		const documentDetails = computed(() => getOpenApiDocumentDetails(inputContent.value));
		/** Get the document type for syntax highlighting */
		const documentType = computed(() => documentDetails.value ? documentDetails.value.type : "json");
		/** Check if the form should be disabled (when input is empty) */
		const isDisabled = computed(() => {
			return !inputContent.value.trim();
		});
		/**
		* Toggle watchMode based on whether the input is a local URL.
		* Only enables watch mode for local URLs, not for files or pasted content.
		*/
		watch(isLocalUrlInput, (value) => {
			watchMode.value = value;
		});
		/**
		* Handles errors during the import process.
		* Shows an error toast, invalidates the loader to show an error state,
		* and closes the command palette modal.
		*
		* @param errorMessage - The error message to display and log
		*/
		const handleImportError = async (errorMessage) => {
			console.error(errorMessage);
			toast(errorMessage, "error");
			await loader.invalidate();
			emit("close");
		};
		/**
		* Directly imports a document into the workspace without showing the modal.
		* This is used when there is only one workspace and it is empty.
		*/
		const handleImport = async (newSource, type) => {
			loader.start();
			const TEMP_DOCUMENT_NAME = "drafts";
			const draftStore = createWorkspaceStore({
				fileLoader: __props.fileLoader,
				meta: { "x-scalar-active-proxy": __props.workspaceStore.workspace["x-scalar-active-proxy"] }
			});
			if (!await loadDocumentFromSource(draftStore, {
				source: newSource,
				type: (() => {
					if (type) return type;
					if (isUrlInput.value) return "url";
					return "raw";
				})()
			}, TEMP_DOCUMENT_NAME, watchMode.value)) return handleImportError("Failed to import document");
			const importResult = await importDocumentToWorkspace({
				workspaceStore: __props.workspaceStore,
				workspaceState: draftStore.exportWorkspace(),
				name: TEMP_DOCUMENT_NAME
			});
			if (!importResult.ok) return handleImportError(importResult.error);
			await loader.validate();
			navigateToDocument(importResult.slug);
			emit("close");
		};
		/** Navigate to the document overview page after successful import */
		const navigateToDocument = (documentName) => {
			router.push({
				name: "document.overview",
				params: { documentSlug: documentName }
			});
		};
		/**
		* Handle file selection and import from file dialog.
		* Reads the file as text and imports it as OpenAPI or Postman collection.
		* Shows loading state during the import process.
		*/
		const { open: openSpecFileDialog } = useFileDialog({
			onChange: (files) => {
				const [file] = files ?? [];
				if (!file) return;
				loader.start();
				const onLoad = async (event) => {
					const text = event.target?.result;
					if (isPostmanCollection(text)) {
						__props.eventBus.emit("ui:open:command-palette", {
							action: "import-postman-collection",
							payload: { inputValue: text }
						});
						await loader.clear();
						return;
					}
					await handleImport(text, "raw");
				};
				const reader = new FileReader();
				reader.onload = onLoad;
				reader.readAsText(file);
			},
			multiple: false,
			accept: ".json,.yaml,.yml"
		});
		/**
		* Handle input changes.
		* Detects cURL commands and redirects to the cURL import command.
		*/
		const handleInput = (value) => {
			const trimmed = value.trim();
			if (trimmed.toLowerCase().startsWith("curl")) return __props.eventBus.emit("ui:open:command-palette", {
				action: "import-curl-command",
				payload: { inputValue: value }
			});
			if (isPostmanCollection(trimmed)) return __props.eventBus.emit("ui:open:command-palette", {
				action: "import-postman-collection",
				payload: { inputValue: value }
			});
			inputContent.value = value;
		};
		/** Handle back navigation when user presses backspace on empty input */
		const handleBack = (event) => {
			emit("back", event);
		};
		return (_ctx, _cache) => {
			return openBlock(), createBlock(CommandActionForm_default, {
				disabled: isDisabled.value,
				loader: unref(loader),
				onSubmit: _cache[2] || (_cache[2] = ($event) => handleImport(inputContent.value))
			}, {
				options: withCtx(() => [createElementVNode("div", _hoisted_2, [renderSlot(_ctx.$slots, "fileUpload", { import: handleImport }, () => [createVNode(unref(ScalarButton), {
					class: "hover:bg-b-2 relative max-h-8 gap-1.5 p-2 text-xs",
					variant: "outlined",
					onClick: unref(openSpecFileDialog)
				}, {
					default: withCtx(() => [_cache[5] || (_cache[5] = createTextVNode(" JSON, or YAML File ", -1)), createVNode(unref(ScalarIcon), {
						class: "text-c-3",
						icon: "Upload",
						size: "md"
					})]),
					_: 1
				}, 8, ["onClick"])]), createVNode(unref(ScalarTooltip), {
					content: isUrlInput.value ? "Watch mode automatically updates the API client when the OpenAPI URL content changes, ensuring your client remains up-to-date." : "Watch mode is only available for URL imports. When enabled it automatically updates the API client when the OpenAPI URL content changes.",
					placement: "bottom"
				}, {
					default: withCtx(() => [createVNode(WatchModeToggle_default, {
						modelValue: watchMode.value,
						"onUpdate:modelValue": _cache[1] || (_cache[1] = ($event) => watchMode.value = $event),
						disabled: !isUrlInput.value
					}, null, 8, ["modelValue", "disabled"])]),
					_: 1
				}, 8, ["content"])])]),
				submit: withCtx(() => [_cache[6] || (_cache[6] = createTextVNode(" Import ", -1)), isUrlInput.value ? (openBlock(), createElementBlock(Fragment, { key: 0 }, [createTextVNode("from URL")], 64)) : documentDetails.value && documentType.value ? (openBlock(), createElementBlock(Fragment, { key: 1 }, [documentDetails.value.title ? (openBlock(), createElementBlock(Fragment, { key: 0 }, [createTextVNode(" \"" + toDisplayString(documentDetails.value.title) + "\" ", 1)], 64)) : (openBlock(), createElementBlock(Fragment, { key: 1 }, [createTextVNode(toDisplayString(documentDetails.value.version), 1)], 64))], 64)) : (openBlock(), createElementBlock(Fragment, { key: 2 }, [createTextVNode("Collection")], 64))]),
				default: withCtx(() => [!documentDetails.value || isUrlInput.value ? (openBlock(), createBlock(CommandActionInput_default, {
					key: 0,
					modelValue: inputContent.value,
					placeholder: "OpenAPI/Swagger/Postman URL or cURL",
					onDelete: handleBack,
					"onUpdate:modelValue": handleInput
				}, null, 8, ["modelValue"])) : (openBlock(), createElementBlock(Fragment, { key: 1 }, [createElementVNode("div", _hoisted_1, [_cache[4] || (_cache[4] = createElementVNode("div", { class: "text-c-2 min-h-8 w-full py-2 pl-12 text-center text-xs" }, " Preview ", -1)), createVNode(unref(ScalarButton), {
					class: "hover:bg-b-2 relative ml-auto max-h-8 gap-1.5 p-2 text-xs",
					variant: "ghost",
					onClick: _cache[0] || (_cache[0] = ($event) => inputContent.value = "")
				}, {
					default: withCtx(() => [..._cache[3] || (_cache[3] = [createTextVNode(" Clear ", -1)])]),
					_: 1
				})]), documentDetails.value && !isUrlInput.value ? (openBlock(), createBlock(unref(ScalarCodeBlock), {
					key: 0,
					class: "bg-b-2 mt-1 max-h-[40dvh] rounded border px-2 py-1 text-sm",
					content: inputContent.value,
					copy: false,
					lang: documentType.value
				}, null, 8, ["content", "lang"])) : createCommentVNode("", true)], 64))]),
				_: 3
			}, 8, ["disabled", "loader"]);
		};
	}
});
//#endregion
export { CommandPaletteImport_vue_vue_type_script_setup_true_lang_default as default };

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