'use client'
import { useEffect, useState } from 'react'
import { useRecoilState, useRecoilValue } from 'recoil'

export default function QEmptyContextMenu(props) {
  const { contextRef, canvasProps } = props

  //   const children = useRecoilValue(modalContent)
  const [contextMenu, setContextMenu] = useState({ visible: false, x: 0, y: 0 })

  useEffect(() => {
    if (!contextRef.current) return

    const handleContextMenu = (e) => {
      e.preventDefault() //기존 contextmenu 막고
      setContextMenu({ visible: true, x: e.pageX, y: e.pageY })
      canvasProps.upperCanvasEl.removeEventListener('contextmenu', handleContextMenu) //한번 노출 후 이벤트 삭제
    }

    const handleClick = (e) => {
      e.preventDefault()
      setContextMenu({ ...contextMenu, visible: false })
    }

    const handleOutsideClick = (e) => {
      e.preventDefault()
      if (contextMenu.visible && !ref.current.contains(e.target)) {
        setContextMenu({ ...contextMenu, visible: false })
      }
    }

    // Prevent the default context menu from appearing on the canvas
    canvasProps.upperCanvasEl.addEventListener('contextmenu', handleContextMenu)
    document.addEventListener('click', handleClick)
    document.addEventListener('click', handleOutsideClick)

    return () => {
      // canvasProps.upperCanvasEl.removeEventListener('contextmenu', handleContextMenu)
      document.removeEventListener('click', handleClick)
      document.removeEventListener('click', handleOutsideClick)
    }
  }, [contextRef, contextMenu])

  const handleMenuClick = (option) => {
    alert(`option ${option} clicked`)
    setContextMenu({ ...contextMenu, visible: false })
  }

  return <></>
}
