import { defineComponent as X, useId as Y, computed as m, ref as B, watch as Z, unref as a, openBlock as d, createBlock as x, withCtx as n, createVNode as s, createElementBlock as K, Fragment as j, createTextVNode as p, toDisplayString as h, createElementVNode as k, renderSlot as y, createCommentVNode as E } from "vue";
import { useWorkspace as _ } from "@scalar/api-client/store";
import { getSnippet as ee } from "@scalar/api-client/views/Components/CodeSnippet";
import { filterSecurityRequirements as te } from "@scalar/api-client/views/Request/RequestSection";
import { ScalarCodeBlock as le } from "@scalar/components";
import b from "../../components/ScreenReader.vue.js";
import { freezeElement as ae } from "../../helpers/freeze-element.js";
import { useConfig as oe } from "../../hooks/useConfig.js";
import re from "./ExamplePicker.vue.js";
import ne from "./TextSelect.vue.js";
/* empty css                */
import w from "../../components/Card/Card.vue.js";
import se from "../../components/Card/CardHeader.vue.js";
import H from "../../components/HttpMethod/HttpMethod.vue.js";
import R from "../../components/Card/CardContent.vue.js";
import ie from "../../components/Card/CardFooter.vue.js";
import { useExampleStore as ue } from "../../legacy/stores/useExampleStore.js";
import { useHttpClientStore as ce } from "../../stores/useHttpClientStore.js";
const me = ["id"], de = ["id"], pe = {
  key: 0,
  class: "request-card-footer-addon"
}, fe = { class: "request-header" }, je = /* @__PURE__ */ X({
  __name: "ExampleRequest",
  props: {
    operation: {},
    server: {},
    collection: {},
    fallback: { type: Boolean },
    transformedOperation: {}
  },
  setup(o) {
    const { selectedExampleKey: S, operationId: J } = ue(), { requestExamples: C, securitySchemes: q, requestExampleMutators: U } = _(), F = oe(), {
      httpClient: i,
      setHttpClient: I,
      availableTargets: O,
      httpTargetTitle: M,
      httpClientTitle: z
    } = ce(), f = Y(), u = m(() => {
      var t;
      const e = ["x-custom-examples", "x-codeSamples", "x-code-samples"];
      for (const l of e)
        if ((t = o.transformedOperation.information) != null && t[l])
          return [...o.transformedOperation.information[l]];
      return [];
    }), r = B(
      // Default to first custom example
      u.value.length ? {
        targetKey: "customExamples",
        clientKey: 0
      } : (
        // Otherwise use the globally selected HTTP client
        {
          targetKey: i.targetKey,
          clientKey: i.clientKey
        }
      )
    );
    Z(i, () => {
      r.value = {
        targetKey: i.targetKey,
        clientKey: i.clientKey
      };
    });
    const $ = m(() => {
      const e = v.value;
      return Object.keys(e).length > 1;
    }), P = () => {
      var T;
      if (r.value.targetKey === "customExamples")
        return ((T = u.value[r.value.clientKey]) == null ? void 0 : T.source) ?? "";
      const e = i.clientKey, t = i.targetKey, l = C[o.operation.examples[0]];
      if (!l)
        return "";
      const c = te(
        o.operation.security || o.collection.security,
        o.collection.selectedSecuritySchemeUids,
        q
      ), [V, Q] = ee(t, e, {
        operation: o.operation,
        example: l,
        server: o.server,
        securitySchemes: c
      });
      return V ? V.message ?? "" : Q;
    }, N = m(() => {
      try {
        return P();
      } catch (e) {
        return console.error("[generateSnippet]", e), "";
      }
    }), v = m(() => {
      var l, c;
      const e = ((c = (l = o.transformedOperation.information) == null ? void 0 : l.requestBody) == null ? void 0 : c.content) ?? {}, t = Object.values(e)[0];
      return (t == null ? void 0 : t.examples) ?? {};
    }), D = m(() => {
      var t, l;
      const e = (
        // Specified language
        ((t = r.value) == null ? void 0 : t.targetKey) === "customExamples" ? ((l = u.value[r.value.clientKey]) == null ? void 0 : l.lang) ?? "plaintext" : (
          // Or language for the globally selected HTTP client
          i.targetKey
        )
      );
      return e === "shell" && N.value.includes("curl") ? "curl" : e === "Objective-C" ? "objc" : e;
    }), W = m(
      () => Object.values(q).flatMap((e) => e.type === "apiKey" ? e.value : (e == null ? void 0 : e.type) === "http" ? [
        e.token,
        e.password,
        btoa(`${e.username}:${e.password}`)
      ] : e.type === "oauth2" ? Object.values(e.flows).map((t) => t.token) : [])
    ), A = m(() => {
      const e = O.value.map((t) => ({
        value: t.key,
        label: t.title,
        options: t.clients.map((l) => ({
          value: JSON.stringify({
            targetKey: t.key,
            clientKey: l.client
          }),
          label: l.title
        }))
      }));
      return u.value.length && e.unshift({
        value: "customExamples",
        label: "Examples",
        options: u.value.map((t, l) => ({
          value: JSON.stringify({
            targetKey: "customExamples",
            clientKey: l
          }),
          label: t.label ?? t.lang ?? `Example #${l + 1}`
        }))
      }), e;
    }), g = B(null);
    function G(e) {
      const t = JSON.parse(e);
      if (g.value) {
        const l = ae(g.value.$el);
        setTimeout(() => {
          l();
        }, 300);
      }
      t.targetKey === "customExamples" || r.value.targetKey === "customExamples" && t.targetKey === i.targetKey && t.clientKey === i.clientKey ? r.value = t : I(t);
    }
    function L(e) {
      S.value = e, J.value = o.operation.operationId;
      const t = C[o.operation.examples[0]], l = v.value[e];
      if (t && (l != null && l.value))
        try {
          U.edit(
            t.uid,
            "body.raw.value",
            JSON.stringify(l.value, null, 2)
          );
        } catch (c) {
          console.error("[handleExampleUpdate]", c);
        }
    }
    return (e, t) => a(O).length || u.value.length ? (d(), x(a(w), {
      key: 0,
      "aria-labelledby": `${a(f)}-header`,
      class: "dark-mode",
      ref_key: "elem",
      ref: g,
      role: "region"
    }, {
      default: n(() => [
        s(a(se), { muted: "" }, {
          actions: n(() => [
            s(ne, {
              class: "request-client-picker",
              controls: `${a(f)}-example`,
              modelValue: JSON.stringify(r.value),
              options: A.value,
              "onUpdate:modelValue": G
            }, {
              default: n(() => [
                r.value.targetKey === "customExamples" ? (d(), K(j, { key: 0 }, [
                  s(b, null, {
                    default: n(() => t[1] || (t[1] = [
                      p("Selected Example:")
                    ])),
                    _: 1
                  }),
                  p(" " + h(u.value[r.value.clientKey].label ?? "Example"), 1)
                ], 64)) : (d(), K(j, { key: 1 }, [
                  s(b, null, {
                    default: n(() => t[2] || (t[2] = [
                      p("Selected HTTP client:")
                    ])),
                    _: 1
                  }),
                  p(" " + h(a(M)) + " " + h(a(z)), 1)
                ], 64))
              ]),
              _: 1
            }, 8, ["controls", "modelValue", "options"])
          ]),
          default: n(() => [
            k("div", {
              id: `${a(f)}-header`,
              class: "request-header"
            }, [
              s(b, null, {
                default: n(() => t[0] || (t[0] = [
                  p("Request Example for")
                ])),
                _: 1
              }),
              s(a(H), {
                as: "span",
                class: "request-method",
                method: e.operation.method
              }, null, 8, ["method"]),
              y(e.$slots, "header", {}, void 0, !0)
            ], 8, me)
          ]),
          _: 3
        }),
        s(a(R), {
          borderless: "",
          class: "request-editor-section custom-scroll",
          frameless: ""
        }, {
          default: n(() => [
            k("div", {
              id: `${a(f)}-example`,
              class: "code-snippet"
            }, [
              s(a(le), {
                class: "bg-b-2 -outline-offset-2",
                content: N.value,
                hideCredentials: W.value,
                lang: D.value,
                lineNumbers: ""
              }, null, 8, ["content", "hideCredentials", "lang"])
            ], 8, de)
          ]),
          _: 1
        }),
        ($.value || !a(F).hideTestRequestButton) && e.$slots.footer ? (d(), x(a(ie), {
          key: 0,
          class: "request-card-footer",
          contrast: ""
        }, {
          default: n(() => [
            $.value ? (d(), K("div", pe, [
              s(re, {
                class: "request-example-selector",
                examples: v.value,
                modelValue: a(S),
                "onUpdate:modelValue": L
              }, null, 8, ["examples", "modelValue"])
            ])) : E("", !0),
            y(e.$slots, "footer", {}, void 0, !0)
          ]),
          _: 3
        })) : E("", !0)
      ]),
      _: 3
    }, 8, ["aria-labelledby"])) : e.fallback ? (d(), x(a(w), {
      key: 1,
      class: "dark-mode"
    }, {
      default: n(() => [
        s(a(R), { class: "request-card-simple" }, {
          default: n(() => [
            k("div", fe, [
              s(a(H), {
                as: "span",
                class: "request-method",
                method: e.operation.method
              }, null, 8, ["method"]),
              y(e.$slots, "header", {}, void 0, !0)
            ]),
            y(e.$slots, "footer", {}, void 0, !0)
          ]),
          _: 3
        })
      ]),
      _: 3
    })) : E("", !0);
  }
});
export {
  je as default
};
