"use client";

import { shouldRedirectWhenLoggedIn } from "@/components/shared/authRedirect";
import { useAuthStore } from "@/store/authStore";
import { useSessionReady } from "@/store/useSessionReady";
import { useRouter } from "next/navigation";
import { useEffect } from "react";

/**
 * Redirects already-authenticated users away from auth pages (login, join, etc.)
 * to the homepage — mirrors the React app's RedirectIfLoggedIn component.
 */
export default function RedirectIfLoggedIn({
  children,
}: {
  children: React.ReactNode;
}) {
  const user = useAuthStore((s) => s.user);
  /* BE-129 — set by the header's "sign in with another account", and the one
     case where a signed-in reader is *meant* to be on this form. */
  const addingAccount = useAuthStore((s) => s.addingAccount);
  const sessionReady = useSessionReady();
  const router = useRouter();

  const redirect = shouldRedirectWhenLoggedIn({
    sessionReady,
    signedIn: Boolean(user),
    addingAccount,
  });

  useEffect(() => {
    /* Not while the render is still on the server snapshot — see the longer
       note in `ProtectedRoute`. Here the cost of acting early would be the
       inverse: a signed-*out* visitor bounced off the sign-in form. */
    if (redirect) router.replace("/");
  }, [redirect, router]);

  /*
   * BE-129 — **nothing clears the add-another-account intent here.**
   *
   * It used to be cleared in an unmount cleanup, on the reasoning that leaving
   * the auth group means the journey was abandoned. That broke the feature
   * outright: Strict Mode is on by default under the App Router, so React
   * mounts, runs effects, **runs the cleanups**, and mounts again — the
   * intent was therefore cleared a moment after the screen opened, the effect
   * above re-ran with it false, and "sign in with another account" bounced
   * straight back home. It was wrong in principle too: an unmount is not a
   * decision by the reader, and React may remount for its own reasons.
   *
   * The intent is cleared where something actually happened instead:
   * `setUser` on a completed sign-in, and `logout` / `endSession` /
   * `signOutActiveAccount` on the way out. It is not persisted either, so a
   * reload drops it. The only cost of letting it linger is that `/login`
   * stays reachable in this tab for a reader who changed their mind, which
   * costs nothing.
   */

  /*
   * The form is rendered while the session is unknown, which is what the
   * server rendered — it has no way to know anyone is signed in. A signed-in
   * reader who lands here sees it for the one render before the redirect, as
   * they did before; what changed is that React is no longer told the two
   * renders agree when they do not.
   */
  if (redirect) return null;

  return <>{children}</>;
}
