'use client';

import { useEffect } from 'react';
import { usePathname, useRouter } from 'next/navigation';
import { useAuth } from '@/contexts/AuthContext';
import { isGatedRoute } from '@/lib/routes';

/**
 * Client-side auth gate (§12). Our session lives in the Supabase client
 * (localStorage), not an httpOnly cookie a server middleware could read — so
 * the gate runs here, in the browser, on top of the existing Supabase auth.
 *
 * Gated routes (a user's own ledger / tracker / account / alerts — see
 * lib/routes.js) bounce signed-out visitors to /login, remembering where they
 * were headed via the `?next=` param the login page already consumes. We wait
 * for auth to finish loading before deciding, so a logged-in user is never
 * flashed to /login on a hard refresh.
 */
export default function AuthGate({ children }: { children: React.ReactNode }) {
  const { user, loading } = useAuth();
  const pathname = usePathname() || '';
  const router = useRouter();

  useEffect(() => {
    if (loading) return;
    if (!user && isGatedRoute(pathname)) {
      const next = encodeURIComponent(pathname);
      router.replace(`/login?next=${next}`);
    }
  }, [user, loading, pathname, router]);

  return <>{children}</>;
}
