import { createBrowserRouter, Navigate } from "react-router";
import Login from "./components/Login";
import Main from "./components/Main";

const isAuthenticated = () => {
  return localStorage.getItem("chatbot_user") !== null;
};

const ProtectedRoute = ({ children }: { children: React.ReactNode }) => {
  return isAuthenticated() ? children : <Navigate to="/login" replace />;
};

const PublicRoute = ({ children }: { children: React.ReactNode }) => {
  return !isAuthenticated() ? children : <Navigate to="/" replace />;
};

export const router = createBrowserRouter([
  {
    path: "/login",
    element: (
      <PublicRoute>
        <Login />
      </PublicRoute>
    ),
  },
  {
    path: "/",
    element: (
      <ProtectedRoute>
        <Main />
      </ProtectedRoute>
    ),
  },
  {
    path: "*",
    element: <Navigate to="/" replace />,
  },
]);
