import React, { useEffect, useRef } from 'react'
import { PointerLockControls } from '@react-three/drei'

import api from '../store'

const Controls: React.FC = () => {
  const ref = useRef<null | PointerLockControls>(null)
  const { setPointerLockStatus, setPointerLockControls } = api.getState()

  useEffect(() => {
    if (ref.current) {
      setPointerLockControls(ref.current)

      const onLock = () => setPointerLockStatus(true)
      const onUnlock = () => {
        setPointerLockStatus(false)
      }

      ref.current.addEventListener?.('lock', onLock)
      ref.current.addEventListener?.('unlock', onUnlock)
      return () => {
        ref.current?.removeEventListener?.('lock', onLock)
        ref.current?.removeEventListener?.('unlock', onUnlock)
      }
    }
  }, [ref, ref.current])

  return <PointerLockControls ref={ref} />
}

export default Controls
