import { Navigate, Outlet, Route, Routes } from 'react-router-dom'
import { getToken } from '@/api/client'
import { AdminLayout } from '@/components/admin-layout'
import LoginPage from '@/pages/login'
import DashboardPage from '@/pages/dashboard'
import PostsListPage from '@/pages/posts-list'
import PostEditPage from '@/pages/post-edit'
import VisitsPage from '@/pages/visits'

function RequireAuth() {
  if (!getToken()) return <Navigate to="/login" replace />
  return <Outlet />
}

export default function App() {
  return (
    <Routes>
      <Route path="/login" element={<LoginPage />} />
      <Route element={<RequireAuth />}>
        <Route element={<AdminLayout />}>
          <Route index element={<DashboardPage />} />
          <Route path="posts" element={<PostsListPage />} />
          <Route path="posts/new" element={<PostEditPage />} />
          <Route path="posts/:id" element={<PostEditPage />} />
          <Route path="visits" element={<VisitsPage />} />
        </Route>
      </Route>
      <Route path="*" element={<Navigate to="/" replace />} />
    </Routes>
  )
}
