"use client";

import { useEffect } from "react";
import { useRouter } from "next/navigation";
import { createClient } from "@/lib/supabase/client";
import { Loader2 } from "lucide-react";

export default function VerifyInvitePage() {
  const router = useRouter();
  const supabase = createClient();

  useEffect(() => {
    // The Supabase client automatically parses the `#access_token` from the URL
    // and establishes the session. We just need to wait for it.
    const {
      data: { subscription },
    } = supabase.auth.onAuthStateChange((event, session) => {
      if (event === "SIGNED_IN" || session) {
        // Session established! Redirect to the accept-invite page
        router.push("/accept-invite");
      }
    });

    // Fallback: If no session is found after a short delay, the link might be invalid
    const timer = setTimeout(async () => {
      const { data } = await supabase.auth.getSession();
      if (!data.session) {
        router.push("/login?error=Invalid+or+expired+invite+link");
      }
    }, 2000);

    return () => {
      subscription.unsubscribe();
      clearTimeout(timer);
    };
  }, [router, supabase]);

  return (
    <div className="flex min-h-screen items-center justify-center bg-background">
      <div className="flex flex-col items-center space-y-4">
        <Loader2 className="size-8 animate-spin text-brand-orange" />
        <h2 className="text-xl font-medium tracking-tight text-foreground">
          Verifying secure invite...
        </h2>
        <p className="text-sm text-muted-foreground">
          Please wait while we authenticate your link.
        </p>
      </div>
    </div>
  );
}
