import { createBrowserRouter, Navigate } from "react-router-dom"
import { ProtectedRoute, AdminRoute } from "./guards"
import { useAuthStore } from "@/store/authStore"
import LoginPage from "@/features/auth/LoginPage"
import BooksPage from "@/features/books/BooksPage"
import MyBorrowsPage from "@/features/borrows/MyBorrowsPage"
import AdminBooksPage from "@/features/admin/AdminBooksPage"
import AdminBorrowsPage from "@/features/admin/AdminBorrowsPage"
import AppLayout from "@/components/layout/AppLayout"
import UserLayout from "@/components/layout/UserLayout"
import AdminLayout from "@/components/layout/AdminLayout"

function RootRedirect() {
  const isAdmin = useAuthStore((s) => s.isAdmin())
  return <Navigate to={isAdmin ? "/admin/books" : "/books"} replace />
}

export const router = createBrowserRouter([
  {
    path: "/login",
    element: <LoginPage />,
  },
  {
    element: <AppLayout />,
    children: [
      {
        path: "/",
        element: <RootRedirect />,
      },
    ],
  },
  {
    element: <UserLayout />,
    children: [
      {
        path: "/books",
        element: <BooksPage />,
      },
      {
        element: <ProtectedRoute />,
        children: [
          {
            path: "/my-borrows",
            element: <MyBorrowsPage />,
          },
        ],
      },
    ],
  },
  {
    element: <AdminRoute />,
    children: [
      {
        element: <AdminLayout />,
        children: [
          {
            path: "/admin",
            element: <Navigate to="/admin/books" replace />,
          },
          {
            path: "/admin/books",
            element: <AdminBooksPage />,
          },
          {
            path: "/admin/borrows",
            element: <AdminBorrowsPage />,
          },
        ],
      },
    ],
  },
])
