import React, { Suspense, useEffect, useState, useRef, lazy } from 'react';
import { Meteor } from 'meteor/meteor';
import { BrowserRouter, Routes, Route, Link } from 'react-router-dom';
import { Login } from './Login';
import { useSubscribe, useTracker, useFind } from 'meteor/react-meteor-data/suspense';

import { Pobles } from './Pobles';
import { Necessitats } from './Necessitats';
import { Tipus } from './Tipus';
import { BarraNav } from './BarraNav/BarraNav';

import { UserStat } from './BarraNav/UserStat';
import { Usuaris } from './Usuaris';

const Loguejat = lazy(async () => await import('/imports/ui/Loguejat.jsx'));


export const App = () => {

  const user = useTracker("user", async () => await Meteor.userAsync());
  const userId = Meteor.userId();

  const [esAdministrador, setEsAdministrador] = useState(false);

  // const u = useTracker("user", async () => await Meteor.userAsync());


  useEffect(() => {
    (async () => {
        const comprovaAdmin = await Roles.userIsInRoleAsync(userId, ["admin"]);
        setEsAdministrador(comprovaAdmin);
    })();
}, [user]);
  // const userId = await Meteor.userAsync();
  
  return <BrowserRouter
    future={{
      v7_relativeSplatPath: true,
      v7_startTransition: true,
    }}
  >
    {Meteor.userId() && <UserStat esAdministrador={esAdministrador} setEsAdministrador={setEsAdministrador} />}

    <BarraNav esAdministrador={esAdministrador} setEsAdministrador={setEsAdministrador} />

    <Routes>
      <Route path="/" element={ <Suspense fallback={<>Carregant...</>}>{user ? <Loguejat /> : <Login/>}</Suspense> } />
      <Route path="/usuaris" element={ <Usuaris /> } />
      <Route path="/pobles" element={ <Pobles /> } />
      <Route path="/necessitats" element={ <Necessitats /> } />
      <Route path="/tipus" element={ <Tipus /> } />
      <Route path="/login" element={ <Login /> } />
    </Routes>
  </BrowserRouter>
};
