import { useEffect, useState } from "react";
import { Routes, Route, Navigate } from "react-router-dom";
import Login from "./pages/Login";
import { getLocalStorage, setLocalStorage } from "./utils/local";
import Home from "./pages/Home";
import { useNavigate } from "react-router-dom";

function App() {
  const navigate = useNavigate();
  const [isLoading, setIsLoading] = useState(true);
  useEffect(() => {
    const urlParams = new URLSearchParams(window.location.search);
    const urlToken = urlParams.get("token");
    const localToken = getLocalStorage("token");
    // 当前路由是否是登录路由
    const isLoginRoute = window.location.pathname === "/web/login";

    if (urlToken) {
      setLocalStorage("token", urlToken);
    }

    if (localToken || urlToken) {
      if (isLoginRoute) {
        navigate("/home");
      }
    }

    setIsLoading(false);
  }, [navigate]);

  if (isLoading) {
    return <div>Loading...</div>; // Or a proper loading component
  }

  return (
    <Routes>
      <Route path="/" element={<Navigate to="/home" replace />} />
      <Route path="/login" element={<Login />} />
      <Route path="/home" element={<Home />} />
    </Routes>
  );
}

export default App;
