"use client"

import { useState, useRef } from "react"

export function useTextSelection() {
  const [selectedText, setSelectedText] = useState("")
  const selectionRef = useRef("")
  const contentRef = useRef<HTMLDivElement>(null)
  const [createDialogOpen, setCreateDialogOpen] = useState(false)
  const [isCreating, setIsCreating] = useState(false)

  const handleContentPointerDown = (e: React.PointerEvent) => {
    if (e.button !== 2) return

    const selection = window.getSelection()
    if (!selection || selection.isCollapsed) {
      selectionRef.current = ""
      return
    }

    if (contentRef.current && contentRef.current.contains(selection.anchorNode)) {
      selectionRef.current = selection.toString().trim()
    } else {
      selectionRef.current = ""
    }
  }

  const handleContextMenuChange = (open: boolean) => {
    if (!open) return

    if (selectionRef.current) {
      setSelectedText(selectionRef.current)
    } else {
      const selection = window.getSelection()
      if (selection && !selection.isCollapsed && contentRef.current && contentRef.current.contains(selection.anchorNode)) {
        const text = selection.toString().trim()
        selectionRef.current = text
        setSelectedText(text)
      } else {
        setSelectedText("")
      }
    }
  }

  return {
    selectedText,
    setSelectedText,
    selectionRef,
    contentRef,
    createDialogOpen,
    setCreateDialogOpen,
    isCreating,
    setIsCreating,
    handleContentPointerDown,
    handleContextMenuChange,
  }
}
