"use client" import { useState, useEffect, useRef } from "react" import { useRouter } from "next/navigation" import { useAuth } from "@/context/auth-context" import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card" import { Button } from "@/components/ui/button" import { Input } from "@/components/ui/input" import { Label } from "@/components/ui/label" import { Separator } from "@/components/ui/separator" import { Alert, AlertDescription } from "@/components/ui/alert" import { Wallet, Mail, Lock, Loader2, Shield, CheckCircle2, AlertCircle } from "lucide-react" import { toast } from "react-hot-toast" export default function LoginPage() { const { connectWallet, loginWithEmail, isLoadingAuth, walletConnected, walletAddress, firebaseUser, authMethod } = useAuth() const router = useRouter() const [email, setEmail] = useState("") const [password, setPassword] = useState("") const [isEmailLogin, setIsEmailLogin] = useState(false) const [isConnectingWallet, setIsConnectingWallet] = useState(false) const [isSubmittingEmail, setIsSubmittingEmail] = useState(false) const hasRedirected = useRef(false) // ✅ Check for existing authentication useEffect(() => { if (hasRedirected.current || isLoadingAuth) return const checkAuth = setTimeout(() => { if (isLoadingAuth) return const isAuthenticated = (walletConnected && walletAddress) || firebaseUser if (isAuthenticated && !hasRedirected.current) { console.log('✅ User already authenticated, redirecting to dashboard...') hasRedirected.current = true router.replace("/dashboard") } }, 500) return () => clearTimeout(checkAuth) }, [isLoadingAuth, walletConnected, walletAddress, firebaseUser, router]) // ✅ Handle MetaMask connection const handleWalletConnect = async () => { if (isConnectingWallet || isLoadingAuth) return setIsConnectingWallet(true) try { console.log('🦊 Starting MetaMask connection...') // Check if MetaMask is installed if (typeof window !== 'undefined' && !window.ethereum) { toast.error("MetaMask not detected. Please install MetaMask extension.") window.open('https://metamask.io/download/', '_blank') return } const success = await connectWallet() if (success) { console.log('✅ MetaMask connection successful') // Redirect will be handled by useEffect } } catch (error: any) { console.error('❌ Wallet connection error:', error) } finally { setIsConnectingWallet(false) } } // ✅ Handle email login const handleEmailLogin = async (e: React.FormEvent) => { e.preventDefault() if (isSubmittingEmail || isLoadingAuth) return 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. Please check your credentials.") } finally { setIsSubmittingEmail(false) } } // Show connected state if ((walletConnected && walletAddress) || firebaseUser) { return (
{walletConnected ? "MetaMask Connected! 🦊" : "Email Login Successful! 📧"} {walletConnected ? `🦊 ${walletAddress?.slice(0, 6)}...${walletAddress?.slice(-4)}` : `📧 ${firebaseUser?.email}` }
) } // Show loading while initializing if (isLoadingAuth) { return (

Initializing...

) } 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 || isConnectingWallet} required />
setPassword(e.target.value)} placeholder="Enter your password" disabled={isSubmittingEmail || isConnectingWallet} required />
)}
{/* MetaMask Installation Help */} {typeof window !== 'undefined' && !window.ethereum && ( MetaMask not detected. )}
) }