import { createHead } from "@unhead/vue/client";
import { reactive, createApp, h } from "vue";
import ApiReference from "../../components/ApiReference.vue.js";
const createApiReference = (elementOrSelectorOrConfig, optionalConfiguration) => {
  const idPrefix = "scalar-refs";
  const props = reactive({
    // Either the configuration will be the second argument or it MUST be the first (configuration only)
    configuration: optionalConfiguration ?? elementOrSelectorOrConfig ?? {}
  });
  let app = createApp(() => h(ApiReference, props));
  app.use(createHead());
  app.config.idPrefix = idPrefix;
  if (optionalConfiguration) {
    const element = typeof elementOrSelectorOrConfig === "string" ? document.querySelector(elementOrSelectorOrConfig) : elementOrSelectorOrConfig;
    if (element) {
      app.mount(element);
    } else {
      console.error("Could not find a mount point for API References:", elementOrSelectorOrConfig);
    }
  }
  document.addEventListener(
    "scalar:reload-references",
    () => {
      console.warn(
        "scalar:reload-references event has been deprecated, please use the scalarInstance.app.mount method instead."
      );
      if (!props.configuration) {
        return;
      }
      const currentElement = typeof elementOrSelectorOrConfig === "string" ? document.querySelector(elementOrSelectorOrConfig) : elementOrSelectorOrConfig;
      if (!currentElement) {
        return;
      }
      if (currentElement && !document.body.contains(currentElement)) {
        document.body.appendChild(currentElement);
      }
      app.unmount();
      app = createApp(() => h(ApiReference, props));
      app.use(createHead());
      app.config.idPrefix = idPrefix;
      app.mount(currentElement);
    },
    false
  );
  const destroy = () => {
    props.configuration = {};
    app.unmount();
  };
  document.addEventListener(
    "scalar:destroy-references",
    () => {
      console.warn("scalar:destroy-references event has been deprecated, please use scalarInstance.destroy instead.");
      destroy();
    },
    false
  );
  document.addEventListener(
    "scalar:update-references-config",
    (ev) => {
      console.warn(
        "scalar:update-references-config event has been deprecated, please use scalarInstance.updateConfiguration instead."
      );
      if ("detail" in ev) {
        Object.assign(props, ev.detail);
      }
    },
    false
  );
  const instance = {
    app,
    getConfiguration: () => props.configuration ?? {},
    updateConfiguration: (newConfig) => {
      props.configuration = newConfig;
    },
    destroy
  };
  return instance;
};
export {
  createApiReference
};
