import { defineComponent as ue, ref as G, shallowRef as de, computed as C, onMounted as me, onBeforeUnmount as fe, watch as x, nextTick as H, createElementBlock as X, unref as o, openBlock as k, normalizeClass as D, createElementVNode as a, createVNode as r, withCtx as m, createTextVNode as q, toDisplayString as Q, createBlock as Z } from "vue";
import { useLoadingState as pe, ScalarButton as f, ScalarHotkey as j } from "@scalar/components";
import { debounce as ve } from "@scalar/helpers/general/debounce";
import { isObject as I } from "@scalar/helpers/object/is-object";
import { ScalarIconArrowsIn as ge, ScalarIconArrowsOut as ye } from "@scalar/icons";
import * as c from "monaco-editor/esm/vs/editor/editor.api.js";
import { createJsonModel as he } from "../../../editor/helpers/json/create-json-model.js";
import { createYamlModel as xe } from "../../../editor/helpers/yaml/create-yaml-model.js";
import { useEditorMarkers as we } from "../../../editor/hooks/use-editor-markers.js";
import be from "./components/EditorDiagnosticsPanel.vue.js";
import Se from "./components/EditorSavePanel.vue.js";
import { getDiagnosticCounts as Ee } from "./helpers/get-diagnostic-counts.js";
import { getOperationContext as V } from "./helpers/get-operation-context.js";
import { getVisibleDiagnostics as Ce } from "./helpers/get-visible-diagnostics.js";
import { parseEditorObject as T } from "./helpers/parse-editor-object.js";
import { stringifyDocument as B } from "./helpers/stringify-document.js";
import { useEditorState as ke } from "./hooks/use-editor-state.js";
import { useJsonPointerLinkSupport as De } from "../../../editor/hooks/use-json-pointer-link-support.js";
import { useEditor as Me } from "../../../editor/hooks/use-editor.js";
const Oe = { class: "grid grid-cols-[minmax(0,1fr)_auto_minmax(0,1fr)] items-center gap-3" }, Ae = { class: "flex min-w-0 items-center gap-1 overflow-x-auto whitespace-nowrap" }, Ne = { class: "text-c-3 ml-2 text-[11px]" }, ze = { class: "text-c-3 ml-2 text-[11px]" }, Le = {
  "aria-label": "Editor language",
  class: "bg-b-1 shadow-border flex items-center justify-self-center overflow-hidden rounded-lg p-0.5",
  role: "tablist"
}, je = { class: "flex min-w-0 shrink-0 items-center gap-2 justify-self-end" }, Ie = { class: "text-c-3 ml-2 text-[11px]" }, Ve = { class: "text-c-3 ml-2 text-[11px]" }, Te = { class: "flex min-h-0 w-full min-w-0 flex-1 rounded-lg border" }, Be = { class: "pointer-events-none absolute top-2 right-2 z-10" }, Ke = { key: 1 }, Pe = 6, ee = "editor:replace-document", st = /* @__PURE__ */ ue({
  __name: "Editor",
  props: {
    documentSlug: {},
    document: {},
    eventBus: {},
    layout: {},
    path: {},
    method: {},
    exampleName: {},
    environment: {},
    securitySchemes: {},
    workspaceStore: {},
    activeWorkspace: {},
    plugins: {},
    customThemes: {},
    currentTheme: {},
    isDarkMode: { type: Boolean },
    fetchRegistryDocument: { type: Function },
    collectionType: {}
  },
  setup(s) {
    const K = G(), i = de(), w = pe(), {
      isAutoSaveEnabled: p,
      isDirty: l,
      editorLanguage: u,
      isDiagnosticsPaneExpanded: b,
      isEditorMaximized: S,
      isYamlMode: v,
      editorBottomPadding: te,
      editorRootClass: oe,
      getLanguageToggleClass: P,
      toggleEditorMaximized: ae
    } = ke(), M = he(), O = xe(), E = G("json"), A = C(() => E.value === "json" ? M : O), se = C(() => i.value?.editor), { markers: N } = we(se), F = () => {
      i.value?.editor.updateOptions({
        padding: {
          top: 0,
          bottom: te.value
        }
      });
    }, ne = C(() => Ee(N.value)), ie = C(
      () => Ce(N.value, Pe)
    ), R = (t) => {
      const e = i.value?.editor;
      e && (e.setSelection({
        startLineNumber: t.startLineNumber,
        startColumn: t.startColumn,
        endLineNumber: t.endLineNumber,
        endColumn: t.endColumn
      }), e.revealPositionInCenter({
        lineNumber: t.startLineNumber,
        column: t.startColumn
      }));
    }, z = () => A.value.model.getValue(), re = (t) => (t === "json" ? M : O).model.getValue(), le = async (t) => {
      const e = await s.workspaceStore.getEditableDocument(s.documentSlug);
      return B(e, E.value);
    }, g = ve({ delay: 1500 }), Y = (t) => {
      g.cleanup(), i.value?.setValue(t, !0);
    }, $ = async () => {
      Y(await le()), l.value = !1, await d();
    }, J = async () => {
      await i.value?.formatDocument();
    }, d = async () => {
      const t = V(s.path, s.method);
      t && await i.value?.focusPath([
        "paths",
        t.path,
        t.method
      ]);
    }, L = async (t) => {
      const e = T(t, u.value);
      if (!e) {
        const n = N.value.find(
          (y) => y.severity === c.MarkerSeverity.Error
        );
        n && R(n), await w.invalidate();
        return;
      }
      w.start(), await s.workspaceStore.replaceDocument(s.documentSlug, e), l.value = !1, await w.validate({ duration: 900 });
    }, U = async () => {
      const t = z();
      t && await L(t);
    }, ce = (t) => {
      l.value = !0, p.value && g.execute(
        ee,
        () => L(t)
      );
    }, W = async () => {
      const t = V(s.path, s.method);
      if (!t)
        return;
      const e = z();
      if (!e)
        return;
      const n = T(e, u.value);
      if (!n || !I(n.paths))
        return;
      const h = n.paths[t.path];
      if (!I(h))
        return;
      const _ = h[t.method];
      I(_) && (_.servers ??= [], i.value?.setValue(B(n, u.value)), await i.value?.focusPath([
        "paths",
        t.path,
        t.method,
        "servers"
      ]));
    };
    return De(i, A), me(() => {
      i.value = Me({
        element: K.value ?? document.createElement("div"),
        onChange: ce,
        model: A,
        actions: [
          {
            id: "scalar.editor.focusOperation",
            label: "Focus Operation",
            keybindings: [c.KeyMod.Alt | c.KeyCode.KeyO],
            run: async () => {
              await d();
            }
          },
          {
            id: "scalar.editor.focusOperationServers",
            label: "Focus Operation Servers",
            keybindings: [c.KeyMod.Alt | c.KeyCode.KeyS],
            run: async () => {
              await W();
            }
          },
          {
            id: "scalar.editor.formatDocument",
            label: "Format Document",
            keybindings: [
              c.KeyMod.Alt | c.KeyMod.Shift | c.KeyCode.KeyF
            ],
            run: async () => {
              await J();
            }
          }
        ]
      }), F(), $();
    }), fe(() => {
      g.cleanup(), l.value && p.value && U(), i.value?.dispose?.(), M.model.dispose(), O.model.dispose();
    }), x(() => s.documentSlug, $), x(
      () => [s.path, s.method],
      async () => {
        await d();
      }
    ), x(b, () => {
      F();
    }), x(u, async (t, e) => {
      const n = l.value, y = re(e ?? "json");
      if (!y) {
        E.value = t, await H(), await d();
        return;
      }
      const h = T(y, e ?? "json");
      E.value = t, await H(), h && (Y(B(h, t)), l.value = n), await d();
    }), x(
      p,
      (t) => {
        if (!t) {
          g.cleanup();
          return;
        }
        if (l.value) {
          const e = z();
          if (!e)
            return;
          g.execute(
            ee,
            () => L(e)
          );
        }
      },
      { flush: "post" }
    ), (t, e) => s.collectionType === "operation" && o(V)(s.path, s.method) !== null ? (k(), X("div", {
      key: 0,
      class: D(["flex w-full min-w-0 flex-1 flex-col gap-2", o(oe)])
    }, [
      a("div", Oe, [
        a("div", Ae, [
          e[6] || (e[6] = a("span", { class: "text-c-2 text-xs font-medium whitespace-nowrap" }, " Shortcuts ", -1)),
          r(o(f), {
            class: "whitespace-nowrap",
            size: "xs",
            variant: "ghost",
            onClick: d
          }, {
            default: m(() => [
              e[4] || (e[4] = a("span", null, "Operation", -1)),
              a("span", Ne, [
                r(o(j), {
                  hotkey: "O",
                  modifier: ["Alt"]
                })
              ])
            ]),
            _: 1
          }),
          r(o(f), {
            class: "whitespace-nowrap",
            size: "xs",
            variant: "ghost",
            onClick: W
          }, {
            default: m(() => [
              e[5] || (e[5] = a("span", null, "Servers", -1)),
              a("span", ze, [
                r(o(j), {
                  hotkey: "S",
                  modifier: ["Alt"]
                })
              ])
            ]),
            _: 1
          })
        ]),
        a("div", Le, [
          r(o(f), {
            "aria-selected": !o(v),
            class: D(o(P)(!o(v))),
            role: "tab",
            size: "xs",
            type: "button",
            variant: "ghost",
            onClick: e[0] || (e[0] = (n) => u.value = "json")
          }, {
            default: m(() => [...e[7] || (e[7] = [
              q(" JSON ", -1)
            ])]),
            _: 1
          }, 8, ["aria-selected", "class"]),
          r(o(f), {
            "aria-selected": o(v),
            class: D(o(P)(o(v))),
            role: "tab",
            size: "xs",
            type: "button",
            variant: "ghost",
            onClick: e[1] || (e[1] = (n) => u.value = "yaml")
          }, {
            default: m(() => [...e[8] || (e[8] = [
              q(" YAML ", -1)
            ])]),
            _: 1
          }, 8, ["aria-selected", "class"])
        ]),
        a("div", je, [
          r(o(f), {
            size: "xs",
            variant: "ghost",
            onClick: J
          }, {
            default: m(() => [
              a("span", null, "Format " + Q(o(v) ? "YAML" : "JSON"), 1),
              a("span", Ie, [
                r(o(j), {
                  hotkey: "F",
                  modifier: ["Alt", "Shift"]
                })
              ])
            ]),
            _: 1
          }),
          r(o(f), {
            "aria-label": o(S) ? "Restore editor size" : "Maximize editor",
            size: "xs",
            variant: "ghost",
            onClick: o(ae)
          }, {
            default: m(() => [
              a("span", null, Q(o(S) ? "Restore" : "Maximize"), 1),
              a("span", Ve, [
                o(S) ? (k(), Z(o(ge), {
                  key: 0,
                  class: "size-3.5"
                })) : (k(), Z(o(ye), {
                  key: 1,
                  class: "size-3.5"
                }))
              ])
            ]),
            _: 1
          }, 8, ["aria-label", "onClick"])
        ])
      ]),
      a("div", Te, [
        a("div", {
          class: D(["relative w-full min-w-0 flex-1", o(S) ? "h-full min-h-0" : "h-[500px]"])
        }, [
          a("div", Be, [
            r(Se, {
              isAutoSaveEnabled: o(p),
              isDirty: o(l),
              saveLoader: o(w),
              onSaveNow: U,
              "onUpdate:isAutoSaveEnabled": e[2] || (e[2] = (n) => p.value = n)
            }, null, 8, ["isAutoSaveEnabled", "isDirty", "saveLoader"])
          ]),
          r(be, {
            diagnosticCounts: ne.value,
            expanded: o(b),
            visibleDiagnostics: ie.value,
            onFocusDiagnostic: R,
            onToggle: e[3] || (e[3] = (n) => b.value = !o(b))
          }, null, 8, ["diagnosticCounts", "expanded", "visibleDiagnostics"]),
          a("div", {
            ref_key: "monacoEditorRef",
            ref: K,
            class: "h-full w-full min-w-0 flex-1"
          }, null, 512)
        ], 2)
      ])
    ], 2)) : (k(), X("div", Ke, "No operation context found"));
  }
});
export {
  st as default
};
