import { useState } from 'react'
import { createRoot } from 'react-dom/client'
import { HashRouter, Route, Routes } from 'react-router-dom'
import '@fontsource-variable/inter'
import '@fontsource-variable/jetbrains-mono'
import '../../../packages/ui/src/tokens.css'
import './app.css'
import { initTheme } from '@sims/ui'
import { clearSession } from './api'
import { Layout } from './Layout'
import { Login } from './Login'
import { Dashboard } from './pages/Dashboard'
import { GenericPage } from './pages/GenericPage'
import { PurchaseInbox } from './pages/PurchaseInbox'
import { SettingsPage } from './pages/SettingsPage'
import { UsersRoles } from './pages/UsersRoles'
import { AuditPage, BillsPage, CustomersPage, ItemsPage, StockPage } from './pages/live'
import { LabelsPage } from './pages/labels'
import { PurchaseEntryPage, PurchasesListPage } from './pages/purchase-entry'
import { PAGES } from './pages/registry'

/** Custom/live pages override registry configs; everything else renders generically. */
const CUSTOM: Record<string, () => React.JSX.Element> = {
  '/purchases/inbox': PurchaseInbox,
  '/admin/settings': SettingsPage,
  '/admin/users': UsersRoles,
  '/catalog/items': ItemsPage,
  '/catalog/labels': LabelsPage,
  '/sales/customers': CustomersPage,
  '/sales/bills': BillsPage,
  '/inventory/stock': StockPage,
  '/admin/audit': AuditPage,
  '/purchases/entry': PurchaseEntryPage,
  '/purchases/list': PurchasesListPage,
}

function App() {
  const [userName, setUserName] = useState<string | undefined>()
  if (userName === undefined) return <Login onLogin={setUserName} />
  return (
    <HashRouter>
      <Routes>
        <Route element={<Layout userName={userName} onLogout={() => { clearSession(); setUserName(undefined) }} />}>
          <Route path="/" element={<Dashboard />} />
          {Object.entries(CUSTOM).map(([path, Page]) => (
            <Route key={path} path={path} element={<Page />} />
          ))}
          {PAGES.filter((p) => !(p.path in CUSTOM)).map((p) => (
            <Route key={p.path} path={p.path} element={<GenericPage cfg={p} />} />
          ))}
          <Route path="*" element={<Dashboard />} />
        </Route>
      </Routes>
    </HashRouter>
  )
}

initTheme()
createRoot(document.getElementById('root')!).render(<App />)
