import { Navigate, Outlet, useLocation } from "react-router-dom";

function getCookie(name: string): string | null {
  const nameEQ = name + "=";
  const ca = document.cookie.split(";").map((c) => c.trim());
  for (const c of ca) {
    if (c.indexOf(nameEQ) === 0) return decodeURIComponent(c.substring(nameEQ.length));
  }
  return null;
}

const ACCESS_COOKIE = "access_token";

export default function PrivateRoute() {
  const location = useLocation();
  const isLoggedIn = !!getCookie(ACCESS_COOKIE);

  if (!isLoggedIn) {
    return <Navigate to="/login" replace state={{ from: location }} />;
  }
  return <Outlet />;
}
