"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, authMethod } = useAuth() const router = useRouter() const [email, setEmail] = useState("") const [password, setPassword] = useState("") const [isEmailLogin, setIsEmailLogin] = useState(false) const [isSignup, setIsSignup] = useState(false) const [username, setUsername] = useState("") const [isConnectingWallet, setIsConnectingWallet] = useState(false) const [connectionStatus, setConnectionStatus] = useState<'idle' | 'connecting' | 'connected' | 'error'>('idle') // ✅ Check if user is already authenticated useEffect(() => { if (!isLoadingAuth) { if (user && authMethod) { console.log('✅ User already authenticated:', authMethod) setConnectionStatus('connected') router.push("/dashboard") } } }, [isLoadingAuth, user, authMethod, 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') // Small delay to ensure state is updated setTimeout(() => { router.push("/dashboard") }, 1000) } else { setConnectionStatus('error') } } catch (error: any) { console.error('❌ Wallet connection error:', error) setConnectionStatus('error') } 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) const success = await loginWithEmail(email, password) if (success) { setTimeout(() => router.push("/dashboard"), 500) } } catch (error: any) { console.error('❌ Email login failed:', error) } } const { signupWithEmail } = useAuth() const handleEmailSignup = async (e: React.FormEvent) => { e.preventDefault() if (!email.trim() || !password.trim() || !username.trim()) { toast.error("Please fill in all fields") return } if (!email.includes('@')) { toast.error("Please enter a valid email address") return } if (password.length < 6) { toast.error("Password must be at least 6 characters") return } try { console.log('📧 Attempting email signup for:', email) const success = await signupWithEmail(email, password, username) if (success) { setTimeout(() => router.push("/dashboard"), 500) } } catch (error: any) { console.error('❌ Email signup failed:', error) } } // ✅ Show connected state if already authenticated if (user && authMethod) { return (
{authMethod === 'metamask' ? 'MetaMask Connected' : 'Logged In'}
{authMethod === 'metamask' && walletAddress ? ( <>{walletAddress.slice(0, 6)}...{walletAddress.slice(-4)} ) : ( <>{user.email} )}
) } ) } 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 && (
{/* Toggle between Login and Signup */}
{isSignup && (
setUsername(e.target.value)} placeholder="Choose a username" disabled={isLoadingAuth} required={isSignup} />
)}
setEmail(e.target.value)} placeholder="Enter your email" disabled={isLoadingAuth} required />
setPassword(e.target.value)} placeholder={isSignup ? "Create a password (min 6 characters)" : "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.

) }