import client, { type BasedClient } from '@based/client'
import { BasedTranslationsProvider } from '@based/i18n'
import { Provider as BasedProvider } from '@based/react'
import { Provider as UiProvider } from '@based/ui'
import { createRoot } from 'react-dom/client'
import { RouterProvider, useRoute } from 'react-router5'
import { MetaProvider, useMeta } from 'src/metaExtractor/metaContext.js'
import basedConfig from '../../based.js'
import {
  Home,
  Layout,
  MetaContent,
  MetaSidebar,
  Navbar,
} from './components/index.js'
import { parseSections } from './helpers/index.js'
import { type TranslationsType, languages } from './i18n/index.js'
import { createAppRouter, useTypedRoute } from './router.js'
import './index.css'
import '@based/ui/assets/global.css'

export const based: BasedClient = client(basedConfig)

const App = () => {
  const meta = useMeta()
  const { params } = useTypedRoute()
  const { route } = useRoute()
  const { section, view } = params
  const isFullscreen = view === 'fullscreen'
  const sections = parseSections(meta)

  const hasComponents =
    sections[section as Based.UI.Playground.RouterParams['section']] > 1

  const content = route.name === 'home' ? <Home /> : <MetaContent />

  return (
    <Layout
      header={!isFullscreen && <Navbar />}
      sidebar={hasComponents && !isFullscreen && <MetaSidebar />}
      content={content}
    />
  )
}

const rootElement = document.getElementById('root')!
const root = createRoot(rootElement)
const router = createAppRouter()

router.start(() => {
  root.render(
    <BasedProvider client={based}>
      <UiProvider forcedTheme="dark">
        <BasedTranslationsProvider<TranslationsType> languages={languages}>
          <MetaProvider>
            <RouterProvider router={router}>
              <App />
            </RouterProvider>
          </MetaProvider>
        </BasedTranslationsProvider>
      </UiProvider>
    </BasedProvider>,
  )
})
