import { useModal as P } from "@scalar/components";
import { createWorkspaceEventBus as S } from "@scalar/workspace-store/events";
import { ref as A, reactive as W, computed as o, createApp as I, watch as N } from "vue";
import { resolveRouteParameters as O } from "./resolve-route-parameters.js";
import { restoreWorkspaceState as R } from "./restore-workspace-state.js";
import { useModalSidebar as _ } from "../hooks/use-modal-sidebar.js";
import j from "../Modal.vue.js";
const z = ({
  el: v,
  eventBus: h = S({
    debug: !1
  }),
  mountOnInitialize: g = !0,
  plugins: x = [],
  workspaceStore: t,
  options: M = {}
}) => {
  const u = {
    path: "default",
    method: "default",
    example: "default",
    documentSlug: t.workspace["x-scalar-active-document"] || "default"
  }, n = A(null), m = W({ ...u }), s = (e) => {
    Object.assign(m, u, e);
  }, a = o(() => O(t, m)), l = o(() => a.value.documentSlug), d = o(() => a.value.path), i = o(() => a.value.method), p = o(() => a.value.example), b = o(() => t.workspace.documents[l.value ?? ""] ?? null), k = _({
    workspaceStore: t,
    documentSlug: l,
    path: d,
    method: i,
    exampleName: p,
    route: s
  }), r = P(), c = I(j, {
    document: b,
    eventBus: h,
    exampleName: p,
    method: i,
    modalState: r,
    path: d,
    plugins: x,
    sidebarState: k,
    workspaceStore: t,
    options: M
  }), w = () => {
    n.value = window.structuredClone(t.exportWorkspace());
  }, C = () => {
    if (!n.value) {
      console.warn("No workspace store snapshot to restore");
      return;
    }
    const e = R({
      workspaceStore: t,
      workspaceState: n.value,
      name: l.value ?? ""
    });
    e.ok || console.error("Failed to restore workspace state", e.error);
  };
  N(
    () => r.open,
    (e) => e ? w() : C()
  ), c.config.idPrefix = "scalar-client";
  const f = (e = v) => {
    if (!e) {
      console.error(
        "[@scalar/api-client] Could not create the API client Modal.",
        "Invalid HTML element provided.",
        "Read more: https://github.com/scalar/scalar/tree/main/packages/api-client"
      );
      return;
    }
    c.mount(e);
  };
  return g && f(), {
    /** The Vue app instance for the modal. Use with caution. */
    app: c,
    /** Open the modal and optionally navigate to a specific route. */
    open: (e) => {
      r.open = !0, e && s(e);
    },
    /** Mount the modal to a given element. */
    mount: f,
    /** Navigate to the specified path, method, and example. */
    route: s,
    /** Controls the visibility of the modal. */
    modalState: r
  };
};
export {
  z as createApiClientModal
};
