import ExamplePicker_default from "./ExamplePicker.vue.js";
import { operationToHar } from "../helpers/operation-to-har/operation-to-har.js";
import HttpMethod_default from "./HttpMethod.vue.js";
import { filterClientsByQuery } from "../helpers/filter-clients-by-query.js";
import { findClient } from "../helpers/find-client.js";
import { getClients } from "../helpers/get-clients.js";
import { getCustomCodeSamples } from "../helpers/get-custom-code-samples.js";
import { getSecrets } from "../helpers/get-secrets.js";
import { generateCodeSnippet } from "../helpers/generate-code-snippet.js";
import { computed, createBlock, createCommentVNode, createElementBlock, createElementVNode, createSlots, createTextVNode, createVNode, defineComponent, mergeModels, onBeforeMount, openBlock, ref, renderSlot, toDisplayString, unref, useId, useModel, watch, withCtx } from "vue";
import { ScalarButton, ScalarCard, ScalarCardFooter, ScalarCardHeader, ScalarCardSection, ScalarCodeBlock, ScalarCombobox, ScalarVirtualText } from "@scalar/components";
import { ScalarIconCaretDown } from "@scalar/icons";
import { getResolvedRef } from "@scalar/workspace-store/helpers/get-resolved-ref";
import { freezeElement } from "@scalar/helpers/dom/freeze-element";
//#region src/v2/blocks/operation-code-sample/components/OperationCodeSample.vue?vue&type=script&setup=true&lang.ts
var _hoisted_1 = ["innerHTML"];
var _hoisted_2 = ["id"];
var _hoisted_3 = {
	key: 0,
	class: "request-card-footer-addon"
};
var _hoisted_4 = { class: "request-header" };
var OperationCodeSample_vue_vue_type_script_setup_true_lang_default = /* @__PURE__ */ defineComponent({
	__name: "OperationCodeSample",
	props: /* @__PURE__ */ mergeModels({
		integration: {},
		clientOptions: {},
		selectedClient: {},
		selectedServer: { default: null },
		selectedContentType: {},
		selectedExample: {},
		eventBus: {},
		securitySchemes: { default: () => [] },
		method: {},
		path: {},
		operation: {},
		fallback: { type: Boolean },
		generateLabel: { type: Function },
		isWebhook: { type: Boolean },
		globalCookies: {},
		requestBodyCompositionSelection: {}
	}, {
		"selectedExample": { default: "" },
		"selectedExampleModifiers": {}
	}),
	emits: ["update:selectedExample"],
	setup(__props) {
		/** Grab the examples for the given content type */
		const requestBodyExamples = computed(() => {
			const content = getResolvedRef(__props.operation.requestBody)?.content ?? {};
			const contentType = __props.selectedContentType || Object.keys(content)[0];
			if (!contentType) return {};
			return content[contentType]?.examples ?? {};
		});
		/** The currently selected example key with v-model support */
		const selectedExampleKey = useModel(__props, "selectedExample");
		onBeforeMount(() => {
			selectedExampleKey.value ||= Object.keys(requestBodyExamples.value)[0] ?? "";
		});
		/** Grab any custom code samples from the operation */
		const customCodeSamples = computed(() => getCustomCodeSamples(__props.operation));
		/** Merge custom code samples with the client options */
		const clients = computed(() => getClients(customCodeSamples.value, __props.clientOptions));
		/** The locally selected client which would include code samples from this operation only */
		const localSelectedClient = ref(findClient(clients.value, __props.selectedClient));
		/** If the globally selected client changes we can update the local one */
		watch(() => __props.selectedClient, (newClient) => {
			const client = findClient(clients.value, newClient);
			if (client) localSelectedClient.value = client;
		});
		/** Generate HAR data for webhook requests */
		const webhookHar = computed(() => {
			if (!__props.isWebhook) return null;
			try {
				return operationToHar({
					operation: __props.operation,
					method: __props.method,
					path: __props.path,
					example: selectedExampleKey.value,
					requestBodyCompositionSelection: __props.requestBodyCompositionSelection
				});
			} catch (error) {
				console.error("[webhookHar]", error);
				return null;
			}
		});
		/** Generate the code snippet for the selected example */
		const generatedCode = computed(() => {
			if (__props.isWebhook) return webhookHar.value?.postData?.text ?? "";
			return generateCodeSnippet({
				includeDefaultHeaders: __props.integration === "client",
				clientId: localSelectedClient.value?.id,
				customCodeSamples: customCodeSamples.value,
				operation: __props.operation,
				method: __props.method,
				path: __props.path,
				contentType: __props.selectedContentType,
				server: __props.selectedServer,
				securitySchemes: __props.securitySchemes,
				example: selectedExampleKey.value,
				globalCookies: __props.globalCookies,
				requestBodyCompositionSelection: __props.requestBodyCompositionSelection
			});
		});
		/** The language for the code block, used for syntax highlighting */
		const codeBlockLanguage = computed(() => {
			if (__props.isWebhook) return webhookLanguage.value;
			return localSelectedClient.value?.lang;
		});
		/** Determine the language for webhook content based on MIME type */
		const webhookLanguage = computed(() => {
			if (!webhookHar.value?.postData) return "json";
			const contentType = webhookHar.value.postData.mimeType;
			if (contentType?.includes("json")) return "json";
			if (contentType?.includes("xml")) return "xml";
			if (contentType?.includes("yaml") || contentType?.includes("yml")) return "yaml";
			if (contentType?.includes("text/plain")) return "text";
			return "json";
		});
		/**  Block secrets from being shown in the code block */
		const secretCredentials = computed(() => getSecrets(__props.securitySchemes));
		/** Grab the ref to freeze the ui as the clients change so there's no jump as the size of the dom changes */
		const elem = ref(null);
		/** Set custom example, or update the selected HTTP client globally */
		const selectClient = (option) => {
			if (elem.value) {
				const unfreeze = freezeElement(elem.value.$el);
				setTimeout(() => {
					unfreeze();
				}, 300);
			}
			localSelectedClient.value = option;
			if (option && !option.id.startsWith("custom")) __props.eventBus.emit("workspace:update:selected-client", option.id);
		};
		const VIRTUALIZATION_THRESHOLD = 2e4;
		const shouldVirtualize = computed(() => (generatedCode.value.length ?? 0) > VIRTUALIZATION_THRESHOLD);
		const id = useId();
		return (_ctx, _cache) => {
			return generatedCode.value ? (openBlock(), createBlock(unref(ScalarCard), {
				key: 0,
				ref_key: "elem",
				ref: elem,
				class: "request-card dark-mode"
			}, {
				default: withCtx(() => [
					createVNode(unref(ScalarCardHeader), { class: "pr-2.5" }, createSlots({
						default: withCtx(() => [
							_cache[2] || (_cache[2] = createElementVNode("span", { class: "sr-only" }, "Request Example for", -1)),
							createVNode(HttpMethod_default, {
								as: "span",
								class: "request-method",
								method: __props.method
							}, null, 8, ["method"]),
							__props.generateLabel ? (openBlock(), createElementBlock("span", {
								key: 0,
								innerHTML: __props.generateLabel()
							}, null, 8, _hoisted_1)) : createCommentVNode("", true),
							renderSlot(_ctx.$slots, "header", {}, void 0, true)
						]),
						_: 2
					}, [!__props.isWebhook && clients.value.length ? {
						name: "actions",
						fn: withCtx(() => [createVNode(unref(ScalarCombobox), {
							class: "max-h-80",
							filterFn: unref(filterClientsByQuery),
							modelValue: localSelectedClient.value,
							options: clients.value,
							placement: "bottom-end",
							teleport: "",
							"onUpdate:modelValue": _cache[0] || (_cache[0] = ($event) => selectClient($event))
						}, {
							default: withCtx(() => [createVNode(unref(ScalarButton), {
								class: "text-c-2 hover:text-c-1 flex h-full w-fit gap-1.5 px-0.5 py-0 text-base font-normal",
								"data-testid": "client-picker",
								variant: "ghost"
							}, {
								default: withCtx(() => [createTextVNode(toDisplayString(localSelectedClient.value?.title) + " ", 1), createVNode(unref(ScalarIconCaretDown), {
									class: "ui-open:rotate-180 mt-px size-3 transition-transform duration-100",
									weight: "bold"
								})]),
								_: 1
							})]),
							_: 1
						}, 8, [
							"filterFn",
							"modelValue",
							"options"
						])]),
						key: "0"
					} : void 0]), 1024),
					createVNode(unref(ScalarCardSection), { class: "request-editor-section custom-scroll p-0" }, {
						default: withCtx(() => [createElementVNode("div", {
							id: `${unref(id)}-example`,
							class: "code-snippet"
						}, [!shouldVirtualize.value ? (openBlock(), createBlock(unref(ScalarCodeBlock), {
							key: 0,
							class: "bg-b-2 h-full",
							content: generatedCode.value,
							hideCredentials: secretCredentials.value,
							lang: codeBlockLanguage.value,
							lineNumbers: ""
						}, null, 8, [
							"content",
							"hideCredentials",
							"lang"
						])) : (openBlock(), createBlock(unref(ScalarVirtualText), {
							key: 1,
							containerClass: "custom-scroll scalar-code-block border rounded-b flex flex-1 max-h-screen",
							contentClass: "language-plaintext whitespace-pre font-code text-base",
							lineHeight: 20,
							text: generatedCode.value
						}, null, 8, ["text"]))], 8, _hoisted_2)]),
						_: 1
					}),
					Object.keys(requestBodyExamples.value).length > 1 || _ctx.$slots.footer ? (openBlock(), createBlock(unref(ScalarCardFooter), {
						key: 0,
						class: "request-card-footer bg-b-3"
					}, {
						default: withCtx(() => [Object.keys(requestBodyExamples.value).length > 1 ? (openBlock(), createElementBlock("div", _hoisted_3, [Object.keys(requestBodyExamples.value).length ? (openBlock(), createBlock(ExamplePicker_default, {
							key: 0,
							modelValue: selectedExampleKey.value,
							"onUpdate:modelValue": _cache[1] || (_cache[1] = ($event) => selectedExampleKey.value = $event),
							examples: requestBodyExamples.value
						}, null, 8, ["modelValue", "examples"])) : createCommentVNode("", true)])) : createCommentVNode("", true), renderSlot(_ctx.$slots, "footer", { exampleName: selectedExampleKey.value }, void 0, true)]),
						_: 3
					})) : createCommentVNode("", true)
				]),
				_: 3
			}, 512)) : __props.fallback ? (openBlock(), createBlock(unref(ScalarCard), {
				key: 1,
				class: "request-card dark-mode"
			}, {
				default: withCtx(() => [createVNode(unref(ScalarCardSection), { class: "request-card-simple" }, {
					default: withCtx(() => [createElementVNode("div", _hoisted_4, [createVNode(HttpMethod_default, {
						as: "span",
						class: "request-method",
						method: __props.method
					}, null, 8, ["method"]), renderSlot(_ctx.$slots, "header", {}, void 0, true)]), renderSlot(_ctx.$slots, "footer", { exampleName: selectedExampleKey.value }, void 0, true)]),
					_: 3
				})]),
				_: 3
			})) : createCommentVNode("", true);
		};
	}
});
//#endregion
export { OperationCodeSample_vue_vue_type_script_setup_true_lang_default as default };

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