import { Navigate, Route, RouterProvider, createBrowserRouter, createRoutesFromElements, useLocation, useNavigate, useRouteLoaderData } from 'react-router-dom'

import Layout from './components/Layout'

import Index from './pages/Index'
import Login from './pages/Login'
import Register from './pages/Register'
import NoMatch from './pages/NoMatch'
import { UserProvider } from './store/user'
import { ajax } from './utils/fetch'
import Engine from './pages/Engine'

const router = createBrowserRouter(
  createRoutesFromElements(
    <Route
      path="/"
      id="root"
      element={<Layout />}
      loader={async () => ajax("/api/user")}
    >
      <Route
        index
        element={<Index />}
        loader={() => ajax("/api/games")}
      />
      <Route path="login" element={<Login />} />
      <Route path="register" element={<Register />} />
      <Route
        path="go/:gameId"
        element={<Auth><Engine /></Auth>}
        loader={({ params }) => ajax(`/api/engine/${params.gameId}`)}
      />
      {/* <Route
        path="admin"
        element={<Auth role="creator"><Admin /></Auth>}
        loader={() => ajax(`/api/admin/games`)}
      />
      <Route
        path="admin/games/new"
        element={<Auth role="creator"><AdminGame /></Auth>}
        loader={() => ({
          title: "Новая игра",
          tasks: []
        })}
      /> */}
      <Route path="*" element={<NoMatch />} />
    </Route>
  )
);
function App() {
  return (
    <RouterProvider router={router} />
  )
}

function Auth({ children }) {
  const baseUser = useRouteLoaderData("root")
  const { user } = UserProvider.useContainer();
  const location = useLocation();
  if (!user && !baseUser) {
    return <Navigate to="/login" state={{ from: location }} replace />;
  }

  return children;
}

export default App
