"use client";

import { useEffect, Suspense } from "react";
import { useSearchParams } from "next/navigation";

function AuthCallbackContent() {
  const searchParams = useSearchParams();

  useEffect(() => {
    // Get the redirect URL from query params
    const redirectUrl = searchParams.get("redirect") || "/account/webinars";
    
    // Check if user is authenticated by fetching session
    const checkAuth = async () => {
      try {
        const res = await fetch("/api/auth/me");
        const data = await res.json();
        
        if (data.user) {
          // User is authenticated, redirect to the specified URL
          window.location.href = redirectUrl;
        } else {
          // Not authenticated, redirect to signin
          window.location.href = `/signin?redirect=${encodeURIComponent(redirectUrl)}`;
        }
      } catch (error) {
        // Error checking auth, redirect to signin
        window.location.href = `/signin?redirect=${encodeURIComponent(redirectUrl)}`;
      }
    };

    checkAuth();
  }, [searchParams]);

  return (
    <div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-primary via-primary-dark to-primary-dark">
      <div className="text-center text-white space-y-4">
        <div className="inline-block animate-spin">
          <div className="text-6xl">⏳</div>
        </div>
        <h1 className="text-3xl font-bold">Authenticating...</h1>
        <p className="text-white/80">Please wait while we complete your authentication</p>
      </div>
    </div>
  );
}

export default function AuthCallbackPage() {
  return (
    <Suspense fallback={
      <div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-primary via-primary-dark to-primary-dark">
        <div className="text-center text-white space-y-4">
          <div className="inline-block animate-spin">
            <div className="text-6xl">⏳</div>
          </div>
          <h1 className="text-3xl font-bold">Loading...</h1>
        </div>
      </div>
    }>
      <AuthCallbackContent />
    </Suspense>
  );
}
