export default () => {
  if (process.env.PROD || typeof window === 'undefined') return

  const isResizeObserverOverlayError = (message) => {
    const text = String(message || '')
    return (
      text.includes('ResizeObserver loop completed with undelivered notifications') ||
      text.includes('ResizeObserver loop limit exceeded')
    )
  }

  window.addEventListener(
    'error',
    (event) => {
      if (!isResizeObserverOverlayError(event?.message)) return
      event.preventDefault()
      event.stopImmediatePropagation()
    },
    true
  )

  window.addEventListener(
    'unhandledrejection',
    (event) => {
      const reason = event?.reason
      const msg =
        typeof reason === 'string'
          ? reason
          : (reason?.message || reason?.toString?.() || '')
      if (!isResizeObserverOverlayError(msg)) return
      event.preventDefault()
      event.stopImmediatePropagation()
    },
    true
  )
}
