import { useHead } from "#app";
import { useEventListener } from "@vueuse/core";
import { computed, readonly, shallowRef, toValue } from "vue";
export default function useDragging(target, options) {
  const start = shallowRef();
  const distance = shallowRef();
  const offset = shallowRef();
  const isDragging = computed(() => start.value !== void 0);
  const coordinate = computed({
    get: () => ({
      x: (offset.value?.x ?? 0) + (distance.value?.x ?? 0),
      y: (offset.value?.y ?? 0) + (distance.value?.y ?? 0)
    }),
    set: (value) => {
      offset.value = {
        x: value.x + (distance.value?.x ?? 0),
        y: value.y + (distance.value?.y ?? 0)
      };
    }
  });
  const cursor = shallowRef();
  useHead(() => ({
    bodyAttrs: {
      style: {
        cursor: isDragging.value ? "grabbing !important" : void 0
      }
    }
  }));
  useEventListener(target, "mousedown", (event) => {
    if (options?.enabled !== void 0 && !toValue(options.enabled)) return;
    start.value = {
      x: event.clientX,
      y: event.clientY
    };
  });
  useEventListener("mousemove", (event) => {
    cursor.value = {
      x: event.clientX - (toValue(target)?.getBoundingClientRect().left ?? 0),
      y: event.clientY - (toValue(target)?.getBoundingClientRect().top ?? 0)
    };
    if (!start.value) return;
    distance.value = {
      x: event.clientX - start.value.x,
      y: event.clientY - start.value.y
    };
  });
  useEventListener("mouseup", () => {
    if (!start.value) return;
    offset.value = {
      x: (offset.value?.x ?? 0) + (distance.value?.x ?? 0),
      y: (offset.value?.y ?? 0) + (distance.value?.y ?? 0)
    };
    start.value = void 0;
    distance.value = void 0;
  });
  useEventListener(target, "mouseleave", () => {
    start.value = void 0;
    distance.value = void 0;
    cursor.value = void 0;
  });
  useEventListener(target, "mouseenter", (event) => {
    cursor.value = {
      x: event.clientX - (toValue(target)?.getBoundingClientRect().left ?? 0),
      y: event.clientY - (toValue(target)?.getBoundingClientRect().top ?? 0)
    };
  });
  return {
    stop: () => {
      start.value = void 0;
      distance.value = void 0;
    },
    isDragging,
    coordinate,
    cursor: readonly(cursor)
  };
}
