import React, { useState, useEffect } from 'react'
import ReactDOM from 'react-dom/client'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import App from './App.tsx'
import './index.css'

const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      refetchOnWindowFocus: false,
      retry: 1,
      staleTime: 30 * 1000, // Data considered fresh for 30 seconds
      gcTime: 5 * 60 * 1000, // Cache garbage collected after 5 minutes (formerly cacheTime)
    },
  },
})

// Recovery component that handles QueryClient context loss
// This can happen during chunk loading race conditions or HMR
function QueryClientRecovery({ children }: { children: React.ReactNode }) {
  const [mountKey, setMountKey] = useState(0)

  useEffect(() => {
    const handleError = (event: ErrorEvent) => {
      if (event.message?.includes('No QueryClient set')) {
        event.preventDefault()
        console.warn('[QueryClient] Context lost, recovering...')
        setMountKey(k => k + 1)
      }
    }
    window.addEventListener('error', handleError)
    return () => window.removeEventListener('error', handleError)
  }, [])

  return (
    <QueryClientProvider key={mountKey} client={queryClient}>
      {children}
    </QueryClientProvider>
  )
}

// Register service worker for PWA support
if ('serviceWorker' in navigator) {
  window.addEventListener('load', () => {
    navigator.serviceWorker.register('/sw.js')
      .then((registration) => {
        console.log('SW registered:', registration.scope)

        // Check for updates periodically
        setInterval(() => {
          registration.update()
        }, 60 * 60 * 1000) // Check every hour
      })
      .catch((error) => {
        console.log('SW registration failed:', error)
      })
  })
}

ReactDOM.createRoot(document.getElementById('root')!).render(
  <React.StrictMode>
    <QueryClientRecovery>
      <App />
    </QueryClientRecovery>
  </React.StrictMode>,
)
