import { useRef, useState } from "react";
import { Plus } from "lucide-react";

export default function DraggableFab({ onClick, ariaLabel }) {
  const dragRef = useRef({ startY: 0, startTop: 0, dragged: false, dragging: false });
  const [top, setTop] = useState(() => Math.max(24, window.innerHeight - 252));

  const clampTop = (value) => Math.min(Math.max(value, 24), window.innerHeight - 180);

  function handlePointerDown(event) {
    dragRef.current = { startY: event.clientY, startTop: top, dragged: false, dragging: true };
    event.currentTarget.setPointerCapture(event.pointerId);
  }

  function handlePointerMove(event) {
    if (!dragRef.current.dragging) return;

    const deltaY = event.clientY - dragRef.current.startY;

    if (Math.abs(deltaY) > 3) {
      dragRef.current.dragged = true;
    }

    setTop(clampTop(dragRef.current.startTop + deltaY));
  }

  function handlePointerUp(event) {
    dragRef.current.dragging = false;
    event.currentTarget.releasePointerCapture(event.pointerId);
  }

  function handleClick(event) {
    if (dragRef.current.dragged) {
      event.preventDefault();
      return;
    }

    onClick();
  }

  return (
    <button
      className="fab touch-none cursor-grab active:cursor-grabbing"
      style={{ top, bottom: "auto" }}
      onPointerDown={handlePointerDown}
      onPointerMove={handlePointerMove}
      onPointerUp={handlePointerUp}
      onClick={handleClick}
      aria-label={ariaLabel}
    >
      <Plus size={30} strokeWidth={2.4} />
    </button>
  );
}
