import { ref } from 'vue';

/**
 * 通用拖拽逻辑 Hook
 * @param {Object} options 配置项
 * @param {Function} [options.onDragStart] 拖拽开始回调
 * @param {Function} [options.onDragEnd] 拖拽结束回调
 * @param {Function} [options.onDrop] 拖拽释放回调，参数为 (item, position)
 * @returns {Object} 拖拽状态与事件处理函数
 */
export function useDrag(options = {}) {
  const { onDrop, onDragStart, onDragEnd, delay = 100 } = options;

  const isDragging = ref(false);
  const draggedItem = ref(null);
  const dragPosition = ref({ x: 0, y: 0 });
  const startPosition = ref({ x: 0, y: 0 });
  const dragTimer = ref(null);

  const handleStart = (clientX, clientY, item) => {
    // 如果物品已放置，不可拖拽
    if (item && item.status === 'placed') return;

    startPosition.value = { x: clientX, y: clientY };
    dragPosition.value = { x: clientX, y: clientY };

    if (dragTimer.value) clearTimeout(dragTimer.value);

    // 延时触发拖拽
    dragTimer.value = setTimeout(() => {
      isDragging.value = true;
      draggedItem.value = item;
      if (onDragStart) onDragStart(item);
    }, delay);
  };

  const handleMove = (clientX, clientY) => {
    if (!isDragging.value) {
      // 检测移动距离，超过阈值取消长按判定
      const dx = Math.abs(clientX - startPosition.value.x);
      const dy = Math.abs(clientY - startPosition.value.y);
      if (dx > 10 || dy > 10) {
        if (dragTimer.value) {
          clearTimeout(dragTimer.value);
          dragTimer.value = null;
        }
      }
    } else {
      dragPosition.value = { x: clientX, y: clientY };
    }
  };

  const handleEnd = () => {
    if (dragTimer.value) {
      clearTimeout(dragTimer.value);
      dragTimer.value = null;
    }

    if (isDragging.value) {
      if (onDrop) {
        onDrop(draggedItem.value, dragPosition.value);
      }
      if (onDragEnd) onDragEnd(draggedItem.value);
      
      isDragging.value = false;
      draggedItem.value = null;
    }
  };

  // 触摸事件处理程序
  const handleTouchStart = (event, item) => {
    if (event.touches && event.touches[0]) {
      const { clientX, clientY } = event.touches[0];
      handleStart(clientX, clientY, item);
    }
  };

  const handleTouchMove = (event) => {
    if (event.touches && event.touches[0]) {
      const { clientX, clientY } = event.touches[0];
      handleMove(clientX, clientY);
    }
  };

  const handleTouchEnd = () => {
    handleEnd();
  };

  // 鼠标事件处理程序
  const handleMouseDown = (event, item) => {
    handleStart(event.clientX, event.clientY, item);
  };

  const handleMouseMove = (event) => {
    if (dragTimer.value || isDragging.value) {
      handleMove(event.clientX, event.clientY);
    }
  };

  const handleMouseUp = () => {
    handleEnd();
  };

  return {
    isDragging,
    draggedItem,
    dragPosition,
    handleTouchStart,
    handleTouchMove,
    handleTouchEnd,
    handleMouseDown,
    handleMouseMove,
    handleMouseUp,
    handleMouseLeave: handleMouseUp
  };
}
