const moveModal = (elmnt, draggableAreaSelector = null) => {
  console.log("Initializing draggable for:", elmnt);
  let pos1 = 0,
    pos2 = 0,
    pos3 = 0,
    pos4 = 0;

  const dragMouseDown = (e) => {
    console.log("dragMouseDown", e);

    if (draggableAreaSelector) {
      const draggableArea = elmnt.querySelector(draggableAreaSelector);
      if (!draggableArea || !draggableArea.contains(e.target)) {
        return; // 只允許指定區域觸發拖動
      }
    }

    e.preventDefault();
     e.stopPropagation();
    pos3 = e.clientX;
    pos4 = e.clientY;

    // 綁定事件到元素範圍
    document.addEventListener("mouseup", closeDragElement);
    document.addEventListener("mousemove", elementDrag);
  };

  const elementDrag = (e) => {
    e.preventDefault();
    pos1 = pos3 - e.clientX;
    pos2 = pos4 - e.clientY;
    pos3 = e.clientX;
    pos4 = e.clientY;

    elmnt.style.top = `${elmnt.offsetTop - pos2}px`;
    elmnt.style.left = `${elmnt.offsetLeft - pos1}px`;
  };

  const closeDragElement = () => {
    document.removeEventListener("mouseup", closeDragElement);
    document.removeEventListener("mousemove", elementDrag);
  };

  elmnt.addEventListener("mousedown", dragMouseDown);

  // 返回一個清理函數
  return () => {
    elmnt.removeEventListener("mousedown", dragMouseDown);
    document.removeEventListener("mouseup", closeDragElement);
    document.removeEventListener("mousemove", elementDrag);
  };
};

export const draggable = {
  install(app) {
    app.directive("draggable", {
      mounted(el, binding) {
        console.log("Initializing draggable directive for:", el.id);

        // 檢查條件並啟用 draggable 行為
        if (binding.value) {
          el.style.position = "absolute"; // 確保元素可拖動
          const draggableArea = binding.value.draggableArea || ".card-title";
          el._cleanup = moveModal(el, draggableArea); // 保存清理函數
        }
      },
      unmounted(el) {
        // 清理事件
        if (el._cleanup) {
          el._cleanup();
          delete el._cleanup;
        }
      },
    });
  },
};
