import { type ReactNode, useRef } from "react";
import { Navigate } from "react-router-dom";
import { useAuth } from "./AuthContext";

/**
 * Route guard for pages that make no sense to an already-authenticated
 * visitor (`/login`, `/signup`). Mirrors {@link RequireAuth}'s waiting
 * behavior while the initial session check is pending.
 *
 * The redirect decision is latched exactly once, the first moment the
 * initial `isLoading` check resolves — deliberately *not* reactive to
 * `user` changing afterward. Without this, a guarded page's own action
 * that authenticates the visitor (e.g. `SignupPage`'s submit handler
 * calling `signup()`, which sets `user`, then explicitly navigating
 * elsewhere) races this guard: `user` becoming truthy while still mounted
 * fires this component's own `<Navigate to="/">`, competing with — and
 * sometimes winning against — the page's explicit `navigate(...)` call to
 * a different destination. Previously invisible only because the old
 * `SignupPage` happened to navigate to the same place ("/") this guard
 * does; became visible once it needed to route to `/onboarding/foyer`
 * instead.
 */
export function RedirectIfAuthenticated({ children }: { children: ReactNode }) {
  const { user, isLoading } = useAuth();
  const shouldRedirect = useRef<boolean | null>(null);

  if (!isLoading && shouldRedirect.current === null) {
    shouldRedirect.current = user !== null;
  }

  if (isLoading || shouldRedirect.current === null) {
    return null;
  }
  if (shouldRedirect.current) {
    return <Navigate to="/" replace />;
  }
  return <>{children}</>;
}
