import { Navigate, Outlet } from 'react-router-dom';
import { PublicRoutes } from '../config/routes';
import { Layout } from '../components/layout/Layout';
import { useEffect, useMemo, useState } from 'react';
import PocketBase from 'pocketbase';

const AuthGuard = () => {
  const pb = useMemo(
    () => new PocketBase(import.meta.env.VITE_BASE_URL_API),
    []
  );

  const [, setToken] = useState(pb.authStore.token);
  const [user, setUser] = useState(pb.authStore.model);

  useEffect(() => {
    return pb.authStore.onChange((token, model) => {
      setToken(token);
      setUser(model);
    });
  }, [pb.authStore]);

  return user ? (
    <Layout>
      <Outlet />
    </Layout>
  ) : (
    <Navigate replace to={PublicRoutes.HOME} />
  );
};

export default AuthGuard;
