"use client";

import { useSession } from "next-auth/react";
import { useRouter, useSearchParams } from "next/navigation";
import { useEffect, Suspense } from "react";
import NextAuthComponent from "@/app/components/NextAuthComponent";

function deriveWorkspace(email: string): string {
  return email.split("@")[0].toLowerCase().replace(/[^a-z0-9]+/g, "-") + "-account";
}

function AuthPageInner() {
  const { data: session, status } = useSession();
  const router = useRouter();
  const searchParams = useSearchParams();

  useEffect(() => {
    if (status === "authenticated" && session?.user?.email) {
      const callbackUrl = searchParams.get("callbackUrl");
      // Only follow external callbackUrls we control (Theia subdomain)
      if (callbackUrl && callbackUrl.startsWith("https://theia.vibnai.com")) {
        window.location.href = callbackUrl;
      } else {
        const workspace = deriveWorkspace(session.user.email);
        router.push(`/${workspace}/projects`);
      }
    }
  }, [status, session, router, searchParams]);

  if (status === "loading") {
    return (
      <div className="flex min-h-screen items-center justify-center bg-background">
        <div className="text-center">
          <div className="h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent mx-auto mb-4" />
          <p className="text-muted-foreground">Loading authentication...</p>
        </div>
      </div>
    );
  }

  return <NextAuthComponent />;
}

export default function AuthPage() {
  return (
    <Suspense>
      <AuthPageInner />
    </Suspense>
  );
}
