// SweetAlert2 팝업을 제목 바를 잡고 마우스/터치로 이동 가능하게 만든다.
// Swal.fire({ didOpen: () => makeSwalDraggable() }) 형태로 사용.
export function makeSwalDraggable() {
  if (typeof document === "undefined") return;
  const popup = document.querySelector<HTMLElement>(".swal2-popup");
  if (!popup) return;
  const handle = popup.querySelector<HTMLElement>(".swal2-title") ?? popup;

  let committedX = 0, committedY = 0; // 지금까지 이동 누적
  let startX = 0, startY = 0;
  let dragging = false;

  handle.style.cursor = "move";
  handle.style.userSelect = "none";
  handle.style.touchAction = "none";

  const point = (e: MouseEvent | TouchEvent) =>
    "touches" in e ? e.touches[0] ?? (e as TouchEvent).changedTouches[0] : (e as MouseEvent);

  const onMove = (e: MouseEvent | TouchEvent) => {
    if (!dragging) return;
    const p = point(e);
    const nx = committedX + (p.clientX - startX);
    const ny = committedY + (p.clientY - startY);
    popup.style.transform = `translate(${nx}px, ${ny}px)`;
    if ("touches" in e) e.preventDefault();
  };

  const onUp = (e: MouseEvent | TouchEvent) => {
    if (!dragging) return;
    dragging = false;
    const p = point(e);
    committedX += p.clientX - startX;
    committedY += p.clientY - startY;
    document.removeEventListener("mousemove", onMove);
    document.removeEventListener("mouseup", onUp);
    document.removeEventListener("touchmove", onMove);
    document.removeEventListener("touchend", onUp);
  };

  const onDown = (e: MouseEvent | TouchEvent) => {
    // 입력/버튼 위에서 시작하면 드래그 안 함
    const target = e.target as HTMLElement;
    if (target.closest("input, textarea, select, button, a")) return;
    const p = point(e);
    startX = p.clientX;
    startY = p.clientY;
    dragging = true;
    document.addEventListener("mousemove", onMove);
    document.addEventListener("mouseup", onUp);
    document.addEventListener("touchmove", onMove, { passive: false });
    document.addEventListener("touchend", onUp);
  };

  handle.addEventListener("mousedown", onDown);
  handle.addEventListener("touchstart", onDown, { passive: true });
}
