import { watchEffect, onMounted, watch, onBeforeUnmount, computed } from 'vue';
import '../../../../hooks/index.mjs';
import { isInViewPort } from '../util.mjs';
import { useState } from '../../../../hooks/use-state/index.mjs';

function useTarget(target, open, gap, scrollIntoViewOptions) {
  const [targetElement, setTargetElement] = useState(void 0);
  watchEffect(
    () => {
      const nextElement = typeof target.value === "function" ? target.value() : target.value;
      setTargetElement(nextElement || null);
    },
    { flush: "post" }
  );
  const [posInfo, setPosInfo] = useState(null);
  const updatePos = () => {
    if (!open.value) {
      setPosInfo(null);
      return;
    }
    if (targetElement.value) {
      if (!isInViewPort(targetElement.value) && open.value)
        targetElement.value.scrollIntoView(scrollIntoViewOptions.value);
      const { left, top, width, height } = targetElement.value.getBoundingClientRect();
      const nextPosInfo = { left, top, width, height, radius: 0 };
      if (JSON.stringify(posInfo.value) !== JSON.stringify(nextPosInfo))
        setPosInfo(nextPosInfo);
    } else {
      setPosInfo(null);
    }
  };
  onMounted(() => {
    watch(
      [open, targetElement],
      () => {
        updatePos();
      },
      { flush: "post", immediate: true }
    );
    window.addEventListener("resize", updatePos);
  });
  onBeforeUnmount(() => {
    window.removeEventListener("resize", updatePos);
  });
  const mergedPosInfo = computed(() => {
    var _a, _b;
    if (!posInfo.value)
      return posInfo.value;
    const gapOffset = ((_a = gap.value) == null ? void 0 : _a.offset) || 6;
    const gapRadius = ((_b = gap.value) == null ? void 0 : _b.radius) || 2;
    return {
      left: posInfo.value.left - gapOffset,
      top: posInfo.value.top - gapOffset,
      width: posInfo.value.width + gapOffset * 2,
      height: posInfo.value.height + gapOffset * 2,
      radius: gapRadius
    };
  });
  return [mergedPosInfo, targetElement];
}

export { useTarget as default };
//# sourceMappingURL=useTarget.mjs.map
