'use client';

import {useEffect} from 'react';
import {useRouter, useSearchParams} from 'next/navigation';
import {Center} from '@astryxdesign/core/Center';
import {Spinner} from '@astryxdesign/core/Spinner';
import {useSession} from '@/features/auth/providers/SessionProvider';
import {resolveRedirectTarget} from '@/features/auth/services/redirectTarget';

/**
 * The mirror of AuthGuard: keeps a signed-in user OFF the sign-in screen.
 *
 * The proxy already redirects /login → /dashboard for a request carrying a
 * valid cookie. This covers the case the proxy cannot see: a client-side
 * navigation back to /login after logging in within the same page session.
 * Offering the form again to someone who is already authenticated reads as the
 * login having failed.
 *
 * While `loading`, the form is NOT rendered. Painting it and then yanking it
 * away is worse than a beat of spinner, and it invites someone to start typing
 * into a form that is about to disappear.
 */
export function GuestGuard({children}: {children: React.ReactNode}) {
  const {status} = useSession();
  const router = useRouter();
  const searchParams = useSearchParams();

  useEffect(() => {
    if (status !== 'authenticated') return;
    // The SAME destination the login form resolves. These two redirects race
    // on a successful sign-in, and a hardcoded /dashboard here silently threw
    // away the deep link the proxy had preserved in `?next=`.
    router.replace(resolveRedirectTarget(searchParams.get('next')));
  }, [status, router, searchParams]);

  if (status !== 'unauthenticated') {
    return (
      <Center height="100vh" role="status" aria-label="Checking your session">
        <Spinner size="lg" />
      </Center>
    );
  }

  return <>{children}</>;
}
