"use client"

import { useCallback, useRef, useState } from "react"
import { useLongPress } from "@/hooks/use-long-press"
import { cn } from "@/lib/utils"

/** Long-press / context-menu handlers to open a sidebar row options bottom sheet. */
export function useSidebarTouchOptionsMenu(enabled: boolean) {
  const [sheetOpen, setSheetOpen] = useState(false)
  const lastOpenRef = useRef(0)

  const openSheet = useCallback(() => {
    const now = Date.now()
    if (now - lastOpenRef.current < 400) return
    lastOpenRef.current = now
    setSheetOpen(true)
  }, [])

  const longPress = useLongPress(openSheet, { disabled: !enabled })

  const touchRowProps = enabled
    ? {
        onContextMenu: (e: React.MouseEvent) => {
          e.preventDefault()
          e.stopPropagation()
          openSheet()
        },
        onPointerDown: longPress.onPointerDown,
        onPointerUp: longPress.onPointerUp,
        onPointerLeave: longPress.onPointerLeave,
        onPointerCancel: longPress.onPointerCancel,
        onClickCapture: longPress.onClickCapture,
      }
    : {}

  const touchRowClassName = enabled
    ? cn("select-none", longPress.ackClassName)
    : undefined

  const closeSheet = useCallback(() => setSheetOpen(false), [])

  return { sheetOpen, setSheetOpen, touchRowProps, touchRowClassName, closeSheet }
}
