import { useCallback, useEffect, useRef, useState } from 'react'

export function useToast(duration = 480) {
  const [visible, setVisible] = useState(false)
  const timer = useRef<ReturnType<typeof setTimeout> | null>(null)

  const show = useCallback(() => {
    if (timer.current) clearTimeout(timer.current)
    setVisible(true)
    timer.current = setTimeout(() => setVisible(false), duration)
  }, [duration])

  const hide = useCallback(() => {
    if (timer.current) clearTimeout(timer.current)
    setVisible(false)
  }, [])

  useEffect(() => () => {
    if (timer.current) clearTimeout(timer.current)
  }, [])

  return { visible, show, hide }
}
