import {useEffect, useRef} from 'react'

export function useOnMiniClose(callback: () => void) {
  // Using a ref allows the callback to be updated without triggering a re-render
  // This makes the hook nicer to use because developers don't need useCallback
  const callbackRef = useRef(callback)
  callbackRef.current = callback

  useEffect(() => {
    const listenerId = window.minisEvents.on('MINI_APP_CLOSE', () => {
      callbackRef.current()
    })

    return () => window.minisEvents.off(listenerId)
  }, [])
}
