import {useFocusEffect} from 'expo-router'
import {useCallback} from 'react'
import {AppState} from 'react-native'

// run cb immediately and then every intervalMs, but only while this screen
// is focused and the app is active — the polling analogue of
// useRefreshOnActive. pass a stable cb (useCallback) or the poll restarts
export const useFocusedPoll = (
  cb: () => void,
  intervalMs: number,
): void => {
  useFocusEffect(
    useCallback(() => {
      let interval: ReturnType<typeof setInterval> | null = null
      const start = () => {
        if (interval) return
        cb()
        interval = setInterval(cb, intervalMs)
      }
      const stop = () => {
        if (interval) clearInterval(interval)
        interval = null
      }
      start()
      const sub = AppState.addEventListener('change', (state) => {
        if (state === 'active') start()
        else stop()
      })
      return () => {
        stop()
        sub.remove()
      }
    }, [cb, intervalMs]),
  )
}
