"use client";

import { useEffect } from "react";
import { useRouter } from "next/navigation";
import { useAuth } from "@abe-kap/appshell-sdk/react";
import { isShellConfigured } from "@/lib/appshell";

/**
 * Client gate for the dashboard. When the Shell is live, an unauthenticated
 * visitor is bounced to the portal; while the session is resolving we hold a
 * lightweight splash. When the Shell is NOT configured this is a pass-through,
 * so the existing mock demo (any login → /dashboard) keeps working unchanged.
 */
export function AuthGate({ children }: { children: React.ReactNode }) {
  const router = useRouter();
  const { status } = useAuth();
  const shell = isShellConfigured();

  useEffect(() => {
    if (shell && status === "unauthenticated") router.replace("/portal/login");
  }, [shell, status, router]);

  if (shell && status !== "authenticated") {
    return (
      <div style={{ minHeight: "60vh", display: "grid", placeItems: "center", color: "var(--muted, #888)" }}>
        {status === "loading" ? "Loading your workspace…" : "Redirecting to sign in…"}
      </div>
    );
  }
  return <>{children}</>;
}
