import { useState, useRef } from "react";

export function useDragResize(setWidth: React.Dispatch<React.SetStateAction<number>>) {

  const [dragging, setDragging] = useState(false);

  // 拖拽改变右侧面板宽度
  const handleMouseMove = (e: MouseEvent) => {
    const offset = startRef.current - e.clientX;
    requestAnimationFrame(() => {
      setWidth((w) => {
        const newW = w + offset;
        if (newW < 280) return 280;
        if (newW > window.innerWidth * 0.5) return window.innerWidth * 0.5;
        return newW;
      });
      startRef.current = e.clientX;
    });
  };

  const handleMouseUp = () => {
    setDragging(false);
    document.body.style.cursor = "default";
    document.removeEventListener("mousemove", handleMouseMove);
    document.removeEventListener("mouseup", handleMouseUp);
  };

  const startRef = useRef<number>(0);
  // 开启左右拖拽
  const handleMouseDown = (e: React.MouseEvent) => {
    setDragging(true);
    // 设置鼠标样式
    document.body.style.cursor = "ew-resize";
    startRef.current = e.clientX;
    document.addEventListener("mousemove", handleMouseMove);
    document.addEventListener("mouseup", handleMouseUp);
  };

  return {
    dragging,
    handleMouseDown,
  };
}
