'use client';

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

/**
 * Client-side half of route protection. The server half is src/proxy.ts.
 *
 * ── Why both ──────────────────────────────────────────────────────────────
 * The proxy is the one that MATTERS: it refuses to serve the route at all, so
 * there is nothing to defeat by disabling JavaScript. But it only runs on
 * navigations the server sees. This guard covers what happens afterwards — a
 * session that expires while a tab sits open, a logout in another tab, a
 * client-side route change within the already-loaded app. Without it, the
 * workspace would keep rendering against an identity that no longer exists
 * until something happened to hit the network.
 *
 * Treat this as a correctness guard, never as the security boundary. Anything
 * that must not leak is fetched through a route handler, and route handlers
 * check the session themselves.
 */
export function AuthGuard({children}: {children: React.ReactNode}) {
  const {status} = useSession();
  const router = useRouter();
  const pathname = usePathname();

  useEffect(() => {
    if (status !== 'unauthenticated') return;
    const next = pathname && pathname !== '/dashboard' ? `?next=${encodeURIComponent(pathname)}` : '';
    router.replace(`/login${next}`);
  }, [status, router, pathname]);

  // 'loading' means the bootstrap request is still in flight. Rendering the
  // workspace here would paint an empty-looking shell and then swap it, and
  // rendering the redirect would fire it for users who ARE signed in.
  if (status !== 'authenticated') {
    return (
      <Center height="100vh" role="status" aria-label="Checking your session">
        <Spinner size="lg" />
      </Center>
    );
  }

  return <>{children}</>;
}
