"use strict";
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const Vue = require("vue");
const index = require("../../../../@popperjs/core/dist/index.js");
const fromPairs = require("../../../../lodash-es/fromPairs.js");
const usePopper = (referenceElementRef, popperElementRef, opts = {}) => {
  const stateUpdater = {
    name: "updateState",
    enabled: true,
    phase: "write",
    fn: ({ state }) => {
      const derivedState = deriveState(state);
      Object.assign(states.value, derivedState);
    },
    requires: ["computeStyles"]
  };
  const options = Vue.computed(() => {
    const { onFirstUpdate, placement, strategy, modifiers } = Vue.unref(opts);
    return {
      onFirstUpdate,
      placement: placement || "bottom",
      strategy: strategy || "absolute",
      modifiers: [
        ...modifiers || [],
        stateUpdater,
        {
          name: "applyStyles",
          enabled: false
        }
      ]
    };
  });
  const instanceRef = Vue.shallowRef();
  const states = Vue.ref({
    styles: {
      popper: {
        position: Vue.unref(options).strategy,
        left: "0",
        top: "0"
      },
      arrow: { position: "absolute" }
    },
    attributes: {}
  });
  const destroy = () => {
    if (!instanceRef.value) return;
    instanceRef.value.destroy();
    instanceRef.value = void 0;
  };
  Vue.watch(options, (newOptions) => {
    const instance = Vue.unref(instanceRef);
    if (instance) instance.setOptions(newOptions);
  }, { deep: true });
  Vue.watch([referenceElementRef, popperElementRef], ([referenceElement, popperElement]) => {
    destroy();
    if (!referenceElement || !popperElement) return;
    instanceRef.value = index.createPopper(referenceElement, popperElement, Vue.unref(options));
  });
  Vue.onBeforeUnmount(() => {
    destroy();
  });
  return {
    state: Vue.computed(() => {
      var _a;
      return { ...((_a = Vue.unref(instanceRef)) == null ? void 0 : _a.state) || {} };
    }),
    styles: Vue.computed(() => Vue.unref(states).styles),
    attributes: Vue.computed(() => Vue.unref(states).attributes),
    update: () => {
      var _a;
      return (_a = Vue.unref(instanceRef)) == null ? void 0 : _a.update();
    },
    forceUpdate: () => {
      var _a;
      return (_a = Vue.unref(instanceRef)) == null ? void 0 : _a.forceUpdate();
    },
    instanceRef: Vue.computed(() => Vue.unref(instanceRef))
  };
};
function deriveState(state) {
  const elements = Object.keys(state.elements);
  return {
    styles: fromPairs.default(elements.map((element) => [element, state.styles[element] || {}])),
    attributes: fromPairs.default(elements.map((element) => [element, state.attributes[element]]))
  };
}
exports.usePopper = usePopper;
