import {useEffect, useRef} from 'react'

import {type AppStateChangePayload} from '@shopify/shop-minis-platform/events'

export function useOnAppStateChange(
  callback: (payload: AppStateChangePayload) => 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('APP_STATE_CHANGE', payload => {
      callbackRef.current(payload)
    })

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