import { defineComponent as P, computed as f, ref as B, createElementBlock as x, openBlock as u, Fragment as W, createElementVNode as o, createVNode as l, createBlock as p, createCommentVNode as w, withCtx as a, unref as n, resolveDynamicComponent as Y, mergeProps as q, createTextVNode as S } from "vue";
import { useModal as T, ScalarButton as d, ScalarModal as V } from "@scalar/components";
import { ScalarIconFloppyDisk as M, ScalarIconSpinner as L, ScalarIconCloudArrowDown as O, ScalarIconWarning as G } from "@scalar/icons";
import { LibraryIcon as H } from "@scalar/icons/library";
import { apply as J } from "@scalar/json-magic/diff";
import { useToasts as K } from "@scalar/use-toasts";
import { deepClone as Q } from "@scalar/workspace-store/helpers/deep-clone";
import { RouterView as X } from "vue-router";
import Z from "../../../components/IconSelector.vue.js";
import ee from "../../components/callout/Callout.vue.js";
import te from "./components/LabelInput.vue.js";
import oe from "./components/SyncConflictResolutionEditor.vue.js";
import ne from "./components/Tabs.vue.js";
const se = { class: "custom-scroll h-full" }, le = {
  key: 0,
  class: "w-full px-3 md:mx-auto md:max-w-180"
}, ae = ["aria-label"], re = { class: "flex flex-row items-center justify-between gap-2" }, ce = { class: "flex min-w-0 items-center gap-2" }, ue = { class: "group relative ml-1.25 min-w-0" }, ie = { class: "px-1.5 py-8" }, de = {
  key: 1,
  class: "flex w-full flex-1 items-center justify-center"
}, me = { class: "flex flex-col gap-5" }, fe = { class: "flex gap-3" }, pe = {
  "aria-hidden": "true",
  class: "bg-b-3 text-c-2 flex size-10 shrink-0 items-center justify-center rounded-lg"
}, ve = { class: "flex flex-wrap items-center justify-end gap-2 border-t border-[var(--scalar-border-color)] pt-4" }, ye = { class: "flex h-full w-full flex-col gap-4 overflow-hidden" }, he = {
  name: "DocumentCollection"
}, Me = /* @__PURE__ */ P({
  ...he,
  props: {
    documentSlug: {},
    document: {},
    eventBus: {},
    layout: {},
    path: {},
    method: {},
    exampleName: {},
    environment: {},
    securitySchemes: {},
    workspaceStore: {},
    activeWorkspace: {},
    plugins: {},
    customThemes: {},
    currentTheme: {},
    isDarkMode: { type: Boolean },
    fetchRegistryDocument: { type: Function }
  },
  setup(v) {
    const t = v, k = f(() => t.document?.info?.title ?? ""), b = f(
      () => t.document?.["x-scalar-icon"] || "interface-content-folder"
    ), y = T(), m = T(), N = f(
      () => t.document?.["x-scalar-is-dirty"] === !0
    ), C = f(
      () => t.document?.["x-scalar-original-source-url"]
    ), D = f(
      () => t.document?.["x-scalar-registry-meta"]
    ), I = f(
      () => C.value !== void 0 || D.value !== void 0
    ), { toast: h } = K(), E = () => {
      t.workspaceStore.revertDocumentChanges(t.documentSlug);
    }, R = () => {
      t.workspaceStore.saveDocument(t.documentSlug);
    }, F = async () => {
      await t.workspaceStore.saveDocument(t.documentSlug), m.hide(), await g();
    }, j = async () => {
      await t.workspaceStore.revertDocumentChanges(t.documentSlug), m.hide(), await g();
    }, i = B(!1), c = B(null), $ = async () => {
      const r = D.value;
      if (r && t.fetchRegistryDocument)
        try {
          const s = await t.fetchRegistryDocument(r);
          return s.ok ? { document: s.data } : (h(s.error, "error"), null);
        } catch {
          return h("Failed to resolve document from registry", "error"), null;
        }
      const e = C.value;
      return e ? { url: e } : null;
    }, z = () => {
      y.hide(), i.value = !1, h(
        "Your document has been rebased with the latest version from the source.",
        "info"
      ), t.eventBus.emit("hooks:on:rebase:document:complete", {
        meta: {
          documentName: t.documentSlug
        }
      });
    }, _ = (r) => {
      r !== null && h(r, "error"), i.value = !1;
    }, g = async () => {
      if (N.value) {
        m.show();
        return;
      }
      if (i.value)
        return;
      i.value = !0;
      const r = await $();
      if (!r) {
        _(null);
        return;
      }
      const e = await t.workspaceStore.rebaseDocument({
        name: t.documentSlug,
        ...r
      });
      if (e?.ok) {
        const s = t.workspaceStore.getOriginalDocument(t.documentSlug) ?? {};
        c.value = {
          conflicts: e.conflicts,
          applyChanges: e.applyChanges,
          resolvedDocument: J(Q(s), e.changes),
          originalDocument: s
        }, c.value.conflicts.length > 0 ? y.show() : (await c.value?.applyChanges({
          resolvedDocument: c.value.resolvedDocument
        }), z());
      } else e?.ok === !1 && e.type === "NO_CHANGES_DETECTED" ? z() : _("Failed to sync document");
    }, A = async ({
      resolvedDocument: r
    }) => {
      await c.value?.applyChanges({ resolvedDocument: r }), t.eventBus.emit("hooks:on:rebase:document:complete", {
        meta: {
          documentName: t.documentSlug
        }
      }), y.hide();
    }, U = () => {
      i.value = !1, c.value = null;
    };
    return (r, e) => (u(), x(W, null, [
      o("div", se, [
        v.document ? (u(), x("div", le, [
          o("div", {
            "aria-label": `title: ${k.value}`,
            class: "mx-auto flex h-fit w-full flex-col gap-2 pt-14 pb-3 md:max-w-180 md:pt-6"
          }, [
            v.document?.["x-scalar-is-dirty"] ? (u(), p(ee, {
              key: 0,
              class: "mb-5",
              type: "warning"
            }, {
              actions: a(() => [
                l(n(d), {
                  class: "text-c-2 hover:text-c-1 flex items-center gap-2",
                  size: "xs",
                  type: "button",
                  variant: "outlined",
                  onClick: E
                }, {
                  default: a(() => [...e[5] || (e[5] = [
                    o("span", null, "Undo", -1)
                  ])]),
                  _: 1
                }),
                l(n(d), {
                  class: "text-c-btn flex items-center gap-2",
                  size: "xs",
                  type: "button",
                  variant: "solid",
                  onClick: R
                }, {
                  default: a(() => [
                    l(n(M), {
                      size: "sm",
                      thickness: "1.5"
                    }),
                    e[6] || (e[6] = o("span", null, "Save", -1))
                  ]),
                  _: 1
                })
              ]),
              default: a(() => [
                e[7] || (e[7] = o("p", null, " You have unsaved changes. Save your work to keep your changes, or undo to revert them. ", -1))
              ]),
              _: 1
            })) : w("", !0),
            o("div", re, [
              o("div", ce, [
                l(Z, {
                  modelValue: b.value,
                  placement: "bottom-start",
                  "onUpdate:modelValue": e[0] || (e[0] = (s) => v.eventBus.emit("document:update:icon", s))
                }, {
                  default: a(() => [
                    l(n(d), {
                      class: "hover:bg-b-2 aspect-square h-7 w-7 cursor-pointer rounded border border-transparent p-0 hover:border-inherit",
                      variant: "ghost"
                    }, {
                      default: a(() => [
                        l(n(H), {
                          class: "text-c-2 size-5",
                          src: b.value,
                          "stroke-width": "2"
                        }, null, 8, ["src"])
                      ]),
                      _: 1
                    })
                  ]),
                  _: 1
                }, 8, ["modelValue"]),
                o("div", ue, [
                  l(te, {
                    class: "text-xl font-bold",
                    inputId: "documentName",
                    modelValue: k.value,
                    "onUpdate:modelValue": e[1] || (e[1] = (s) => v.eventBus.emit("document:update:info", { title: s }))
                  }, null, 8, ["modelValue"])
                ])
              ]),
              I.value ? (u(), p(n(d), {
                key: 0,
                class: "text-c-2 hover:text-c-1 shrink-0 gap-1.5",
                "data-testid": "document-sync-button",
                disabled: i.value,
                size: "xs",
                title: "Pull the latest version from the document source and merge with your local copy. Save your changes first if you have unsaved edits.",
                type: "button",
                variant: "ghost",
                onClick: g
              }, {
                default: a(() => [
                  i.value ? (u(), p(n(L), {
                    key: 0,
                    class: "size-3.5 animate-spin",
                    size: "sm"
                  })) : (u(), p(n(O), {
                    key: 1,
                    class: "size-3.5",
                    size: "sm",
                    thickness: "1.5"
                  })),
                  e[8] || (e[8] = o("span", null, "Sync from source", -1))
                ]),
                _: 1
              }, 8, ["disabled"])) : w("", !0)
            ])
          ], 8, ae),
          l(ne, { type: "document" }),
          o("div", ie, [
            l(n(X), null, {
              default: a(({ Component: s }) => [
                (u(), p(Y(s), q(t, { collectionType: "document" }), null, 16))
              ]),
              _: 1
            })
          ])
        ])) : (u(), x("div", de, [...e[9] || (e[9] = [
          o("div", { class: "flex h-full flex-col items-center justify-center" }, [
            o("h1", { class: "text-2xl font-bold" }, "Document not found"),
            o("p", { class: "text-gray-500" }, " The document you are looking for does not exist. ")
          ], -1)
        ])]))
      ]),
      l(n(V), {
        bodyClass: "border-t-0 rounded-t-lg flex flex-col gap-5",
        size: "xs",
        state: n(m),
        title: "Sync requires saved document",
        onClose: e[3] || (e[3] = (s) => n(m).hide())
      }, {
        default: a(() => [
          o("div", me, [
            o("div", fe, [
              o("div", pe, [
                l(n(G), { class: "size-5 text-[var(--scalar-color-yellow)]" })
              ]),
              e[10] || (e[10] = o("div", { class: "min-w-0 flex-1 space-y-1" }, [
                o("p", { class: "text-c-1 text-sm leading-snug font-medium" }, " You have unsaved changes "),
                o("p", { class: "text-c-2 text-sm leading-relaxed" }, " Save your work to keep changes, or discard to revert to the last saved version. Then you can sync with the source. ")
              ], -1))
            ]),
            o("div", ve, [
              l(n(d), {
                size: "sm",
                type: "button",
                variant: "ghost",
                onClick: e[2] || (e[2] = (s) => n(m).hide())
              }, {
                default: a(() => [...e[11] || (e[11] = [
                  S(" Cancel ", -1)
                ])]),
                _: 1
              }),
              l(n(d), {
                size: "sm",
                type: "button",
                variant: "outlined",
                onClick: j
              }, {
                default: a(() => [...e[12] || (e[12] = [
                  S(" Discard changes ", -1)
                ])]),
                _: 1
              }),
              l(n(d), {
                class: "flex items-center gap-2",
                size: "sm",
                type: "button",
                variant: "solid",
                onClick: F
              }, {
                default: a(() => [
                  l(n(M), {
                    size: "sm",
                    thickness: "1.5"
                  }),
                  e[13] || (e[13] = S(" Save and continue ", -1))
                ]),
                _: 1
              })
            ])
          ])
        ]),
        _: 1
      }, 8, ["state"]),
      c.value ? (u(), p(n(V), {
        key: 0,
        bodyClass: "sync-conflict-modal-root flex h-dvh flex-col p-4",
        maxWidth: "calc(100dvw - 32px)",
        size: "full",
        state: n(y),
        onClose: U
      }, {
        default: a(() => [
          o("div", ye, [
            l(oe, {
              baseDocument: c.value.originalDocument,
              conflicts: c.value.conflicts,
              resolvedDocument: c.value.resolvedDocument,
              onApplyChanges: e[4] || (e[4] = (s) => A(s))
            }, null, 8, ["baseDocument", "conflicts", "resolvedDocument"])
          ])
        ]),
        _: 1
      }, 8, ["state"])) : w("", !0)
    ], 64));
  }
});
export {
  Me as default
};
