"use client" import { useState, useEffect } 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, AlertCircle, CheckCircle2 } from "lucide-react" import { toast } from "react-hot-toast" export function LoginComponent() { const { connectWallet, loginWithEmail, isLoadingAuth, walletConnected, walletAddress, user, 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 [connectionStatus, setConnectionStatus] = useState<'idle' | 'connecting' | 'connected' | 'error'>('idle') // ✅ Check if user is already authenticated useEffect(() => { if (!isLoadingAuth) { if (walletConnected && walletAddress) { console.log('✅ MetaMask already connected:', walletAddress) setConnectionStatus('connected') toast.success("Already connected to MetaMask!") router.push("/dashboard") } else if (firebaseUser) { console.log('✅ Firebase user already logged in:', firebaseUser.email) router.push("/dashboard") } } }, [isLoadingAuth, walletConnected, walletAddress, firebaseUser, router]) const handleWalletConnect = async () => { setIsConnectingWallet(true) setConnectionStatus('connecting') 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.") setConnectionStatus('error') return } const success = await connectWallet() if (success) { setConnectionStatus('connected') console.log('✅ MetaMask connection successful') toast.success("MetaMask connected successfully! 🦊") // Small delay to ensure state is updated setTimeout(() => { router.push("/dashboard") }, 1000) } else { setConnectionStatus('error') toast.error("Failed to connect MetaMask. Please try again.") } } catch (error: any) { console.error('❌ Wallet connection error:', error) setConnectionStatus('error') if (error.message?.includes('User rejected')) { toast.error("Connection cancelled by user.") } else if (error.message?.includes('MetaMask not detected')) { toast.error("Please install MetaMask extension.") } else { toast.error("MetaMask connection failed. Please try again.") } } finally { setIsConnectingWallet(false) } } const handleEmailLogin = async (e: React.FormEvent) => { e.preventDefault() if (!email.trim() || !password.trim()) { toast.error("Please enter both email and password") return } if (!email.includes('@')) { toast.error("Please enter a valid email address") return } try { console.log('📧 Attempting email login for:', email) await loginWithEmail(email, password) toast.success("Logged in successfully!") router.push("/dashboard") } catch (error: any) { console.error('❌ Email login failed:', error) toast.error(error.message || "Login failed. Please check your credentials.") } } // ✅ Show connected state if already authenticated if (connectionStatus === 'connected' || (walletConnected && walletAddress)) { return (
MetaMask Connected! 🦊
🦊 {walletAddress?.slice(0, 6)}...{walletAddress?.slice(-4)}
) } return (
Welcome to OpenLearnX! 🎓

Connect your MetaMask wallet or login with email

{/* MetaMask Login - Primary Option */}

✨ Recommended: Get Web3 features, blockchain verification, and token rewards!

or
{/* Email Login - Alternative Option */}
{isEmailLogin && (
setEmail(e.target.value)} placeholder="Enter your email" disabled={isLoadingAuth} required />
setPassword(e.target.value)} placeholder="Enter your password" disabled={isLoadingAuth} required />
)}
{/* MetaMask Installation Help */} {typeof window !== 'undefined' && !window.ethereum && ( MetaMask not detected. )} {/* Connection Status */} {connectionStatus === 'error' && ( Connection failed. Please make sure MetaMask is unlocked and try again. )}

New to OpenLearnX? Your account will be created automatically upon first login.

) }