import {useEffect, useState} from 'react'

// reflect `active` turning true only after it has held for `ms`; turning false
// is immediate. a brief true that resolves within the window never shows —
// gates a spinner/badge so a fast operation doesn't flash it. deriving the
// result as `active && elapsed` keeps the hide synchronous and lets the cleanup
// reset the timer for the next window without a setState in the effect body
export const useDelayedFlag = (
  active: boolean,
  ms: number,
): boolean => {
  const [elapsed, setElapsed] = useState(false)
  useEffect(() => {
    if (!active) return
    const id = setTimeout(() => setElapsed(true), ms)
    return () => {
      clearTimeout(id)
      setElapsed(false)
    }
  }, [active, ms])
  return active && elapsed
}
