import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import './index.css'
import App from './App.tsx'
import { hydrateLocalDb } from './lib/localdb'
import { resolveTransport, startSync } from './lib/sync'
import { ZeroSession } from './zero/ZeroSession'
import { AuthGate } from './auth/AuthGate'

/*
 * The local database is loaded before the first render.
 *
 * Components read their initial state synchronously, so if the app painted
 * first it would start from empty defaults and then write those defaults over
 * the stored records. Hydration is a couple of milliseconds; a flash of the
 * wrong workspace would be permanent.
 */
hydrateLocalDb().then(() => {
  startSync(resolveTransport())
  createRoot(document.getElementById('root')!).render(
    <StrictMode>
      {/* The sync client is built for whoever is signed in, so the session
          resolves first and the provider follows it. */}
      <ZeroSession>
        <AuthGate>
          <App />
        </AuthGate>
      </ZeroSession>
    </StrictMode>,
  )
})
