"use client";

import { getSession } from "next-auth/react";
import { useSearchParams } from "next/navigation";
import { useRouter } from "next/navigation";
import { useEffect, useState, type ReactNode } from "react";

/**
 * Client-side only: redirect to "/" when user is authenticated and this page
 * was not opened after a 401 (session=expired). Uses getSession() so it works
 * without SessionProvider (login page is outside (main)). useSearchParams() so
 * it works in production where server searchParams can be undefined.
 */
export default function LoginRedirectIfAuthenticated({
  children,
}: {
  children: ReactNode;
}) {
  const searchParams = useSearchParams();
  const router = useRouter();
  const [checked, setChecked] = useState(false);

  useEffect(() => {
    let cancelled = false;
    getSession().then((session) => {
      if (cancelled) return;
      setChecked(true);
      if (!session) return;
      const sessionExpired = searchParams.get("session") === "expired";
      if (!sessionExpired) {
        router.replace("/");
      }
    });
    return () => {
      cancelled = true;
    };
  }, [searchParams, router]);

  if (!checked) return <>{children}</>;
  return <>{children}</>;
}
