import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom'
import { Toaster } from 'react-hot-toast'
import { useEffect } from 'react'
import { useAuthStore } from './store'
import { RequireAuth, RequireAdmin } from './components/ui/ProtectedRoute'
import AuthPage from './pages/AuthPage'
import ChatPage from './pages/ChatPage'
import AdminPage from './pages/AdminPage'

function AppInit({ children }) {
  const { isAuthenticated, loadMe } = useAuthStore()
  useEffect(() => {
    if (isAuthenticated) loadMe()
  }, [])
  return children
}

export default function App() {
  return (
    <BrowserRouter>
      <AppInit>
        <Routes>
          <Route path="/login" element={<AuthPage />} />
          <Route
            path="/"
            element={
              <RequireAuth>
                <ChatPage />
              </RequireAuth>
            }
          />
          <Route
            path="/admin"
            element={
              <RequireAdmin>
                <AdminPage />
              </RequireAdmin>
            }
          />
          <Route path="*" element={<Navigate to="/" replace />} />
        </Routes>
      </AppInit>

      <Toaster
        position="top-right"
        toastOptions={{
          style: {
            background: '#18181f',
            color: '#e8e8f0',
            border: '1px solid rgba(255,255,255,0.08)',
            borderRadius: '12px',
            fontSize: '13px',
          },
          success: { iconTheme: { primary: '#00c9a7', secondary: '#18181f' } },
          error: { iconTheme: { primary: '#f87171', secondary: '#18181f' } },
        }}
      />
    </BrowserRouter>
  )
}
