import { useRef, useState } from 'react'
import { clamp } from '@/utils/px'

// Heights in px. The sheet rests above the 88px tab bar, so the lowest snap
// only needs to reveal the drag handle; the tallest keeps clear of the top nav.
const SNAP_POINTS = [64, 220, 400, 520]

function nearestSnap(height: number): number {
  return SNAP_POINTS.reduce((nearest, item) =>
    Math.abs(item - height) < Math.abs(nearest - height) ? item : nearest
  )
}

export function useDragSheet(initialHeight = 220) {
  const [height, setHeight] = useState(initialHeight)
  const [dragging, setDragging] = useState(false)
  const startY = useRef(0)
  const startHeight = useRef(initialHeight)

  const onTouchStart = (event: any) => {
    const touch = event.touches[0]
    startY.current = touch.clientY
    startHeight.current = height
    setDragging(true)
  }

  const onTouchMove = (event: any) => {
    if (!dragging) return
    const touch = event.touches[0]
    const next = startHeight.current + startY.current - touch.clientY
    setHeight(clamp(next, SNAP_POINTS[0], SNAP_POINTS[SNAP_POINTS.length - 1]))
  }

  const onTouchEnd = () => {
    setDragging(false)
    setHeight(nearestSnap(height))
  }

  return {
    height,
    dragging,
    isMin: height <= SNAP_POINTS[0] + 8,
    onTouchStart,
    onTouchMove,
    onTouchEnd
  }
}
