import { StrictMode, useEffect, useState, type ComponentType } from 'react'
import { createRoot } from 'react-dom/client'
import './index.css'

import { AppErrorBoundary, AppStartupError } from './components/AppErrorBoundary'

function AppStartup() {
  const [App, setApp] = useState<ComponentType | null>(null)
  const [error, setError] = useState<unknown>(null)

  useEffect(() => {
    import('./App.tsx')
      .then((module) => setApp(() => module.default))
      .catch((error) => {
        console.error('[app] Startup failed:', error)
        setError(error)
      })
  }, [])

  if (error) return <AppStartupError error={error} />

  if (!App) {
    return (
      <div className="flex min-h-screen items-center justify-center bg-[#05080D] px-4 text-sm text-slate-400">
        Starting Crypto Intelligence Platform...
      </div>
    )
  }

  return (
    <AppErrorBoundary>
      <App />
    </AppErrorBoundary>
  )
}

const rootElement = document.getElementById('root')

if (!rootElement) {
  throw new Error('Missing root element: expected #root in index.html')
}

createRoot(rootElement).render(
  <StrictMode>
    <AppStartup />
  </StrictMode>,
)
