import React, { useEffect, useState } from "react";
import { Navigate, useLocation } from "react-router-dom";
import {
  consumeTokenFromUrl,
  getMasterStoredAuth,
} from "hse-auth";

function buildReturnTo(location) {
  const path = `${location.pathname || "/"}${location.search || ""}`;
  if (!path.startsWith("/") || path.startsWith("//")) return "/";
  return path;
}

export default function ProtectedRoute({ children }) {
  const location = useLocation();
  const [ready, setReady] = useState(false);
  const [authed, setAuthed] = useState(false);

  useEffect(() => {
    let cancelled = false;

    (async () => {
      await consumeTokenFromUrl({ master: true });
      if (!cancelled) {
        setAuthed(Boolean(getMasterStoredAuth()?.token));
        setReady(true);
      }
    })();

    return () => {
      cancelled = true;
    };
  }, []);

  if (!ready) {
    return <div className="master-loading">Loading...</div>;
  }

  if (!authed) {
    const returnTo = buildReturnTo(location);
    const loginPath =
      returnTo && returnTo !== "/"
        ? `/login?returnTo=${encodeURIComponent(returnTo)}`
        : "/login";
    return <Navigate to={loginPath} replace />;
  }

  return <>{children}</>;
}
