import { lazy } from 'react'

/**
 * Wraps React.lazy with retry logic for stale chunk errors after deployments.
 * On first failure, reloads the page once to get fresh asset manifest.
 */
export function lazyWithRetry<T extends React.ComponentType<unknown>>(
  importFn: () => Promise<{ default: T }>,
) {
  return lazy(() =>
    importFn().catch((error: Error) => {
      const isChunkError =
        error.message.includes('dynamically imported module') ||
        error.message.includes('Loading chunk') ||
        error.message.includes('importing a module script failed') ||
        error.message.includes('loading css chunk')

      if (!isChunkError) throw error

      // Only auto-reload once per 10 seconds to prevent loops
      const key = 'rf_lazy_chunk_reload'
      const lastReload = sessionStorage.getItem(key)
      const now = Date.now()

      if (!lastReload || now - Number(lastReload) > 10_000) {
        sessionStorage.setItem(key, String(now))
        window.location.reload()
      }

      // If we already reloaded recently and it still fails, let it propagate
      throw error
    }),
  )
}
