"use client";

// ---------------------------------------------------------------------------
// AuthGate — client-side route protection for authenticated app routes
// ---------------------------------------------------------------------------
// Identity is owned by Ory Kratos. Route protection is done by checking the
// live Kratos session via `whoami()`:
//   - 200 / active session  -> render the protected content
//   - no session            -> redirect to /login
//
// The Next.js middleware does a cheap cookie-presence pre-filter, but only a
// `whoami` call can confirm the session is actually valid (not expired). This
// gate is the authoritative check for the browser.
// ---------------------------------------------------------------------------

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { Loader2 } from "lucide-react";

import { useAuthStore } from "@/stores/auth";

export function AuthGate({ children }: { children: React.ReactNode }) {
  const router = useRouter();
  const hydrate = useAuthStore((s) => s.hydrate);
  const [checked, setChecked] = useState(false);
  const [allowed, setAllowed] = useState(false);

  useEffect(() => {
    let cancelled = false;

    hydrate().then(() => {
      if (cancelled) return;
      const { isAuthenticated } = useAuthStore.getState();
      if (isAuthenticated) {
        setAllowed(true);
        setChecked(true);
      } else {
        // No valid Kratos session — bounce to login.
        router.replace("/login");
      }
    });

    return () => {
      cancelled = true;
    };
  }, [hydrate, router]);

  if (!checked || !allowed) {
    return (
      <div className="flex min-h-screen items-center justify-center bg-background">
        <Loader2 className="size-6 animate-spin text-muted-foreground" />
      </div>
    );
  }

  return <>{children}</>;
}
