import { routes } from '~/router/index';
import { createBrowserRouter, RouterProvider } from 'react-router-dom';
import { useEffect, useState } from 'react';
import Cookies from 'js-cookie';

function PrivateRouter() {
  const [router, setRouter] = useState(createBrowserRouter(routes));
  // 在切换路由之前判断
  const beforeEach = () => {
    // TODO: 判断是否登录 (需要改为实时获取地址栏的路由)
    const path = location.pathname;
    const token = Cookies.get('SHAREFLY-TOKEN');
    if (!token && path !== '/login') {
      location.replace('/login');
      return;
    }
  };
  useEffect(() => {
    beforeEach();
    setRouter(createBrowserRouter(routes)); //不同账号登录时，重新更新路由（有瑕疵）
  }, [location.pathname]);

  return <RouterProvider router={router} />;
}

export default PrivateRouter;
