/**
 * @license
 * SPDX-License-Identifier: Apache-2.0
 */

import type { ReactNode } from "react";
import { BrowserRouter, Navigate, Routes, Route } from "react-router-dom";
import Layout from "./components/Layout";
import Dashboard from "./pages/Dashboard";
import Expansion from "./pages/Expansion";
import Opportunities from "./pages/Opportunities";
import Work from "./pages/Work";
import Profile from "./pages/Profile";
import { ThemeProvider } from "./components/ThemeProvider";
import LoginPage from "./pages/Login";
import WecomLoginCallbackPage from "./pages/WecomLoginCallback";
import { isAuthed } from "./lib/auth";

function RequireAuth({ children }: { children: ReactNode }) {
  if (!isAuthed()) {
    return <Navigate to="/login" replace />;
  }

  return children;
}

export default function App() {
  return (
    <ThemeProvider defaultTheme="light" storageKey="crm-theme">
      <BrowserRouter>
        <Routes>
          <Route path="/login" element={<LoginPage />} />
          <Route path="/login/wecom" element={<WecomLoginCallbackPage />} />
          <Route
            path="/"
            element={
              <RequireAuth>
                <Layout />
              </RequireAuth>
            }
          >
            <Route index element={<Dashboard />} />
            <Route path="expansion" element={<Expansion />} />
            <Route path="opportunities" element={<Opportunities />} />
            <Route path="work/*" element={<Work />} />
            <Route path="profile" element={<Profile />} />
          </Route>
        </Routes>
      </BrowserRouter>
    </ThemeProvider>
  );
}
