import { useEffect, useRef } from 'react'

// --- Хук для перетаскивания разделителя ---
export const useDraggableDivider = (onDrag: (delta: number) => void) => {
  const ref = useRef<HTMLDivElement>(null)

  useEffect(() => {
    const el = ref.current
    if (!el) return

    const handleMouseDown = (e: MouseEvent) => {
      e.preventDefault()
      document.body.style.cursor = 'col-resize'

      const container = el.parentElement
      if (!container) return

      const bounds = container.getBoundingClientRect()

      const handleMouseMove = (me: MouseEvent) => {
        // Получаем актуальные границы контейнера
        const currentBounds = container.getBoundingClientRect()
        const newLeftWidth = me.clientX - currentBounds.left
        const totalWidth = currentBounds.width

        // Рассчитываем процент напрямую от позиции мыши
        let newLeftPercentage = newLeftWidth / totalWidth
        newLeftPercentage = Math.max(0.2, Math.min(0.8, newLeftPercentage))

        // Вызываем callback с новыми процентами
        onDrag(newLeftPercentage)
      }

      const handleMouseUp = () => {
        document.body.style.cursor = 'auto'
        document.removeEventListener('mousemove', handleMouseMove)
        document.removeEventListener('mouseup', handleMouseUp)
      }

      document.addEventListener('mousemove', handleMouseMove)
      document.addEventListener('mouseup', handleMouseUp)
    }

    el.addEventListener('mousedown', handleMouseDown)

    return () => {
      el.removeEventListener('mousedown', handleMouseDown)
    }
  }, [onDrag])

  return ref
}
