import "regenerator-runtime/runtime";
import React, { Suspense, useEffect } from "react";
import ReactDOM from "react-dom";
import { Switch, BrowserRouter, Route, useLocation } from "react-router-dom";
import { routes } from "./routes";
import { Provider, useDispatch, useSelector } from "react-redux";
import store from "./store/store";
import Loading from "@src/components/common/Loading";
import Header from "./components/common/Header";
import Footer from "./components/common/Footer";
import { ACCESS_TOKEN } from "./constants/Cookie";
import AccessToken from "./constants/AccessToken";
import ScrollUtil from "./utils/ScrollUtil";
import { fetchUserInfo } from "./store/reducers/UserReducer";
import "./index.scss";
import NetworkLoading from "./components/common/NetworkLoading";
import CookieUtil from "./utils/CookieUtil";

const Main = () => {
  const dispatch = useDispatch();
  const location = useLocation();
  const { isLoading } = useSelector((store) => store.networkLoading);

  useEffect(() => {
    const accessToken = CookieUtil.getCookie(ACCESS_TOKEN);

    if (accessToken) {
      AccessToken.setAccessToken(accessToken);
    }

    dispatch(fetchUserInfo());
  }, []);

  useEffect(() => {
    ScrollUtil.scrollTop(false);
  }, [location.pathname]);

  return (
    <Suspense fallback={<Loading />}>
      <Header />
      {isLoading && <NetworkLoading />}
      <Switch>
        {routes.map((route, index) => (
          <Route
            key={index}
            exact={route.exact}
            path={route.path}
            component={route.component}
          />
        ))}
      </Switch>
      <Footer />
    </Suspense>
  );
};

const App = () => {
  return (
    <Provider store={store}>
      <BrowserRouter>
        <Main />
      </BrowserRouter>
    </Provider>
  );
};

ReactDOM.render(<App />, document.getElementById("root"));
