import { QueryClientProvider } from '@tanstack/react-query'
import { useEffect, useState, type ReactNode } from 'react'
import { installOverdeckQueryPersistence } from '../../lib/query-persistence'
import { createOverdeckQueryClient } from '../../lib/query-client'
import { CollectorRealtimeBridge } from '../overview/CollectorRealtimeBridge'
import { DeckPageSkeleton } from './DeckPageSkeleton'

export function CollectorPageApp({ children }: { children: ReactNode }) {
  const [queryClient] = useState(createOverdeckQueryClient)
  const [ready, setReady] = useState(false)

  useEffect(() => {
    const uninstall = installOverdeckQueryPersistence(queryClient)
    setReady(true)
    return uninstall
  }, [queryClient])

  if (!ready) {
    return <DeckPageSkeleton />
  }

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