"use client" import { useEffect, useRef, useState } from "react" import { useRouter } from "next/navigation" import { useAuth } from "@/context/auth-context" import { Button } from "@/components/ui/button" import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card" import { Input } from "@/components/ui/input" import { Label } from "@/components/ui/label" import { Separator } from "@/components/ui/separator" import { Wallet, Mail, Lock, Loader2, CheckCircle2 } from "lucide-react" import { toast } from "react-hot-toast" export default function LoginPage() { const { user, firebaseUser, walletConnected, walletAddress, isLoadingAuth, authMethod, connectWallet, loginWithEmail } = useAuth() const router = useRouter() const hasRedirected = useRef(false) const [email, setEmail] = useState("") const [password, setPassword] = useState("") const [isEmailLogin, setIsEmailLogin] = useState(false) const [isSubmittingEmail, setIsSubmittingEmail] = useState(false) // ✅ FIXED: More comprehensive redirect logic with debug logging useEffect(() => { console.log("🔍 Login page - checking auth state:", { isLoadingAuth, hasRedirected: hasRedirected.current, user: !!user, firebaseUser: !!firebaseUser, walletConnected, walletAddress, authMethod }) // Don't redirect if still loading or already redirected if (isLoadingAuth || hasRedirected.current) { console.log("⏳ Skipping redirect - loading or already redirected") return } // Check for successful authentication const isMetaMaskAuth = walletConnected && walletAddress && user && authMethod === "metamask" const isFirebaseAuth = firebaseUser && authMethod === "firebase" const isAuthenticated = isMetaMaskAuth || isFirebaseAuth console.log("🔍 Authentication check:", { isMetaMaskAuth, isFirebaseAuth, isAuthenticated }) if (isAuthenticated && !hasRedirected.current) { console.log("✅ User authenticated - redirecting to dashboard...") hasRedirected.current = true // Add a small delay to ensure state is fully updated setTimeout(() => { router.replace("/dashboard") }, 100) } }, [ user, firebaseUser, walletConnected, walletAddress, authMethod, isLoadingAuth, router ]) // ✅ FIXED: Include all necessary dependencies // ✅ Handle MetaMask connection with immediate redirect check const handleMetaMaskLogin = async () => { try { console.log("🦊 Starting MetaMask login...") await connectWallet() console.log("🦊 MetaMask login completed, checking for redirect...") // Force a redirect check after a short delay setTimeout(() => { const isAuth = walletConnected && walletAddress && user && authMethod === "metamask" if (isAuth && !hasRedirected.current) { console.log("🔄 Force redirecting after MetaMask success...") hasRedirected.current = true router.replace("/dashboard") } }, 500) } catch (error) { console.error("❌ MetaMask login failed:", error) } } // ✅ Handle email login const handleEmailLogin = async (e: React.FormEvent) => { e.preventDefault() if (!email.trim() || !password.trim()) { toast.error("Please enter both email and password") return } setIsSubmittingEmail(true) try { await loginWithEmail(email, password) // Redirect will be handled by useEffect } catch (error: any) { console.error("❌ Email login failed:", error) toast.error(error.message || "Login failed") } finally { setIsSubmittingEmail(false) } } // ✅ Show success state when authenticated but not yet redirected const isAuthenticated = (walletConnected && walletAddress && user) || firebaseUser if (isAuthenticated && !hasRedirected.current) { return (
Login Successful! ✅

{authMethod === "metamask" ? `🦊 MetaMask connected: ${walletAddress?.slice(0, 6)}...${walletAddress?.slice(-4)}` : `📧 Email: ${firebaseUser?.email}` }

Redirecting to dashboard...
{/* Manual redirect button as backup */}
) } // ✅ Show login form return (
Welcome to OpenLearnX! 🎓 {/* MetaMask Login */}

✨ Recommended: Get Web3 features and blockchain verification!

{/* Email Login */}
{isEmailLogin && (
setEmail(e.target.value)} placeholder="Enter your email" disabled={isSubmittingEmail || isLoadingAuth} required />
setPassword(e.target.value)} placeholder="Enter your password" disabled={isSubmittingEmail || isLoadingAuth} required />
)}
) }