"use client";

import { useEffect } from "react";
import { useRouter } from "next/navigation";

/**
 * Redirects unauthenticated visits to the sign-in screen (/) — the route groups
 * put the login page at the root — remembering where they came from.
 * The SessionProvider is the source of truth: it already validated the token or
 * dispatched a session-expired cleanup on failure.
 */
export function RequireAuth({
  tokenPresent,
  loading,
  children,
}: {
  tokenPresent: boolean;
  loading: boolean;
  children: React.ReactNode;
}) {
  const router = useRouter();

  useEffect(() => {
    if (!loading && !tokenPresent) {
      const next = encodeURIComponent(window.location.pathname + window.location.search);
      router.replace(next && next !== "%2F" ? `/?next=${next}` : "/");
    }
  }, [loading, tokenPresent, router]);

  if (loading || !tokenPresent) {
    return (
      <div className="flex min-h-[60vh] items-center justify-center" role="status" aria-label="Loading">
        <span className="h-8 w-8 animate-spin rounded-full border-2 border-primary border-t-transparent" />
      </div>
    );
  }

  return <>{children}</>;
}